diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index ae2711ffcf..de310f7a32 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -36,9 +36,12 @@ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-objectstore", "registry-platform-oidc", + "registry-platform-posture", + "registry-platform-provision", "registry-platform-ratelimit", "registry-platform-resilience", "registry-platform-script", @@ -167,6 +170,66 @@ # change to either host runs them; the shard builds both before it tests. RSTACK_DEV_HOST_PACKAGES = frozenset({"registry-bregctl", "registry-caseworkctl"}) +# The acceptance journeys start every runtime and `*ctl` tool in their product +# column (products/platform/journeys/products.yaml; test_ci_changes.py checks +# this set against it), `rstack dev`, and the ThunderID tooling the product +# tools link for their development issuer. The starters the journeys copy +# live in product directories and product crates, whose paths already seed +# these packages. +JOURNEY_PACKAGES = frozenset( + { + "registry-adapter", + "registry-adapter-job", + "registry-adapterctl", + "registry-breg", + "registry-breg-mcp", + "registry-breg-review", + "registry-bregctl", + "registry-casework", + "registry-caseworkctl", + "registry-coordinator", + "registry-discovery", + "registry-discoveryctl", + "registry-documents", + "registry-documentsctl", + "registry-evidence", + "registry-evidence-oid4vci", + "registry-evidence-oid4vp", + "registry-evidencectl", + "registry-mcp", + "registry-messaging", + "registry-messagingctl", + "registry-render", + "registry-scheduling", + "registry-schedulingctl", + "registry-thunderid-tooling", + } +) | RSTACK_DEV_HARNESS_PACKAGES +# The journey scripts, their tables, the realm and the per-product inputs. +JOURNEY_INPUTS = ("products/platform/journeys/**",) + +# The token fixture corpus, read by the corpus test in +# registry-platform-testing and by the token characterisation test of every +# runtime that verifies a token. The corpus is not a crate, so its path names +# those crates directly instead of relying on the reverse-dependency closure. +TOKEN_FIXTURE_CORPUS = "products/platform/conformance/tokens/" +TOKEN_FIXTURE_PACKAGES = frozenset( + { + "registry-platform-testing", + "registry-adapter", + "registry-breg", + "registry-casework", + "registry-coordinator", + "registry-documents", + "registry-evidence", + "registry-evidence-oid4vci", + "registry-mcp-edge", + "registry-messaging", + "registry-render", + "registry-scheduling", + } +) + # The runtime configuration conformance gate reads the sources of the runtimes # it holds rows for, their generated runtime schemas, and the canonical shared # configuration blocks schema. A product that joins the gate joins this set. @@ -544,6 +607,49 @@ # spread across parallel `postgres:i/N` shard lanes — the runner's owned # target lists cover every test exactly once across the shard set. BREG_POSTGRES_SHARDS = 3 +# The packages whose provisioning journey runs against the contracts-journeys +# lane's TLS-only PostgreSQL service, and the inputs that select that lane. +PROVISION_JOURNEY_PACKAGES = ( + "registry-adapterctl", + "registry-bregctl", + "registry-caseworkctl", + "registry-coordinator", + "registry-documentsctl", + "registry-messagingctl", + "registry-schedulingctl", +) +PROVISION_JOURNEY_INPUTS = ( + *(f"crates/{package}/src/provision.rs" for package in PROVISION_JOURNEY_PACKAGES), + # Each journey's test file. The database-free `provision_cli.rs` stays out. + *( + f"crates/{package}/tests/provision_postgres.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-caseworkctl" + ), + "crates/registry-caseworkctl/tests/provision.rs", + "crates/registry-casework/migrations/**", + "crates/registry-documents/migrations/**", + "crates/registry-messaging/migrations/**", + "crates/registry-scheduling/migrations/**", + # What `apply` grants and what the start check reads, per product. + # The Adapter migrates and grants when it serves, not in a separate apply. + "crates/registry-adapter/src/serve.rs", + "crates/registry-casework/src/activation.rs", + "crates/registry-documents/src/activation.rs", + "crates/registry-messaging/src/activation.rs", + "crates/registry-scheduling/src/store/activation.rs", + # The Coordinator keeps its DDL in code, and dispatches its tool from cli.rs. + "crates/registry-coordinator/src/deployment.rs", + "crates/registry-coordinator/src/store.rs", + "crates/registry-coordinator/src/cli.rs", + # The tool dispatch of every other product. + *( + f"crates/{package}/src/lib.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-coordinator" + ), +) + BREG_CONTRACTS_LANES = ( "contracts", "contracts-journeys", @@ -1237,6 +1343,8 @@ def classify( seeds.update(MANIFEST_PACKAGES) elif path.startswith("products/platform/"): seeds.update(PLATFORM_PACKAGES) + if path.startswith(TOKEN_FIXTURE_CORPUS): + seeds.update(TOKEN_FIXTURE_PACKAGES) elif path.startswith("products/breg/"): seeds.update(BREG_PACKAGES) elif path.startswith("products/casework/"): @@ -1565,6 +1673,12 @@ def classify( or bool(affected & BREG_EVIDENCE_COMPOSITION_PACKAGES) ) + acceptance_journeys = integration and ( + complete + or any(matches(path, *JOURNEY_INPUTS) for path in paths) + or bool(affected & JOURNEY_PACKAGES) + ) + matrix = [] for shard_name, shard_packages in SHARDS.items(): selected = sorted(affected.intersection(shard_packages)) @@ -1595,6 +1709,17 @@ def classify( for path in paths ) ) + # The provisioning PostgreSQL suite runs in the contracts-journeys lane, + # after that lane's TLS proof makes its PostGIS 17 service TLS-only. It + # joins only the breg_contracts output: breg_integration and + # casework_postgres read the selection above, so the provisioning crate + # on its own does not select them. + # Each product's provisioning journey runs in the same lane after the + # suite, so a product's provision command, its journey, its migrations, its + # apply and start check or its tool's dispatch select the lane too. + provision_postgres = "registry-platform-provision" in affected or any( + matches(path, *PROVISION_JOURNEY_INPUTS) for path in paths + ) outputs = { "full_sweep": full_sweep, @@ -1616,7 +1741,7 @@ def classify( or bool(affected & DISCOVERY_PACKAGES) or any(matches(path, *DISCOVERY_PROVIDER_INPUTS) for path in paths) or any(matches(path, *DISCOVERY_TUTORIAL_INPUTS) for path in paths), - "breg_contracts": breg_contracts, + "breg_contracts": breg_contracts or provision_postgres, "evidence_contracts": bool(affected & EVIDENCE_PACKAGES), "evidence_assurance": evidence_assurance, "evidence_postgres": bool(affected & EVIDENCE_POSTGRES_PACKAGES), @@ -1659,6 +1784,7 @@ def classify( "render_tutorial": render_tutorial, "scheduling_tutorial": scheduling_tutorial, "breg_evidence_composition": breg_evidence_composition, + "acceptance_journeys": acceptance_journeys, "identifiers": identifiers, } return outputs diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 4a7a620b09..44661ebdf2 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -28,13 +28,18 @@ EVIDENCE_AUTHORING_GUIDE_IMPLEMENTATION_INPUTS, EVIDENCE_TUTORIAL_INPUTS, IDENTIFIER_CATALOG_INPUTS, + JOURNEY_PACKAGES, REGISTRY_RECORD_CROSS_PRODUCT_INPUTS, + TOKEN_FIXTURE_CORPUS, + TOKEN_FIXTURE_PACKAGES, BREG_PACKAGES, CASEWORK_PACKAGES, DOCUMENTS_PACKAGES, ADAPTER_PACKAGES, MESSAGING_PACKAGES, MESSAGING_TUTORIAL_INPUTS, + PROVISION_JOURNEY_INPUTS, + PROVISION_JOURNEY_PACKAGES, RENDER_TUTORIAL_INPUTS, SCHEDULING_TUTORIAL_INPUTS, STACK_CLIENT_PACKAGES, @@ -75,6 +80,114 @@ ) AUTHORING_SCHEMA_DIRECTORY = Path("crates/registry-evidencectl/schemas/authoring") +# The acceptance journeys' directory and the ratchet-mode options every CI +# call of a journey script carries. +JOURNEYS = Path("products/platform/journeys") +JOURNEY_RATCHET = "--expected products/platform/journeys/expected-failures.yaml --strict" +JOURNEY_SCRIPTS = { + "own-provider.sh": "own-provider", + "promote.sh": "own-provider", + "rstack-dev.sh": "rstack-dev", +} + +# The Base Registry Engine lane that runs the provisioning PostgreSQL suite +# after its own TLS proof. +PROVISION_POSTGRES_LANE = "contracts-journeys" + +# The steps that give a coverage job the provisioning suite's two TLS +# servers, in their order before the coverage run, and the step after it +# that removes the PostgreSQL 16 server. +PROVISION_SERVER_STEPS = ( + "Serve the provisioning PostGIS service over TLS", + "Start PostgreSQL 16 for the provisioning floor test", + "Serve PostgreSQL 16 over TLS for the provisioning floor test", + "Bundle the provisioning servers' CAs", +) +PROVISION_STOP_STEP = "Stop PostgreSQL 16 for the provisioning floor test" +# The steps a coverage job shares, key for key, with the contracts-journeys lane. +PROVISION_LANE_STEPS = PROVISION_SERVER_STEPS[1:3] + (PROVISION_STOP_STEP,) + + +def provision_test_variables() -> set[str]: + """Every PROVISION_TEST_* variable the provisioning PostgreSQL suite reads.""" + + return set( + re.findall( + r'"(PROVISION_TEST_[A-Z_]+)"', + Path("crates/registry-platform-provision/tests/postgres.rs").read_text( + encoding="utf-8" + ), + ) + ) + + +PROVISION_JOURNEY_STEP = "Product provisioning PostgreSQL journeys" + + +def provision_journeys() -> dict[str, tuple[str, tuple[str, ...]]]: + """Each product's provisioning journey: package, test target and tests. + + A journey is an integration test target that reads the shared provisioning + test environment. Its tests are every test in a file gated on + postgres-test as a whole, or the tests after the first postgres-test gate + in a file that also holds ungated command tests. + """ + + journeys = {} + for target in sorted(Path("crates").glob("*/tests/*.rs")): + package = target.parts[1] + text = target.read_text(encoding="utf-8") + if package == "registry-platform-provision" or "provision_test_env" not in text: + continue + gate = '#![cfg(feature = "postgres-test")]' + if gate not in text: + text = text[text.index('#[cfg(feature = "postgres-test")]') :] + tests = re.findall( + r"#\[(?:tokio::)?test[^\]]*\]\s*(?:#\[[^\]]*\]\s*)*(?:async\s+)?fn\s+(\w+)", + text, + ) + journeys[package] = (target.stem, tuple(tests)) + return journeys + + +def cargo_test_commands(run: str) -> list[str]: + """Each cargo test command in a run script, continuation lines joined.""" + + commands = [] + for line in run.replace("\\\n", " ").splitlines(): + for segment in re.split(r"\||&&|;", line): + if "cargo test" in segment: + commands.append(" ".join(segment.split())) + return commands + + +def journey_products() -> dict[str, Any]: + """The journeys' product column, read from its checked-in table.""" + + return yaml.safe_load((JOURNEYS / "products.yaml").read_text(encoding="utf-8")) + + +def without_dependency_edges(metadata: dict[str, Any]) -> dict[str, Any]: + """The same workspace with every dependency edge removed. + + A path then reaches only the packages the classifier seeds for it, so a + test sees the path mapping itself rather than what the reverse-dependency + closure adds. + """ + + return { + **metadata, + "packages": [ + {**package, "dependencies": []} for package in metadata["packages"] + ], + } + + +def folded_command(step: dict[str, Any]) -> str: + """A step's run text with continuation lines joined and spaces collapsed.""" + + return " ".join(step.get("run", "").replace("\\\n", " ").split()) + def config_conformance_runner() -> Any: """The configuration conformance corpus runner, loaded as a module.""" @@ -427,6 +540,9 @@ def test_deferred_ci_work_keeps_its_selector_and_explicit_status_guard( "breg-evidence-composition": ( "needs.changes.outputs.breg_evidence_composition == 'true'" ), + "acceptance-journeys": ( + "needs.changes.outputs.acceptance_journeys == 'true'" + ), "docs-archives": "needs.changes.outputs.docs_archives == 'true'", "config-conformance": ( "needs.changes.outputs.config_conformance == 'true'" @@ -547,6 +663,7 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "docs-required", @@ -626,6 +743,7 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "client-bindings", @@ -668,6 +786,7 @@ def test_final_aggregate_flattens_rust_results_with_equivalent_outcomes( "render-tutorial", "scheduling-tutorial", "breg-evidence-composition", + "acceptance-journeys", "evidence-anchors", "docs", "client-bindings", @@ -678,7 +797,7 @@ def test_final_aggregate_flattens_rust_results_with_equivalent_outcomes( final_needs, previous_final_needs.difference({"rust-result"}).union(rust_needs), ) - self.assertEqual(43, len(final_needs)) + self.assertEqual(44, len(final_needs)) # Platform line coverage publishes from main and the nightly sweep; # it does not hold the merge queue. self.assertNotIn("platform-coverage", final_needs) @@ -983,6 +1102,7 @@ def test_final_aggregate_refuses_a_selected_integration_job_that_skipped( "breg-tutorial": "breg_tutorial", "casework-tutorial": "casework_tutorial", "breg-evidence-composition": "breg_evidence_composition", + "acceptance-journeys": "acceptance_journeys", "deployment": "deployment", } @@ -1821,23 +1941,127 @@ def test_platform_coverage_has_the_shared_activation_database(self) -> None: def test_nightly_platform_coverage_has_the_pull_request_database(self) -> None: # The nightly platform shard runs the same --all-features build as # platform-coverage, whose PostgreSQL tests fail rather than skip - # without their database, so it needs the same service and URLs. + # without their databases, so it needs the same services, the same + # provisioning servers and the same test variables. pull_request = self.workflow_jobs["platform-coverage"] nightly = yaml.safe_load( Path(".github/workflows/nightly-rust-coverage.yml").read_text() )["jobs"]["rust"] self.assertEqual(nightly.get("services"), pull_request["services"]) - def database_urls(job: dict[str, Any], step_name: str) -> dict[str, str]: + def test_variables(job: dict[str, Any], step_name: str) -> dict[str, str]: step = next(step for step in job["steps"] if step.get("name") == step_name) return { name: value for name, value in step.get("env", {}).items() - if name.endswith("_DATABASE_URL") + if "_TEST_" in name } - expected = database_urls(pull_request, "Enforce platform line coverage") + expected = test_variables(pull_request, "Enforce platform line coverage") self.assertTrue(expected) - self.assertEqual(database_urls(nightly, "Run shard with coverage"), expected) + self.assertLessEqual(provision_test_variables(), set(expected)) + self.assertEqual(test_variables(nightly, "Run shard with coverage"), expected) + + # The provisioning servers' steps match key for key. In the nightly + # sweep only the platform shard, built with --all-features, runs them. + pull_request_steps = {step.get("name"): step for step in pull_request["steps"]} + nightly_names = [step.get("name") for step in nightly["steps"]] + nightly_steps = dict(zip(nightly_names, nightly["steps"])) + for name in (*PROVISION_SERVER_STEPS, PROVISION_STOP_STEP): + with self.subTest(step=name): + for key in ("id", "shell", "env", "run"): + self.assertEqual( + pull_request_steps[name].get(key), nightly_steps[name].get(key), key + ) + for name in PROVISION_SERVER_STEPS: + with self.subTest(step=name): + self.assertEqual("matrix.name == 'platform'", nightly_steps[name]["if"]) + self.assertEqual( + "always() && matrix.name == 'platform' && " + "steps.provision-postgres-16.outputs.container_id != ''", + nightly_steps[PROVISION_STOP_STEP]["if"], + ) + indices = [nightly_names.index(name) for name in PROVISION_SERVER_STEPS] + run = nightly_names.index("Run shard with coverage") + self.assertEqual(sorted(indices), indices) + self.assertLess(nightly_names.index("Checkout"), indices[0]) + self.assertLess(indices[-1], run) + self.assertLess(run, nightly_names.index(PROVISION_STOP_STEP)) + + def test_platform_coverage_serves_the_provisioning_suite(self) -> None: + # --all-features enables registry-platform-provision's postgres-test, + # whose suite fails rather than skips without its two TLS servers. + job = self.workflow_jobs["platform-coverage"] + lane = self.workflow_jobs["breg-contracts"] + service = job["services"]["postgis"] + self.assertEqual(lane["services"]["postgres"]["image"], service["image"]) + self.assertEqual(["5432/tcp"], service["ports"]) + + steps = job["steps"] + names = [step.get("name") for step in steps] + coverage = names.index("Enforce platform line coverage") + indices = [names.index(name) for name in PROVISION_SERVER_STEPS] + self.assertEqual(sorted(indices), indices) + self.assertLess(names.index("Checkout"), indices[0]) + self.assertLess(indices[-1], coverage) + stop = names.index(PROVISION_STOP_STEP) + self.assertLess(coverage, stop) + for index in indices: + with self.subTest(step=names[index]): + self.assertNotIn("if", steps[index]) + self.assertEqual( + "always() && steps.provision-postgres-16.outputs.container_id != ''", + steps[stop]["if"], + ) + + # The PostgreSQL 16 server is started, secured and removed exactly as + # the contracts-journeys lane does it. + lane_steps = {step.get("name"): step for step in lane["steps"]} + for name in PROVISION_LANE_STEPS: + with self.subTest(step=name): + for key in ("id", "shell", "env", "run"): + self.assertEqual( + lane_steps[name].get(key), steps[names.index(name)].get(key), key + ) + + # The service is made TLS-only by the lane's own script. + service_tls = steps[indices[0]] + self.assertEqual( + "${{ job.services.postgis.id }}", service_tls["env"]["SERVICE_CONTAINER_ID"] + ) + self.assertIn("BREG_TEST_TLS_SETUP_ONLY=1", folded_command(service_tls)) + self.assertIn( + "products/breg/scripts/test-postgres-tls.sh", folded_command(service_tls) + ) + + # The bundle joins the two CA files the TLS steps write. + bundle = steps[indices[3]] + self.assertEqual( + service_tls["env"]["SERVICE_CA_PEM_PATH"], bundle["env"]["SERVICE_CA_PEM_PATH"] + ) + self.assertEqual( + lane_steps[PROVISION_SERVER_STEPS[2]]["env"]["OLD_CA_PEM_PATH"], + bundle["env"]["OLD_CA_PEM_PATH"], + ) + self.assertIn( + 'cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}"', + bundle["run"], + ) + + # Every variable the suite reads is set on the coverage run; each URL + # verifies the server certificate and its host name. + env = steps[coverage]["env"] + self.assertEqual(bundle["env"]["BUNDLE_PATH"], env["PROVISION_TEST_DATABASE_CA"]) + self.assertEqual( + "postgresql://provision:provision_test@localhost:" + "${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full", + env["PROVISION_TEST_DATABASE_URL"], + ) + self.assertEqual( + "postgresql://provision:provision_test@localhost:" + "${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full", + env["PROVISION_TEST_OLD_DATABASE_URL"], + ) + self.assertLessEqual(provision_test_variables(), set(env)) def test_source_client_tutorial_includes_messaging_before_release_admission(self) -> None: script = next( @@ -2667,7 +2891,9 @@ def test_casework_task_approval_journey_runs_wherever_its_inputs_change( # The casework-postgres job owns the stock-issuer task approval # journey through Evidence, BReg, and Scheduling. It must run on every # change that selects the BReg product gate and on every change to the - # Scheduling runtime whose probe example the journey builds. + # Scheduling runtime whose probe example the journey builds. A change + # that joins the BReg contracts lane only for another product's + # provisioning journey does not select the BReg product gate. paths = [f"{root}/src/lib.rs" for root in self.workspace.roots.values()] paths.extend( ( @@ -2682,7 +2908,10 @@ def test_casework_task_approval_journey_runs_wherever_its_inputs_change( for path in paths: with self.subTest(path=path): outputs = classify(self.workspace, (path,)) - if outputs["breg_contracts"] or ( + provisioning_only = matches(path, *PROVISION_JOURNEY_INPUTS) and not ( + set(outputs["rust_packages"]) & BREG_PACKAGES + ) + if (outputs["breg_contracts"] and not provisioning_only) or ( "registry-scheduling" in outputs["rust_packages"] ): self.assertTrue(outputs["casework_postgres"]) @@ -3857,6 +4086,509 @@ def test_non_workflow_file_under_workflow_directory_stays_unselected( ) self.assertFalse(outputs["release_tool"]) + def test_journey_packages_are_the_journey_product_column(self) -> None: + column = journey_products()["products"] + products = { + package + for product in column + for package in (product["crate"], product["ctl"], *product["cargoPackages"]) + if package is not None + } + self.assertEqual( + products + | {"registry-rstack", "registry-rstack-dev", "registry-thunderid-tooling"}, + JOURNEY_PACKAGES, + ) + self.assertLessEqual(JOURNEY_PACKAGES, self.workspace.package_names) + + def test_acceptance_journeys_routing(self) -> None: + # Every package in the product column, and the rstack and ThunderID + # harness packages, selects the journeys in the merge queue. + for package in sorted(JOURNEY_PACKAGES): + path = f"{self.workspace.roots[package]}/Cargo.toml" + with self.subTest(path=path): + self.assertTrue(classify(self.workspace, (path,))["acceptance_journeys"]) + + # Without dependency edges a path reaches only what it seeds, so these + # select the journeys through their own mapping: the harness and its + # tables by path, each starter the journeys copy through the product + # directory or product crate that holds it. + edgeless = Workspace(without_dependency_edges(self.metadata)) + for path in ( + *sorted(path.as_posix() for path in JOURNEYS.iterdir() if path.is_file()), + "products/platform/journeys/own-provider.sh", + "products/platform/journeys/keycloak/realm.json", + "products/platform/journeys/projects/scheduling/runtime.yaml", + "crates/registry-bregctl/src/starters.rs", + "crates/registry-documentsctl/src/starter.rs", + "crates/registry-messagingctl/src/starter.rs", + "crates/registry-evidencectl/templates/starter/README.md", + "products/breg/evidence/starter/README.md", + "products/documents/examples/starter/documents.yaml", + "products/messaging/examples/starter/dev.yaml", + ): + with self.subTest(path=path): + self.assertTrue(classify(edgeless, (path,))["acceptance_journeys"]) + + # A platform path outside the journeys seeds only the platform crates, + # none of which the journeys start. + self.assertFalse( + classify(edgeless, ("products/platform/scripts/run-fuzz-smoke.sh",))[ + "acceptance_journeys" + ] + ) + # Review defers the journeys even for their own inputs. + self.assertFalse( + classify( + self.workspace, + ("products/platform/journeys/products.yaml",), + pull_request=True, + )["acceptance_journeys"] + ) + + def test_acceptance_journeys_job_runs_each_leg_in_ratchet_mode(self) -> None: + job = self.workflow_jobs["acceptance-journeys"] + self.assertEqual("Acceptance journeys (${{ matrix.title }})", job["name"]) + self.assertEqual("ubuntu-24.04", job["runs-on"]) + self.assertFalse(job["strategy"]["fail-fast"]) + self.assertEqual( + [ + {"leg": "own-provider", "title": "own-provider and promote"}, + {"leg": "rstack-dev", "title": "rstack dev"}, + ], + job["strategy"]["matrix"]["include"], + ) + # A leg that passes 40 minutes moves to the nightly sweep and ci:full, + # so the limit is that condition, and nothing retries. + self.assertEqual(40, job["timeout-minutes"]) + self.assertNotIn("continue-on-error", job) + steps = job["steps"] + for step in steps: + with self.subTest(step=step.get("name")): + self.assertNotIn("continue-on-error", step) + self.assertNotIn("retry", step.get("uses", "") + step.get("run", "")) + + def index_of(predicate: Any) -> int: + found = [index for index, step in enumerate(steps) if predicate(step)] + self.assertEqual(1, len(found)) + return found[0] + + # The build covers the product column's packages and features and + # rstack, so every binary the journeys start comes from this commit. + products = journey_products() + build = index_of(lambda step: folded_command(step).startswith("cargo build ")) + words = shlex.split(folded_command(steps[build])) + self.assertEqual(["cargo", "build", "--locked"], words[:3]) + self.assertEqual("--bins", words[-1]) + packages = {words[index + 1] for index, word in enumerate(words) if word == "-p"} + self.assertEqual( + { + package + for product in products["products"] + for package in product["cargoPackages"] + } + | {"registry-rstack"}, + packages, + ) + features = { + feature + for index, word in enumerate(words) + if word == "--features" + for feature in words[index + 1].split(",") + } + self.assertEqual( + { + feature + for product in products["products"] + for feature in product.get("cargoFeatures") or () + }, + features, + ) + for feature in sorted(features): + package, name = feature.split("/") + with self.subTest(feature=feature): + self.assertIn(name, self.workspace.packages[package]["features"]) + + # Keycloak comes from quay.io by the digest the product column pins. + image = products["ownProviderIssuer"]["image"] + self.assertRegex(image, r"^quay\.io/keycloak/keycloak:[0-9.]+@sha256:[0-9a-f]{64}$") + pull = index_of(lambda step: folded_command(step).startswith("docker pull ")) + self.assertEqual(f"docker pull {image}", folded_command(steps[pull])) + self.assertEqual("matrix.leg == 'own-provider'", steps[pull]["if"]) + + calls = { + script: index_of( + lambda step, script=script: f"products/platform/journeys/{script} " + in folded_command(step) + ) + for script in JOURNEY_SCRIPTS + } + for script, leg in JOURNEY_SCRIPTS.items(): + command = folded_command(steps[calls[script]]) + with self.subTest(script=script): + self.assertEqual(f"matrix.leg == '{leg}'", steps[calls[script]]["if"]) + self.assertTrue( + command.startswith(f"products/platform/journeys/{script} --all ") + ) + self.assertIn('--bin-dir "${GITHUB_WORKSPACE}/target/debug"', command) + self.assertIn(JOURNEY_RATCHET, command) + self.assertIn(f'--out "${{RUNNER_TEMP}}/journeys/{script[:-3]}"', command) + self.assertLess(build, calls[script]) + # Promote takes over the own-provider run that ended with --keep. + self.assertIn("--keep", folded_command(steps[calls["own-provider.sh"]])) + self.assertIn( + '--from "${RUNNER_TEMP}/journeys/own-provider"', + folded_command(steps[calls["promote.sh"]]), + ) + self.assertLess(pull, calls["own-provider.sh"]) + self.assertLess(calls["own-provider.sh"], calls["promote.sh"]) + + def test_changes_job_checks_the_journey_tables_on_every_pull_request(self) -> None: + steps = self.workflow_jobs["changes"]["steps"] + names = [step.get("name") for step in steps] + tables = steps[names.index("Test the acceptance journey tables")] + self.assertEqual( + "uv run --no-project --with PyYAML==6.0.2 python -m unittest " + "products/platform/journeys/test_journey_tables.py", + tables["run"], + ) + self.assertNotIn("if", tables) + self.assertNotIn("if", self.workflow_jobs["changes"]) + self.assertLess(names.index("Install uv"), names.index("Test the acceptance journey tables")) + + def test_token_fixture_packages_are_every_crate_that_characterises_tokens( + self, + ) -> None: + characterising = { + self.workspace.package_for_path(path.as_posix()) + for path in Path("crates").glob("*/**/token_characterisation.rs") + } + self.assertNotIn(None, characterising) + self.assertEqual( + characterising | {"registry-platform-testing"}, TOKEN_FIXTURE_PACKAGES + ) + self.assertTrue(Path(TOKEN_FIXTURE_CORPUS).is_dir()) + + def test_a_token_corpus_change_selects_every_crate_that_reads_it(self) -> None: + corpus = f"{TOKEN_FIXTURE_CORPUS}fixtures/entra-id-token.json" + edgeless = Workspace(without_dependency_edges(self.metadata)) + outputs = classify(edgeless, (corpus,)) + sharded = { + package + for entry in outputs["rust_matrix"]["include"] + for package in entry["packages"] + } + self.assertLessEqual(TOKEN_FIXTURE_PACKAGES, sharded) + # Elsewhere under products/platform/ seeds only the platform crates. + other = classify(edgeless, ("products/platform/scripts/run-fuzz-smoke.sh",)) + self.assertFalse( + (TOKEN_FIXTURE_PACKAGES - set(SHARDS["platform"])) + & set(other["rust_packages"]) + ) + # The real graph reaches them as well. + self.assertLessEqual( + TOKEN_FIXTURE_PACKAGES, set(classify(self.workspace, (corpus,))["rust_packages"]) + ) + + def test_platform_shard_runs_the_feature_gated_token_corpus_test(self) -> None: + # No platform crate enables token-fixtures, so the shard's own run + # skips the corpus test; this step runs it. + self.assertIn("registry-platform-testing", SHARDS["platform"]) + manifest = Path("crates/registry-platform-testing/Cargo.toml").read_text( + encoding="utf-8" + ) + self.assertIn( + '[[test]]\nname = "token_fixtures"\nrequired-features = ["token-fixtures"]', + manifest, + ) + steps = [ + step + for step in self.workflow_jobs["rust-tests"]["steps"] + if step.get("name") == "Test the token fixture corpus" + ] + self.assertEqual(1, len(steps)) + self.assertEqual( + "matrix.name == 'platform' && " + "contains(matrix.packages, 'registry-platform-testing')", + steps[0]["if"], + ) + self.assertEqual( + "cargo test --locked -p registry-platform-testing " + "--features token-fixtures --test token_fixtures", + steps[0]["run"], + ) + + def test_platform_shard_runs_the_feature_gated_refusal_trace_id_test(self) -> None: + # No platform crate enables refusal-trace-id, so the shard's own run + # compiles httpsec without the impl and skips its test; this step runs it. + self.assertIn("registry-platform-httpsec", SHARDS["platform"]) + manifest = Path("crates/registry-platform-httpsec/Cargo.toml").read_text( + encoding="utf-8" + ) + self.assertIn('refusal-trace-id = ["server", "dep:registry-platform-authcommon"]', manifest) + steps = [ + step + for step in self.workflow_jobs["rust-tests"]["steps"] + if step.get("name") == "Test the refusal trace id implementation" + ] + self.assertEqual(1, len(steps)) + self.assertEqual( + "matrix.name == 'platform' && " + "contains(matrix.packages, 'registry-platform-httpsec')", + steps[0]["if"], + ) + self.assertEqual( + "cargo test --locked -p registry-platform-httpsec " + "--features refusal-trace-id --lib", + steps[0]["run"], + ) + + def test_provisioning_changes_select_the_tls_postgres_lane(self) -> None: + # The suite runs in the contracts-journeys lane, which review keeps. + self.assertIn(PROVISION_POSTGRES_LANE, BREG_CONTRACTS_LANES[:2]) + # Without dependency edges the provisioning crate reaches nothing + # else, so its own mapping has to select the lane, not a dependent + # that happens to link it. + edgeless = Workspace(without_dependency_edges(self.metadata)) + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for path in ( + "crates/registry-platform-provision/src/lib.rs", + "crates/registry-platform-provision/tests/postgres.rs", + ): + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertTrue(outputs["breg_contracts"]) + self.assertIn( + PROVISION_POSTGRES_LANE, outputs["breg_contracts_lanes"] + ) + # The suite needs no other PostgreSQL job, so the provisioning crate on + # its own selects none. + alone = classify(edgeless, ("crates/registry-platform-provision/src/lib.rs",)) + self.assertFalse(alone["breg_integration"]) + self.assertFalse(alone["casework_postgres"]) + + def test_contracts_journeys_lane_runs_the_provisioning_postgres_suite( + self, + ) -> None: + steps = self.workflow_jobs["breg-contracts"]["steps"] + names = [step.get("name") for step in steps] + tls = names.index("Base Registry Engine PostgreSQL TLS proof") + start = names.index("Start PostgreSQL 16 for the provisioning floor test") + secure = names.index("Serve PostgreSQL 16 over TLS for the provisioning floor test") + suite = names.index("Provisioning PostgreSQL suite") + stop = names.index("Stop PostgreSQL 16 for the provisioning floor test") + self.assertLess(tls, start) + self.assertLess(start, secure) + self.assertLess(secure, suite) + self.assertLess(suite, stop) + lane = f"matrix.lane == '{PROVISION_POSTGRES_LANE}'" + for index in (start, secure, suite): + with self.subTest(step=names[index]): + self.assertEqual(lane, steps[index]["if"]) + self.assertEqual("provision-postgres-16", steps[start]["id"]) + self.assertEqual( + f"always() && {lane} && " + "steps.provision-postgres-16.outputs.container_id != ''", + steps[stop]["if"], + ) + + self.assertRegex( + steps[start]["run"], + r"image='docker\.io/library/postgres:16\.[0-9]+@sha256:[0-9a-f]{64}'", + ) + self.assertIn("--label org.registrystack.ci.postgres-service=true", folded_command(steps[start])) + self.assertIn("--publish 127.0.0.1::5432", folded_command(steps[start])) + + # The lane's own TLS script gives the old server a throwaway CA. + secure_command = folded_command(steps[secure]) + self.assertIn("BREG_TEST_TLS_SETUP_ONLY=1", secure_command) + self.assertIn("products/breg/scripts/test-postgres-tls.sh", secure_command) + + # Every variable the suite reads is set, each URL verifies the + # certificate and its host name, and a run that passes no test fails. + suite_run = steps[suite]["run"] + variables = provision_test_variables() + self.assertEqual( + { + "PROVISION_TEST_DATABASE_URL", + "PROVISION_TEST_DATABASE_CA", + "PROVISION_TEST_OLD_DATABASE_URL", + }, + variables, + ) + for variable in sorted(variables): + with self.subTest(variable=variable): + self.assertRegex(suite_run, rf"(?m)^export {variable}=\S") + self.assertEqual(2, suite_run.count("/postgres?sslmode=verify-full\"")) + # The suite target and the library's command tests, which need cli. + for target, log in (("--lib", "lib"), ("--test postgres", "suite")): + with self.subTest(target=target): + self.assertIn( + "cargo test --locked -p registry-platform-provision " + f"--features postgres-test,cli {target} " + f'| tee "${{RUNNER_TEMP}}/provision-postgres-{log}.log"', + folded_command(steps[suite]), + ) + self.assertIn( + "for target in lib suite; do grep -Eq " + "'^test result: ok\\. [1-9][0-9]* passed; 0 failed; 0 ignored' " + '"${RUNNER_TEMP}/provision-postgres-${target}.log"', + folded_command(steps[suite]), + ) + + stop_run = steps[stop]["run"] + self.assertIn("org.registrystack.ci.postgres-service", stop_run) + self.assertIn('docker rm --force "${CONTAINER_ID}"', stop_run) + + def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None: + # A package that adds a journey adds itself to the classifier's list. + journeys = provision_journeys() + self.assertEqual(set(PROVISION_JOURNEY_PACKAGES), set(journeys)) + edgeless = Workspace(without_dependency_edges(self.metadata)) + paths = [ + *(f"crates/{package}/src/provision.rs" for package in journeys), + *(f"crates/{package}/tests/{target}.rs" for package, (target, _) in journeys.items()), + "crates/registry-casework/migrations/0001_review_baseline.sql", + "crates/registry-documents/migrations/0001_documents.sql", + "crates/registry-messaging/migrations/0001_messaging.sql", + "crates/registry-scheduling/migrations/0001_scheduling.sql", + "crates/registry-casework/src/activation.rs", + "crates/registry-documents/src/activation.rs", + "crates/registry-messaging/src/activation.rs", + "crates/registry-scheduling/src/store/activation.rs", + "crates/registry-coordinator/src/deployment.rs", + "crates/registry-coordinator/src/store.rs", + "crates/registry-coordinator/src/cli.rs", + *( + f"crates/{package}/src/lib.rs" + for package in journeys + if package != "registry-coordinator" + ), + ] + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for path in paths: + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertTrue(outputs["breg_contracts"]) + self.assertIn( + PROVISION_POSTGRES_LANE, outputs["breg_contracts_lanes"] + ) + + def test_database_free_provisioning_tests_do_not_select_the_tls_postgres_lane( + self, + ) -> None: + # `provision_cli.rs` reads no database, so the ordinary package tests + # cover it and the TLS PostgreSQL journey need not run. The Base + # Registry Engine tool is left out: any change to a breg package + # selects the breg contracts for its own reasons. + edgeless = Workspace(without_dependency_edges(self.metadata)) + checked = 0 + for package in PROVISION_JOURNEY_PACKAGES: + path = f"crates/{package}/tests/provision_cli.rs" + if package == "registry-bregctl" or not Path(path).exists(): + continue + checked += 1 + for graph, workspace in (("real", self.workspace), ("edgeless", edgeless)): + for event, outputs in ( + ("pull_request", classify(workspace, (path,), pull_request=True)), + ("merge_group", classify(workspace, (path,))), + ): + with self.subTest(graph=graph, path=path, event=event): + self.assertFalse(outputs["breg_contracts"]) + self.assertGreater(checked, 0) + + def test_contracts_journeys_lane_runs_each_product_provisioning_journey( + self, + ) -> None: + steps = self.workflow_jobs["breg-contracts"]["steps"] + names = [step.get("name") for step in steps] + suite = names.index("Provisioning PostgreSQL suite") + journey = names.index(PROVISION_JOURNEY_STEP) + stop = names.index("Stop PostgreSQL 16 for the provisioning floor test") + self.assertLess(suite, journey) + self.assertLess(journey, stop) + step = steps[journey] + self.assertEqual(f"matrix.lane == '{PROVISION_POSTGRES_LANE}'", step["if"]) + + # The journeys read the two variables of the shared test helper, and + # the URL verifies the server certificate and its host name. + run = step["run"] + self.assertRegex( + run, + r'(?m)^export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@' + r'localhost:\$\{DATABASE_PORT\}/postgres\?sslmode=verify-full"$', + ) + self.assertRegex(run, r"(?m)^export PROVISION_TEST_DATABASE_CA=\S") + + journeys = provision_journeys() + command = folded_command(step) + for package, (target, _) in journeys.items(): + with self.subTest(package=package): + self.assertIn( + f"cargo test --locked -p {package} --features postgres-test " + f'--test {target} | tee "${{RUNNER_TEMP}}/provision-journey-{package}.log"', + command, + ) + # A run that selected no test still exits 0, so every log needs a pass + # count, no ignored test, and the journey's own line. + self.assertIn(f"for package in {' '.join(journeys)}; do", command) + self.assertIn( + "grep -Eq '^test result: ok\\. [1-9][0-9]* passed; 0 failed; 0 ignored' " + '"${log}"', + command, + ) + self.assertIn( + "grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " + "\\.\\.\\. ok$' \"${log}\"", + command, + ) + + def test_other_postgres_steps_leave_the_provisioning_journeys_to_the_tls_lane( + self, + ) -> None: + # Product PostgreSQL lanes serve plaintext, and the journeys refuse a + # server they cannot verify. A command there that runs a journey + # package's every test target skips the journey's tests. + journeys = provision_journeys() + sources = [] + for workflow in sorted(Path(".github/workflows").glob("*.yml")): + jobs = yaml.safe_load(workflow.read_text(encoding="utf-8"))["jobs"] + for job_name, job in jobs.items(): + for step in job.get("steps", []): + if step.get("name") != PROVISION_JOURNEY_STEP: + source = f"{workflow.name}:{job_name}:{step.get('name')}" + sources.append((source, step.get("run", ""))) + for script in sorted(Path("products").glob("*/scripts/*.sh")): + sources.append((str(script), script.read_text(encoding="utf-8"))) + + checked = 0 + for source, run in sources: + for command in cargo_test_commands(run): + for package, (target, tests) in journeys.items(): + if not re.search(rf"-p {re.escape(package)}(?=\s|$)", command): + continue + if "postgres-test" not in command: + continue + with self.subTest(source=source, package=package): + self.assertNotIn(f"--test {target} ", f"{command} ") + selectors = re.findall( + r"--(?:test|lib|bins?|examples?|doc)(?=\s|$)", command + ) + every_target = "--tests" in command or "--all-targets" in command + if every_target or not selectors: + checked += 1 + for test in tests: + self.assertIn(f"--skip {test}", command) + # The Messaging lane's messagingctl run is one such command. + self.assertGreaterEqual(checked, 1) + + def edit_lock_package(text: str, name: str, **fields: str) -> str: """Return the lockfile with one uniquely named package's fields replaced.""" @@ -4114,6 +4846,7 @@ def test_heavy_integration_waits_for_the_merge_queue_or_ci_full(self) -> None: "breg_tutorial", "casework_tutorial", "breg_evidence_composition", + "acceptance_journeys", ) # Each heavy selector keeps its own path gate; this change reaches all. paths = ( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dda895aa05..7ee0b0f326 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,6 +95,7 @@ jobs: render_tutorial: ${{ steps.filter.outputs.render_tutorial }} scheduling_tutorial: ${{ steps.filter.outputs.scheduling_tutorial }} breg_evidence_composition: ${{ steps.filter.outputs.breg_evidence_composition }} + acceptance_journeys: ${{ steps.filter.outputs.acceptance_journeys }} identifiers: ${{ steps.filter.outputs.identifiers }} steps: - name: Checkout @@ -123,6 +124,23 @@ jobs: with: version: "0.11.16" + # Our signatures are what an independent Standard Webhooks receiver computes. + # Platform owns this gate. Remove it when the shared crate stops signing deliveries. + - name: Test Standard Webhooks signature vectors + run: uv run --no-project --with standardwebhooks==1.3.0 python -m unittest products/platform/scripts/test_standard_webhooks_vectors.py + + # The public Go receiver example verifies the committed vectors, and the + # delivery signing page quotes its verifier. + # Platform owns this gate. Remove it when the delivery signing page drops the Go receiver example. + - name: Install Go for the receiver example + uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: 1.27.2 + cache: false + + - name: Test the Go delivery receiver example + run: go -C products/platform/examples/delivery-receiver-go test ./... + - name: Test CI classifier run: uv run --no-project --with PyYAML==6.0.2 python .github/scripts/test_ci_changes.py @@ -161,6 +179,11 @@ jobs: - name: Test evidence fuzz runner run: uv run --no-project --with PyYAML==6.0.2 python -m unittest products/evidence/scripts/test_run_fuzz_smoke.py + # The acceptance journeys run in the heavy tier; their tables are + # checked on every pull request. + - name: Test the acceptance journey tables + run: uv run --no-project --with PyYAML==6.0.2 python -m unittest products/platform/journeys/test_journey_tables.py + - name: Install pinned actionlint shell: bash run: | @@ -300,7 +323,10 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 15 # --all-features enables the dispatch and activation PostgreSQL tests, - # which fail rather than skip without their disposable database. + # which fail rather than skip without their disposable database. It also + # enables the provisioning suite, which fails rather than skips without a + # PostgreSQL 17 superuser with PostGIS over TLS and a server below the + # floor signed by a CA it trusts. services: postgres: image: docker.io/library/postgres:17.11@sha256:67f41722b7a8cbdb868a44a4995c846eddfdc2973bccb291ce937dce88ad5675 @@ -315,6 +341,20 @@ jobs: --health-retries 5 ports: - 5432/tcp + postgis: + # The PostgreSQL 17 / PostGIS 3.5.2 image breg-contracts pins. + image: postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6 + env: + POSTGRES_DB: provision + POSTGRES_USER: provision + POSTGRES_PASSWORD: provision_test + options: >- + --health-cmd "pg_isready -U provision -d provision" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432/tcp steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -323,6 +363,105 @@ jobs: persist-credentials: false submodules: false + # The contracts-journeys lane's TLS script, in setup-only mode, gives + # the service a throwaway CA and makes it TLS-only. + - name: Serve the provisioning PostGIS service over TLS + shell: bash + env: + SERVICE_CONTAINER_ID: ${{ job.services.postgis.id }} + SERVICE_PORT: ${{ job.services.postgis.ports['5432'] }} + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${SERVICE_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${SERVICE_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + # The same PostgreSQL 16 steps as the contracts-journeys lane, which + # test_ci_changes.py holds equal. + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + # One bundle trusts both servers' throwaway CAs. + - name: Bundle the provisioning servers' CAs + shell: bash + env: + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + BUNDLE_PATH: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + run: | + set -euo pipefail + for ca in "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}" + - name: Cache Cargo registry and build artifacts uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 with: @@ -338,6 +477,9 @@ jobs: env: DISPATCH_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch ACTIVATION_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch + PROVISION_TEST_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full + PROVISION_TEST_DATABASE_CA: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + PROVISION_TEST_OLD_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full run: >- cargo llvm-cov --locked -p 'registry-platform-*' @@ -363,6 +505,21 @@ jobs: if-no-files-found: error retention-days: 1 + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + platform-coverage-upload: name: Upload platform coverage needs: @@ -716,6 +873,18 @@ jobs: if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-testing') run: cargo test --locked -p registry-platform-testing --features test-authorization-server --test test_authorization_server + # The corpus test needs token-fixtures, which no platform crate enables, + # so the shard's own run skips it. + - name: Test the token fixture corpus + if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-testing') + run: cargo test --locked -p registry-platform-testing --features token-fixtures --test token_fixtures + + # The refusal trace id impl sits behind refusal-trace-id, which no + # platform crate enables, so the shard's own run skips its test. + - name: Test the refusal trace id implementation + if: matrix.name == 'platform' && contains(matrix.packages, 'registry-platform-httpsec') + run: cargo test --locked -p registry-platform-httpsec --features refusal-trace-id --lib + - name: Check Casework schemas against their generators if: matrix.name == 'casework' run: products/casework/scripts/check-schemas.sh @@ -1287,7 +1456,11 @@ jobs: - name: Verify messagingctl messages commands env: MESSAGING_TEST_DATABASE_URL: postgresql://messaging:messaging_test@localhost:${{ job.services.postgres.ports['5432'] }}/messaging - run: cargo test --locked -p registry-messagingctl --features postgres-test --tests + # The provisioning journey needs a TLS server and runs in the + # contracts-journeys lane. + run: >- + cargo test --locked -p registry-messagingctl --features postgres-test --tests + -- --skip provision_then_apply_then_serve_with_split_roles - name: Send one email and one SMS through messagingctl dev env: MESSAGINGCTL_BIN: ${{ github.workspace }}/target/debug/messagingctl @@ -1737,6 +1910,169 @@ jobs: if: matrix.lane == 'contracts-journeys' run: products/breg/quickstart/run.sh --spatial --smoke + # The provisioning suite needs a PostgreSQL 17 superuser with PostGIS + # over TLS, which this lane's service is once the TLS proof has run, and + # a server below the floor signed by a CA the suite also trusts. It + # fails, never skips, when one of its variables is missing. + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + if: matrix.lane == 'contracts-journeys' + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + # Setup-only mode gives this server its own throwaway CA and makes it + # TLS-only, the way the proof above does for the lane's service. + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Provisioning PostgreSQL suite + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + DATABASE_PORT: ${{ job.services.postgres.ports['5432'] }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + if [[ ! "${DATABASE_PORT}" =~ ^[0-9]+$ || ! "${OLD_PORT}" =~ ^[0-9]+$ ]]; then + echo "::error::the provisioning suite needs the port of both PostgreSQL servers" + exit 1 + fi + for ca in "${BREG_TEST_TLS_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + # One bundle trusts both servers' throwaway CAs. + bundle="${RUNNER_TEMP}/provision-postgres-ca-bundle.pem" + cat "${BREG_TEST_TLS_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${bundle}" + export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@localhost:${DATABASE_PORT}/postgres?sslmode=verify-full" + export PROVISION_TEST_DATABASE_CA="${bundle}" + export PROVISION_TEST_OLD_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres?sslmode=verify-full" + # With cli on, the library's command tests also run against the + # first server. No rust-tests shard enables cli. + cargo test --locked -p registry-platform-provision --features postgres-test,cli --lib \ + | tee "${RUNNER_TEMP}/provision-postgres-lib.log" + cargo test --locked -p registry-platform-provision --features postgres-test,cli --test postgres \ + | tee "${RUNNER_TEMP}/provision-postgres-suite.log" + # A run that selected no test still exits 0, so each target needs a + # pass count and no ignored test. + for target in lib suite; do + grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${RUNNER_TEMP}/provision-postgres-${target}.log" || { echo "::error::expected the provisioning PostgreSQL ${target} tests to pass with no test ignored"; exit 1; } + done + + - name: Product provisioning PostgreSQL journeys + if: matrix.lane == 'contracts-journeys' + shell: bash + env: + DATABASE_PORT: ${{ job.services.postgres.ports['5432'] }} + run: | + set -euo pipefail + if [[ ! "${DATABASE_PORT}" =~ ^[0-9]+$ ]]; then + echo "::error::the provisioning journeys need the port of the TLS PostgreSQL service" + exit 1 + fi + if [[ ! -s "${BREG_TEST_TLS_CA_PEM_PATH}" ]]; then + echo "::error::the provisioning journeys need the CA file ${BREG_TEST_TLS_CA_PEM_PATH}" + exit 1 + fi + # Each journey provisions its product's database and roles on the + # TLS-only service, applies as the owner role and serves as the + # runtime role. The Adapter applies inside `adapter serve`. + export PROVISION_TEST_DATABASE_URL="postgresql://breg:breg_test@localhost:${DATABASE_PORT}/postgres?sslmode=verify-full" + export PROVISION_TEST_DATABASE_CA="${BREG_TEST_TLS_CA_PEM_PATH}" + cargo test --locked -p registry-adapterctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-adapterctl.log" + cargo test --locked -p registry-bregctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-bregctl.log" + cargo test --locked -p registry-caseworkctl --features postgres-test --test provision \ + | tee "${RUNNER_TEMP}/provision-journey-registry-caseworkctl.log" + cargo test --locked -p registry-coordinator --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-coordinator.log" + cargo test --locked -p registry-documentsctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-documentsctl.log" + cargo test --locked -p registry-messagingctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-messagingctl.log" + cargo test --locked -p registry-schedulingctl --features postgres-test --test provision_postgres \ + | tee "${RUNNER_TEMP}/provision-journey-registry-schedulingctl.log" + # A run that selected no test still exits 0, so every log needs a + # pass count, no ignored test, and the journey's own line. + for package in registry-adapterctl registry-bregctl registry-caseworkctl registry-coordinator registry-documentsctl registry-messagingctl registry-schedulingctl; do + log="${RUNNER_TEMP}/provision-journey-${package}.log" + grep -Eq '^test result: ok\. [1-9][0-9]* passed; 0 failed; 0 ignored' "${log}" || { echo "::error::expected the ${package} provisioning journey tests to pass with no test ignored"; exit 1; } + grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ \.\.\. ok$' "${log}" || { echo "::error::expected the ${package} provisioning journey to run and pass"; exit 1; } + done + + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && matrix.lane == 'contracts-journeys' && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + breg-postgres-18: name: Base Registry Engine PostgreSQL 18 portability needs: changes @@ -2144,6 +2480,9 @@ jobs: - name: Test supporting release image packaging run: python3 -m unittest release/scripts/test_release_supporting_images.py + - name: Test release image build command + run: python3 -m unittest release/scripts/test_build_release_image.py + - name: Test release candidate manifest and promotion verifier run: python3 -m unittest release/scripts/test_release_candidate.py @@ -3083,6 +3422,103 @@ jobs: --evidencectl "$GITHUB_WORKSPACE/target/debug/evidencectl" \ --evidence "$GITHUB_WORKSPACE/target/debug/evidence" + acceptance-journeys: + # The first-hour journeys of products/platform/journeys/ in ratchet mode: + # a leg passes when every product's outcome equals expected-failures.yaml, + # and --strict fails it when a listed failure no longer fails, so the + # change that fixes a cell deletes its row. Owner: platform. A leg that + # passes this 40 minute limit, or fails for harness reasons more than + # twice in a week, moves to the nightly sweep and ci:full only. No step + # retries. + name: Acceptance journeys (${{ matrix.title }}) + needs: + - changes + - rust-policy + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.acceptance_journeys == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + include: + - leg: own-provider + title: own-provider and promote + - leg: rstack-dev + title: rstack dev + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + submodules: false + + - name: Cache Cargo registry + uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 + with: + shared-key: workspace-registry + cache-targets: false + save-if: ${{ github.ref == 'refs/heads/main' }} + + # The digest products/platform/journeys/products.yaml pins. No other + # job pulls from quay.io, so a registry outage fails here, before any + # product step runs. + - name: Pull the Keycloak issuer image + if: matrix.leg == 'own-provider' + run: docker pull quay.io/keycloak/keycloak:26.7.3@sha256:ff4257d0d64efbe99ed1ddfaf07765cc3c36dc7518bf8324d41961327f441c54 + + # Every package and feature in the journeys' product column, and rstack. + - name: Build the journey binaries + run: >- + cargo build --locked + -p registry-adapter -p registry-adapter-job -p registry-adapterctl + -p registry-breg -p registry-breg-mcp -p registry-breg-review -p registry-bregctl + -p registry-casework -p registry-caseworkctl + -p registry-coordinator + -p registry-discovery -p registry-discoveryctl + -p registry-documents -p registry-documentsctl + -p registry-evidence -p registry-evidence-oid4vci -p registry-evidence-oid4vp -p registry-evidencectl + -p registry-mcp + -p registry-messaging -p registry-messagingctl + -p registry-render + -p registry-rstack + -p registry-scheduling -p registry-schedulingctl + --features registry-breg/runtime,registry-discovery/server + --bins + + - name: Run the own-provider journey + if: matrix.leg == 'own-provider' + run: >- + products/platform/journeys/own-provider.sh --all + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --keep + --out "${RUNNER_TEMP}/journeys/own-provider" + + # Promote takes over the containers and run directory the own-provider + # journey kept, and its cleanup removes them. + - name: Run the promote journey + if: matrix.leg == 'own-provider' + run: >- + products/platform/journeys/promote.sh --all + --from "${RUNNER_TEMP}/journeys/own-provider" + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --out "${RUNNER_TEMP}/journeys/promote" + + - name: Run the rstack dev journey + if: matrix.leg == 'rstack-dev' + run: >- + products/platform/journeys/rstack-dev.sh --all + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --expected products/platform/journeys/expected-failures.yaml --strict + --out "${RUNNER_TEMP}/journeys/rstack-dev" + + - name: Report disk usage + if: always() + run: | + df -h / + du -sh target 2>/dev/null || true + evidence-anchors: # The documentation anchors cite source across the whole workspace, so this check # runs on every pull request rather than behind the changed-path classifier: a @@ -3574,6 +4010,7 @@ jobs: - render-tutorial - scheduling-tutorial - breg-evidence-composition + - acceptance-journeys - evidence-anchors - docs - client-bindings @@ -3609,6 +4046,7 @@ jobs: "breg-tutorial": "breg_tutorial", "casework-tutorial": "casework_tutorial", "breg-evidence-composition": "breg_evidence_composition", + "acceptance-journeys": "acceptance_journeys", "deployment": "deployment", } selection = jobs["changes"].get("outputs", {}) diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml index f1b5a0b6f7..56f7cc5c5d 100644 --- a/.github/workflows/nightly-release.yml +++ b/.github/workflows/nightly-release.yml @@ -5,6 +5,12 @@ on: schedule: - cron: "19 0 * * *" workflow_dispatch: + inputs: + arm64_images: + description: Also build native Linux arm64 image layouts, retained for inspection and not published. Builds only when no nightly has published this commit yet, and only from the canonical repository's protected main. + type: boolean + required: false + default: false permissions: contents: read @@ -217,6 +223,70 @@ jobs: retention-days: 7 if-no-files-found: error + arm64-images: + name: Build native Linux arm64 nightly image layouts + needs: [select, arm64] + if: needs.select.outputs.skip != 'true' && inputs.arm64_images + runs-on: ubuntu-24.04-arm + timeout-minutes: 90 + steps: + - name: Checkout selected source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ needs.select.outputs.source_sha }} + persist-credentials: false + submodules: false + - name: Download exact arm64 binaries + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + name: nightly-arm64-${{ github.run_id }}-${{ github.run_attempt }} + path: arm64 + - name: Stage the arm64 image binaries + env: + IMAGE_NAMES: ${{ needs.select.outputs.image_names }} + BASE_VERSION: ${{ needs.select.outputs.base_version }} + NIGHTLY_TAG: ${{ needs.select.outputs.tag }} + run: | + mkdir -p dist/image-bin + operator_tools="$(python3 release/scripts/release_candidate.py image-operator-tools --version "${BASE_VERSION}")" + for name in ${IMAGE_NAMES}; do + install -m 0755 "arm64/${name}-${NIGHTLY_TAG}-linux-arm64" "dist/image-bin/${name}" + for pair in ${operator_tools}; do + if [[ "${pair%%=*}" == "${name}" ]]; then + tool="${pair#*=}" + install -m 0755 "arm64/${tool}-${NIGHTLY_TAG}-linux-arm64" "dist/image-bin/${tool}" + fi + done + done + - name: Set up pinned Docker Buildx + id: buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 + with: + version: ${{ env.RELEASE_BUILDX_VERSION }} + driver-opts: image=${{ env.RELEASE_BUILDKIT_IMAGE }} + - name: Build arm64 image layouts without publication credentials + env: + IMAGE_NAMES: ${{ needs.select.outputs.image_names }} + NIGHTLY_VERSION: ${{ needs.select.outputs.version }} + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + RELEASE_BUILDX_BUILDER: ${{ steps.buildx.outputs.name }} + RELEASE_IMAGE_PLATFORM: linux/arm64 + run: | + mkdir -p dist/images-arm64 + for name in ${IMAGE_NAMES}; do + reference="ghcr.io/registrystack/${name}-candidate:candidate-arm64-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + RELEASE_IMAGE_OCI_LAYOUT="${GITHUB_WORKSPACE}/dist/images-arm64/${name}.oci" \ + release/scripts/build-release-image.sh "${name}" "${reference}" \ + "https://github.com/${GITHUB_REPOSITORY}" "${SOURCE_SHA}" "${NIGHTLY_VERSION}" "dist/images-arm64/${name}.metadata.json" + done + - name: Retain arm64 image layouts + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: arm64-image-layouts-${{ github.run_id }}-${{ github.run_attempt }} + path: dist/images-arm64 + retention-days: 7 + if-no-files-found: error + images: name: Merge Linux shards and build exact nightly image layouts needs: [select, linux] diff --git a/.github/workflows/nightly-rust-coverage.yml b/.github/workflows/nightly-rust-coverage.yml index 4c336fa155..813e3d5654 100644 --- a/.github/workflows/nightly-rust-coverage.yml +++ b/.github/workflows/nightly-rust-coverage.yml @@ -55,9 +55,11 @@ jobs: COVERAGE_PACKAGES: ${{ matrix.packages }} # The platform shard's --all-features build enables the dispatch and # activation PostgreSQL tests, which fail rather than skip without their - # disposable database. The other shards start the service and leave it - # unused, so this definition stays identical to platform-coverage in - # ci.yml, which .github/scripts/test_ci_changes.py holds. + # disposable database, and the provisioning suite, which fails rather + # than skips without its two TLS servers. The other shards start the + # services and leave them unused, so this definition stays identical to + # platform-coverage in ci.yml, which .github/scripts/test_ci_changes.py + # holds. The provisioning server steps run in the platform shard only. services: postgres: image: docker.io/library/postgres:17.11@sha256:67f41722b7a8cbdb868a44a4995c846eddfdc2973bccb291ce937dce88ad5675 @@ -72,6 +74,20 @@ jobs: --health-retries 5 ports: - 5432/tcp + postgis: + # The PostgreSQL 17 / PostGIS 3.5.2 image breg-contracts pins. + image: postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6 + env: + POSTGRES_DB: provision + POSTGRES_USER: provision + POSTGRES_PASSWORD: provision_test + options: >- + --health-cmd "pg_isready -U provision -d provision" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432/tcp steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -80,6 +96,105 @@ jobs: persist-credentials: false submodules: false + # The same provisioning server steps as platform-coverage in ci.yml. + - name: Serve the provisioning PostGIS service over TLS + if: matrix.name == 'platform' + shell: bash + env: + SERVICE_CONTAINER_ID: ${{ job.services.postgis.id }} + SERVICE_PORT: ${{ job.services.postgis.ports['5432'] }} + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${SERVICE_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${SERVICE_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${SERVICE_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Start PostgreSQL 16 for the provisioning floor test + id: provision-postgres-16 + if: matrix.name == 'platform' + shell: bash + run: | + set -euo pipefail + # PostgreSQL 16.15, verified 2026-11-27. + image='docker.io/library/postgres:16.15@sha256:f9a7b9ebf6f56201f949db745e47bc423c0f0f8294bafe991cc10bf74b029657' + container_name="provision-postgres-16-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_id="$( + docker run --detach \ + --name "${container_name}" \ + --label org.registrystack.ci.postgres-service=true \ + --env POSTGRES_USER=provision \ + --env POSTGRES_PASSWORD=provision_test \ + --health-cmd 'pg_isready -U provision -d provision' \ + --health-interval 10s \ + --health-timeout 5s \ + --health-retries 5 \ + --publish 127.0.0.1::5432 \ + "${image}" + )" + printf 'container_id=%s\n' "${container_id}" >> "${GITHUB_OUTPUT}" + + for _ in $(seq 1 30); do + health="$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" + if [[ "${health}" == healthy ]]; then + break + fi + if [[ "${health}" == unhealthy ]]; then + docker logs "${container_id}" + exit 1 + fi + sleep 2 + done + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "${container_id}")" != healthy ]]; then + docker logs "${container_id}" + exit 1 + fi + + endpoint="$(docker port "${container_id}" 5432/tcp)" + port="${endpoint##*:}" + [[ "${port}" =~ ^[0-9]+$ ]] + printf 'port=%s\n' "${port}" >> "${GITHUB_OUTPUT}" + + - name: Serve PostgreSQL 16 over TLS for the provisioning floor test + if: matrix.name == 'platform' + shell: bash + env: + OLD_CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + OLD_PORT: ${{ steps.provision-postgres-16.outputs.port }} + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + run: | + set -euo pipefail + BREG_TEST_TLS_SETUP_ONLY=1 \ + BREG_TEST_TLS_POSTGRES_CONTAINER_ID="${OLD_CONTAINER_ID}" \ + BREG_TEST_TLS_DATABASE_HOST=localhost \ + BREG_TEST_TLS_DATABASE_URL="postgresql://provision:provision_test@localhost:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_HOSTNAME_MISMATCH_DATABASE_URL="postgresql://provision:provision_test@127.0.0.1:${OLD_PORT}/postgres" \ + BREG_TEST_TLS_CA_DER_PATH='' \ + BREG_TEST_TLS_CA_PEM_PATH="${OLD_CA_PEM_PATH}" \ + products/breg/scripts/test-postgres-tls.sh + + - name: Bundle the provisioning servers' CAs + if: matrix.name == 'platform' + shell: bash + env: + SERVICE_CA_PEM_PATH: ${{ runner.temp }}/provision-postgres-ca.pem + OLD_CA_PEM_PATH: ${{ runner.temp }}/provision-old-postgres-ca.pem + BUNDLE_PATH: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + run: | + set -euo pipefail + for ca in "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}"; do + if [[ ! -s "${ca}" ]]; then + echo "::error::the provisioning suite needs the CA file ${ca}" + exit 1 + fi + done + cat "${SERVICE_CA_PEM_PATH}" "${OLD_CA_PEM_PATH}" > "${BUNDLE_PATH}" + - name: Cache Cargo registry uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 with: @@ -97,6 +212,9 @@ jobs: env: DISPATCH_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch ACTIVATION_TEST_DATABASE_URL: postgresql://dispatch:dispatch_test@localhost:${{ job.services.postgres.ports['5432'] }}/dispatch + PROVISION_TEST_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ job.services.postgis.ports['5432'] }}/postgres?sslmode=verify-full + PROVISION_TEST_DATABASE_CA: ${{ runner.temp }}/provision-postgres-ca-bundle.pem + PROVISION_TEST_OLD_DATABASE_URL: postgresql://provision:provision_test@localhost:${{ steps.provision-postgres-16.outputs.port }}/postgres?sslmode=verify-full run: | set -euo pipefail @@ -158,6 +276,21 @@ jobs: use_oidc: true version: v11.3.1 + - name: Stop PostgreSQL 16 for the provisioning floor test + if: always() && matrix.name == 'platform' && steps.provision-postgres-16.outputs.container_id != '' + env: + CONTAINER_ID: ${{ steps.provision-postgres-16.outputs.container_id }} + shell: bash + run: | + set -euo pipefail + label="$( + docker inspect \ + --format '{{ index .Config.Labels "org.registrystack.ci.postgres-service" }}' \ + "${CONTAINER_ID}" + )" + [[ "${label}" == true ]] + docker rm --force "${CONTAINER_ID}" + - name: Report disk usage if: always() run: | diff --git a/.github/workflows/render-golden.yml b/.github/workflows/render-golden.yml index 1bba2b026e..33f54e78aa 100644 --- a/.github/workflows/render-golden.yml +++ b/.github/workflows/render-golden.yml @@ -25,6 +25,8 @@ on: - "crates/registry-platform-config/**" - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" + - "crates/registry-platform-loopback/**" + - "crates/registry-platform-posture/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" @@ -50,6 +52,8 @@ on: - "crates/registry-platform-config/**" - "crates/registry-platform-crypto/**" - "crates/registry-platform-httpsec/**" + - "crates/registry-platform-loopback/**" + - "crates/registry-platform-posture/**" - "crates/registry-platform-testing/**" - "crates/registry-platform-yaml/**" - "products/render/**" diff --git a/.gitleaks.toml b/.gitleaks.toml index 50335e43e7..4ad416c05a 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -86,3 +86,10 @@ paths = [ ] regexTarget = "line" regexes = ['''^(\s*"presentation": ")?eyJhbGciOiAiRVMyNTYiLCAidHlwIjogI(mV4YW1wbGUrc2Qtand0In0\.|mRjK3NkLWp3dCIsICJraWQiOiAi)'''] + +[[allowlists]] +description = "Allow the synthetic HMAC keys in the Standard Webhooks test vectors. They are random test bytes and the official library's published example key, not credentials." +condition = "AND" +paths = ['''^crates/registry-platform-crypto/tests/fixtures/standard-webhooks\.json$'''] +regexTarget = "line" +regexes = ['''^\s*"(keyHex|previousKeyHex)": "[0-9a-f]{48,128}",$'''] diff --git a/Cargo.lock b/Cargo.lock index f6c815cd09..7b321ab666 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6109,11 +6109,13 @@ dependencies = [ "registry-adapter-connectors", "registry-adapter-core", "registry-adapter-engine", + "registry-platform-authcommon", "registry-platform-buildinfo", "registry-platform-config", "registry-platform-crypto", "registry-platform-hooks", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-ratelimit", "registry-platform-testing", @@ -6154,6 +6156,7 @@ dependencies = [ "registry-platform-buildinfo", "registry-platform-config", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-script", "registry-platform-yaml", "registry-record", @@ -6162,7 +6165,9 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "tokio-postgres", "tokio-rustls", + "uuid", "zeroize", ] @@ -6414,6 +6419,7 @@ dependencies = [ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-testing", "registry-platform-yaml", "registry-rstack-dev", @@ -6618,6 +6624,7 @@ dependencies = [ "registry-cli-report", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", @@ -6629,6 +6636,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] @@ -6671,6 +6679,8 @@ dependencies = [ "registry-caseworkctl", "registry-cli-reference", "registry-coordinator", + "registry-discovery", + "registry-discoveryctl", "registry-documents", "registry-documentsctl", "registry-evidence", @@ -6702,6 +6712,7 @@ dependencies = [ name = "registry-cli-report" version = "0.49.0" dependencies = [ + "registry-platform-posture", "serde", "serde_json", ] @@ -6739,6 +6750,7 @@ dependencies = [ "registry-platform-httputil", "registry-platform-metrics", "registry-platform-oidc", + "registry-platform-provision", "registry-platform-script", "registry-platform-testing", "registry-platform-yaml", @@ -6964,6 +6976,7 @@ dependencies = [ "registry-platform-buildinfo", "registry-platform-canonical-json", "registry-platform-config", + "registry-platform-crypto", "registry-platform-dispatch", "registry-platform-hooks", "registry-platform-httpsec", @@ -7039,6 +7052,7 @@ dependencies = [ "registry-documents-core", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "serde", "serde_json", @@ -7046,6 +7060,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] @@ -7091,6 +7106,7 @@ dependencies = [ "registry-platform-ratelimit", "registry-platform-sdjwt", "registry-platform-sqlite", + "registry-platform-testing", "registry-platform-text", "registry-platform-x509", "registry-platform-yaml", @@ -7239,6 +7255,7 @@ dependencies = [ "registry-evidence-client", "registry-evidence-verifier", "registry-platform-audit", + "registry-platform-authcommon", "registry-platform-buildinfo", "registry-platform-config", "registry-platform-crypto", @@ -7248,6 +7265,7 @@ dependencies = [ "registry-platform-oidc", "registry-platform-ratelimit", "registry-platform-sdjwt", + "registry-platform-testing", "registry-platform-yaml", "registry-thunderid-tooling", "reqwest 0.12.28", @@ -7378,6 +7396,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httpsec", + "registry-platform-loopback", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", @@ -7674,6 +7693,7 @@ dependencies = [ "registry-platform-dispatch", "registry-platform-httputil", "registry-platform-oidc", + "registry-platform-provision", "registry-platform-testing", "registry-platform-yaml", "registry-rstack-dev", @@ -7762,6 +7782,7 @@ name = "registry-platform-activation" version = "0.49.0" dependencies = [ "chrono", + "registry-platform-posture", "schemars", "serde", "serde_json", @@ -7777,6 +7798,7 @@ version = "0.49.0" dependencies = [ "hmac 0.13.0", "regex", + "registry-platform-posture", "rustix 1.1.6", "schemars", "serde", @@ -7799,12 +7821,15 @@ dependencies = [ "futures", "proptest", "registry-platform-crypto", + "registry-platform-metrics", "serde", "serde_json", "sha2 0.11.1", "subtle", "tempfile", "thiserror 2.0.21", + "tracing", + "tracing-subscriber", "ulid", "zeroize", ] @@ -7837,6 +7862,8 @@ name = "registry-platform-config" version = "0.49.0" dependencies = [ "registry-platform-canonical-json", + "registry-platform-loopback", + "registry-platform-posture", "registry-platform-yaml", "rustix 1.1.6", "schemars", @@ -7845,6 +7872,7 @@ dependencies = [ "sha2 0.11.1", "tempfile", "thiserror 2.0.21", + "tracing", "url", "zeroize", ] @@ -7930,6 +7958,9 @@ version = "0.49.0" dependencies = [ "axum", "http", + "registry-platform-authcommon", + "registry-platform-loopback", + "registry-platform-posture", "serde", "serde_json", "thiserror 2.0.21", @@ -7961,6 +7992,8 @@ dependencies = [ "registry-platform-authcommon", "registry-platform-canonical-json", "registry-platform-crypto", + "registry-platform-loopback", + "registry-platform-posture", "reqwest 0.12.28", "rustls-native-certs", "serde", @@ -7976,6 +8009,10 @@ dependencies = [ "zeroize", ] +[[package]] +name = "registry-platform-loopback" +version = "0.49.0" + [[package]] name = "registry-platform-metrics" version = "0.49.0" @@ -8012,9 +8049,11 @@ dependencies = [ "base64 0.23.1", "chrono", "jsonwebtoken", + "registry-platform-authcommon", "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-posture", "registry-platform-yaml", "reqwest 0.12.28", "schemars", @@ -8023,10 +8062,36 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "tokio", - "tracing", "uuid", ] +[[package]] +name = "registry-platform-posture" +version = "0.49.0" + +[[package]] +name = "registry-platform-provision" +version = "0.49.0" +dependencies = [ + "clap", + "getrandom 0.4.3", + "postgres-protocol", + "registry-cli-report", + "registry-platform-activation", + "registry-platform-yaml", + "rustls", + "schemars", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tokio-postgres", + "tokio-postgres-rustls", + "url", + "zeroize", +] + [[package]] name = "registry-platform-ratelimit" version = "0.49.0" @@ -8094,12 +8159,15 @@ dependencies = [ "bytes", "futures", "jsonwebtoken", + "rand 0.9.5", "registry-platform-audit", "registry-platform-crypto", "registry-platform-httpsec", "registry-platform-httputil", "registry-platform-oidc", + "registry-platform-yaml", "reqwest 0.12.28", + "serde", "serde_json", "sha2 0.11.1", "tempfile", @@ -8195,6 +8263,7 @@ dependencies = [ "registry-platform-httputil", "registry-platform-metrics", "registry-platform-oidc", + "registry-platform-testing", "registry-platform-yaml", "registry-render-client", "reqwest 0.12.28", @@ -8336,6 +8405,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-provision", "registry-platform-yaml", "reqwest 0.12.28", "rustix 1.1.6", @@ -8383,6 +8453,7 @@ dependencies = [ "registry-platform-hooks", "registry-platform-httpsec", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-metrics", "registry-platform-oidc", "registry-platform-testing", @@ -8487,6 +8558,7 @@ dependencies = [ "registry-platform-audit", "registry-platform-buildinfo", "registry-platform-config", + "registry-platform-provision", "registry-platform-yaml", "registry-scheduling", "registry-scheduling-core", @@ -8496,6 +8568,7 @@ dependencies = [ "tokio", "tokio-postgres", "uuid", + "zeroize", ] [[package]] @@ -8528,6 +8601,7 @@ dependencies = [ "registry-platform-config", "registry-platform-crypto", "registry-platform-httputil", + "registry-platform-loopback", "registry-platform-oidc", "registry-platform-yaml", "reqwest 0.12.28", diff --git a/Cargo.toml b/Cargo.toml index 8be5c1b7cf..cc1a9f906f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,9 +49,12 @@ members = [ "crates/registry-platform-hooks", "crates/registry-platform-httpsec", "crates/registry-platform-httputil", + "crates/registry-platform-loopback", "crates/registry-platform-metrics", "crates/registry-platform-objectstore", "crates/registry-platform-oidc", + "crates/registry-platform-posture", + "crates/registry-platform-provision", "crates/registry-platform-ratelimit", "crates/registry-platform-resilience", "crates/registry-platform-script", @@ -203,9 +206,12 @@ registry-platform-dispatch = { path = "crates/registry-platform-dispatch", versi registry-platform-hooks = { path = "crates/registry-platform-hooks", version = "0.49.0" } registry-platform-httpsec = { path = "crates/registry-platform-httpsec", version = "0.49.0", default-features = false } registry-platform-httputil = { path = "crates/registry-platform-httputil", version = "0.49.0" } +registry-platform-loopback = { path = "crates/registry-platform-loopback", version = "0.49.0" } registry-platform-metrics = { path = "crates/registry-platform-metrics", version = "0.49.0" } registry-platform-objectstore = { path = "crates/registry-platform-objectstore", version = "0.49.0" } registry-platform-oidc = { path = "crates/registry-platform-oidc", version = "0.49.0" } +registry-platform-posture = { path = "crates/registry-platform-posture", version = "0.49.0" } +registry-platform-provision = { path = "crates/registry-platform-provision", version = "0.49.0" } registry-platform-ratelimit = { path = "crates/registry-platform-ratelimit", version = "0.49.0" } registry-platform-resilience = { path = "crates/registry-platform-resilience", version = "0.49.0" } registry-platform-script = { path = "crates/registry-platform-script", version = "0.49.0" } diff --git a/crates/registry-adapter-connectors/src/coordinator_event.rs b/crates/registry-adapter-connectors/src/coordinator_event.rs index 2f22dc009a..49202bd541 100644 --- a/crates/registry-adapter-connectors/src/coordinator_event.rs +++ b/crates/registry-adapter-connectors/src/coordinator_event.rs @@ -2,24 +2,21 @@ //! A platform-signed event admission to Registry Coordinator. This //! connector deliberately links no Coordinator crate or client: it uses -//! the shared hook envelope, Version 1 signature, and fixed event +//! the shared hook envelope, Standard Webhooks signature, and fixed event //! destination transport that the Coordinator receiver verifies. use std::sync::Arc; use std::time::{Duration, SystemTime}; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields, SigningError}; +use registry_platform_crypto::delivery_signature::{sign, DeliveryKeys}; use registry_platform_hooks::{Causation, EnvelopeLimits, EventSubject, HookEnvelope}; use registry_platform_httputil::destination::{ - DestinationDeliveryCertainty, EventDeliveryHeaders, EventDestinationPolicy, - EventDestinationRequestTemplate, MAX_DESTINATION_REQUEST_HEADER_BYTES, - MAX_DESTINATION_TARGET_BYTES, + DestinationDeliveryCertainty, EventDestinationPolicy, EventDestinationRequestTemplate, + SignedEventHeaders, MAX_DESTINATION_REQUEST_HEADER_BYTES, MAX_DESTINATION_TARGET_BYTES, }; use serde_json::Value; -use time::format_description::well_known::Rfc3339; use time::OffsetDateTime; use uuid::Uuid; -use zeroize::Zeroizing; const MAX_PROBLEM_BYTES: usize = 65_536; const MAX_REQUEST_BYTES: usize = registry_platform_hooks::MAX_ENVELOPE_BYTES @@ -32,7 +29,7 @@ const CANONICAL_BODY_IDENTITY_DOMAIN: &[u8] = b"registry-adapter/coordinator-can pub enum CoordinatorEventOutcome { /// Coordinator admitted or recovered the event's one Run. Admitted { run_id: String }, - /// The item cannot produce one valid Version 1 signed event. Nothing was + /// The item cannot produce one valid Standard Webhooks event. Nothing was /// sent, so the job may record an item-scoped refusal and continue. Unsignable, /// The event itself does not satisfy the reviewed trigger contract. @@ -92,7 +89,7 @@ pub enum CoordinatorEventConfigError { /// destination authority and authenticated source. pub struct CoordinatorEventReceiver { template: EventDestinationRequestTemplate, - target: String, + keys: DeliveryKeys, event_type: String, data_schema: String, } @@ -105,13 +102,14 @@ impl std::fmt::Debug for CoordinatorEventReceiver { impl CoordinatorEventReceiver { /// Freeze one workflow trigger, its exact request target, and its event - /// contract. Binding, source, and credentials remain shared connector - /// state, so a revised receiver cannot substitute another authority. + /// contract and its delivery keys. The destination policy and source + /// remain shared connector state. pub fn new( workflow: &str, trigger: &str, event_type: &str, data_schema: &str, + keys: DeliveryKeys, ) -> Result { if !local_id(workflow) || !local_id(trigger) @@ -121,7 +119,7 @@ impl CoordinatorEventReceiver { return Err(CoordinatorEventConfigError::Invalid); } let target = format!("/v1/events/{workflow}/{trigger}"); - let template = EventDestinationRequestTemplate::event_delivery( + let template = EventDestinationRequestTemplate::signed_event_delivery( &target, registry_platform_hooks::MAX_ENVELOPE_BYTES, MAX_REQUEST_BYTES, @@ -129,20 +127,19 @@ impl CoordinatorEventReceiver { .map_err(|_| CoordinatorEventConfigError::Invalid)?; Ok(Self { template, - target, + keys, event_type: event_type.to_string(), data_schema: data_schema.to_string(), }) } } -/// One frozen destination authority and its host-owned HMAC key. One +/// One frozen destination authority and source. One /// connector may serve the primary and optional revised trigger of the same /// workflow without duplicating or widening that authority. pub struct CoordinatorEventConnector { policy: Arc, source: String, - signing_key: Zeroizing>, timeout: Duration, } @@ -156,16 +153,12 @@ impl CoordinatorEventConnector { /// Freeze a reviewed workflow trigger on an already validated event /// destination policy. The path and complete header shape cannot vary /// per item. - #[allow(clippy::too_many_arguments)] pub fn new( policy: Arc, source: &str, - signing_key: Vec, timeout: Duration, ) -> Result { if !visible_bounded(source, 2_048) - || signing_key.len() - < registry_platform_crypto::delivery_signature::MIN_HMAC_SHA256_KEY_BYTES || timeout.is_zero() || timeout > registry_platform_httputil::destination::MAX_DESTINATION_OPERATION_TIMEOUT { @@ -174,7 +167,6 @@ impl CoordinatorEventConnector { Ok(Self { policy, source: source.to_string(), - signing_key: Zeroizing::new(signing_key), timeout, }) } @@ -222,7 +214,9 @@ impl CoordinatorEventConnector { } /// Sign and send one canonical envelope. A retry reuses `event.id` and - /// body, while delivery time and signature are fresh transport fields. + /// body, while send time and signature are fresh transport fields. + /// Generation and delivery attempt are checked for the caller's + /// positive-counter invariant only. pub async fn admit( &self, receiver: &CoordinatorEventReceiver, @@ -239,60 +233,20 @@ impl CoordinatorEventConnector { Ok(envelope) => envelope, Err(_) => return CoordinatorEventOutcome::Unsignable, }; - let wire = match serde_json::to_value(&envelope) { - Ok(wire) => wire, - Err(_) => return CoordinatorEventOutcome::Unsignable, + let Ok(send_time) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) else { + return CoordinatorEventOutcome::Stop { + code: "coordinator.event.signing-unavailable", + }; }; - let Some(event_time) = wire.get("time").and_then(Value::as_str) else { + let timestamp = send_time.as_secs(); + let Ok(signature) = sign(&receiver.keys, &envelope.id, timestamp, &body) else { return CoordinatorEventOutcome::Unsignable; }; - let generation = generation.to_string(); - let attempt = delivery_attempt.to_string(); - let delivery_time = match OffsetDateTime::now_utc().format(&Rfc3339) { - Ok(time) => time, - Err(_) => { - return CoordinatorEventOutcome::Stop { - code: "coordinator.event.signing-unavailable", - }; - } - }; - let signature = match sign_v1( - self.signing_key.as_slice(), - SignatureFields { - id: &envelope.id, - source: &envelope.source, - event_type: &envelope.event_type, - time: event_time, - data_schema: &envelope.dataschema, - generation: &generation, - attempt: &attempt, - delivery_time: &delivery_time, - method: "POST", - request_target: &receiver.target, - content_type: "application/json", - idempotency_key: &envelope.id, - body: &body, - }, - ) { - Ok(signature) => signature, - Err(SigningError::InputTooLarge) => return CoordinatorEventOutcome::Unsignable, - Err(SigningError::InvalidKey) => { - return CoordinatorEventOutcome::Stop { - code: "coordinator.event.signing-unavailable", - }; - } - }; - let request = match receiver.template.render_event( - EventDeliveryHeaders { + let timestamp = timestamp.to_string(); + let request = match receiver.template.render_signed_event( + SignedEventHeaders { id: envelope.id.as_bytes(), - source: envelope.source.as_bytes(), - event_type: envelope.event_type.as_bytes(), - time: event_time.as_bytes(), - dataschema: envelope.dataschema.as_bytes(), - generation: generation.as_bytes(), - attempt: attempt.as_bytes(), - delivery_time: delivery_time.as_bytes(), - idempotency_key: envelope.id.as_bytes(), + timestamp: timestamp.as_bytes(), signature: signature.as_bytes(), }, body, @@ -416,9 +370,6 @@ fn classify_problem(status: u16, code: Option<&str>) -> CoordinatorEventOutcome (503, Some("audit.response-unavailable")) => CoordinatorEventOutcome::Stop { code: "audit.response-unavailable", }, - (503, Some("event.source-unavailable")) => CoordinatorEventOutcome::Stop { - code: "event.source-unavailable", - }, (503, Some("service.unavailable")) => CoordinatorEventOutcome::Stop { code: "service.unavailable", }, @@ -452,11 +403,11 @@ mod tests { use axum::body::{to_bytes, Body}; use axum::extract::State; - use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, Response, StatusCode}; + use axum::http::{HeaderMap, HeaderValue, Request, Response, StatusCode}; use axum::routing::any; use axum::Router; use registry_platform_crypto::delivery_signature::{ - verify_v1_authenticity, MIN_HMAC_SHA256_KEY_BYTES, + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, }; use registry_platform_httputil::destination::{DestinationProfile, EventDestinationPolicy}; use serde_json::json; @@ -604,20 +555,21 @@ mod tests { let policy = EventDestinationPolicy::new( "coordinator-test", &fixture.origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the fixture origin is permitted"); - let connector = CoordinatorEventConnector::new( - Arc::new(policy), - SOURCE, - KEY.to_vec(), - Duration::from_secs(2), + let connector = + CoordinatorEventConnector::new(Arc::new(policy), SOURCE, Duration::from_secs(2)) + .expect("the connector configuration is valid"); + let receiver = CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + keys(KEY, None), ) - .expect("the connector configuration is valid"); - let receiver = - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the receiver contract is valid"); + .expect("the receiver contract is valid"); (connector, receiver) } @@ -632,27 +584,6 @@ mod tests { .expect("the event is valid") } - #[test] - fn a_short_signing_key_is_refused_before_any_delivery() { - let policy = EventDestinationPolicy::new( - "coordinator-test", - "http://127.0.0.1:9/", - DestinationProfile::LoopbackDevelopmentHttp, - &[], - ) - .expect("the loopback origin is permitted"); - assert_eq!( - CoordinatorEventConnector::new( - Arc::new(policy), - SOURCE, - vec![0x41; MIN_HMAC_SHA256_KEY_BYTES - 1], - Duration::from_secs(1), - ) - .expect_err("the short key must be refused"), - CoordinatorEventConfigError::Invalid - ); - } - #[tokio::test] async fn an_unsignable_item_is_refused_without_sending() { let fixture = FixtureReceiver::start(vec![Answer::admitted()]).await; @@ -670,7 +601,7 @@ mod tests { } #[tokio::test] - async fn retries_keep_event_bytes_and_refresh_attempt_metadata_and_signature() { + async fn a_signed_event_carries_the_envelope_id_as_webhook_id_on_every_attempt() { let fixture = FixtureReceiver::start(vec![Answer::admitted(), Answer::admitted()]).await; let (connector, receiver) = connector(&fixture); let event = event(json!({"item": {"age": "045"}})); @@ -680,7 +611,6 @@ mod tests { run_id: RUN_ID.to_string() } ); - tokio::time::sleep(Duration::from_millis(2)).await; assert_eq!( connector.admit(&receiver, event, 1, 2).await, CoordinatorEventOutcome::Admitted { @@ -692,47 +622,133 @@ mod tests { assert_eq!(requests[0].body, requests[1].body); assert_eq!(requests[0].method, "POST"); assert_eq!(requests[0].target, "/v1/events/case-ingestion/submitted"); - assert_eq!(requests[0].headers["x-registry-delivery-attempt"], "1"); - assert_eq!(requests[1].headers["x-registry-delivery-attempt"], "2"); - assert_ne!( - requests[0].headers["x-registry-delivery-time"], - requests[1].headers["x-registry-delivery-time"] - ); - assert_ne!( - requests[0].headers["x-registry-signature"], - requests[1].headers["x-registry-signature"] - ); for request in &requests { - let header = |name: &str| { - request.headers[name] - .to_str() - .expect("the delivery header is text") - }; - verify_v1_authenticity( - KEY, - SignatureFields { - id: header("ce-id"), - source: header("ce-source"), - event_type: header("ce-type"), - time: header("ce-time"), - data_schema: header("ce-dataschema"), - generation: header("x-registry-event-generation"), - attempt: header("x-registry-delivery-attempt"), - delivery_time: header("x-registry-delivery-time"), - method: &request.method, - request_target: &request.target, - content_type: header("content-type"), - idempotency_key: header("idempotency-key"), - body: &request.body, - }, - header("x-registry-signature"), - ) - .expect("the shared cryptographic verifier accepts the attempt"); - assert_eq!(header("ce-id"), EVENT_ID); - assert_eq!(header("ce-source"), SOURCE); + assert_eq!(request.headers["webhook-id"], EVENT_ID); + let envelope = + HookEnvelope::from_canonical_bytes(&request.body, &EnvelopeLimits::default()) + .unwrap(); + assert_eq!(envelope.id, EVENT_ID); } } + #[tokio::test] + async fn a_signed_event_signs_id_timestamp_and_the_exact_body() { + let fixture = FixtureReceiver::start(vec![Answer::admitted()]).await; + let (connector, receiver) = connector(&fixture); + connector + .admit(&receiver, event(json!({"item": "value"})), 1, 1) + .await; + let requests = fixture.requests(); + let request = &requests[0]; + let header = |name: &str| request.headers[name].to_str().unwrap(); + assert_eq!(header("accept"), "application/json"); + assert_eq!(header("content-type"), "application/json"); + let mut application_headers = request + .headers + .keys() + .map(|name| name.as_str()) + .filter(|name| !matches!(*name, "host" | "content-length")) + .collect::>(); + application_headers.sort_unstable(); + assert_eq!( + application_headers, + [ + "accept", + "content-type", + "webhook-id", + "webhook-signature", + "webhook-timestamp", + ] + ); + verify( + &keys(KEY, None), + SignedContent { + id: header("webhook-id"), + timestamp: header("webhook-timestamp"), + signature: header("webhook-signature"), + body: &request.body, + }, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .expect("the signature covers the id, timestamp and exact body"); + } + + #[tokio::test] + async fn a_revised_trigger_signs_with_its_own_key() { + let fixture = FixtureReceiver::start(vec![Answer::admitted()]).await; + let (connector, _) = connector(&fixture); + let revised_key = &[0x6a; 32]; + let receiver = CoordinatorEventReceiver::new( + "case-ingestion", + "revised", + EVENT_TYPE, + DATA_SCHEMA, + keys(revised_key, None), + ) + .unwrap(); + connector + .admit(&receiver, event(json!({"item": "value"})), 1, 1) + .await; + let requests = fixture.requests(); + let request = &requests[0]; + assert_eq!(request.target, "/v1/events/case-ingestion/revised"); + let content = || SignedContent { + id: request.headers["webhook-id"].to_str().unwrap(), + timestamp: request.headers["webhook-timestamp"].to_str().unwrap(), + signature: request.headers["webhook-signature"].to_str().unwrap(), + body: &request.body, + }; + let now = SystemTime::now(); + assert!(verify(&keys(KEY, None), content(), now, DELIVERY_TOLERANCE).is_err()); + verify(&keys(revised_key, None), content(), now, DELIVERY_TOLERANCE).unwrap(); + } + + #[tokio::test] + async fn a_rotating_trigger_sends_the_current_signature_first() { + let fixture = FixtureReceiver::start(vec![Answer::admitted()]).await; + let (connector, _) = connector(&fixture); + let previous_key = &[0x7a; 32]; + let receiver = CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + keys(KEY, Some(previous_key)), + ) + .unwrap(); + connector + .admit(&receiver, event(json!({"item": "value"})), 1, 1) + .await; + let requests = fixture.requests(); + let request = &requests[0]; + let timestamp = request.headers["webhook-timestamp"] + .to_str() + .unwrap() + .parse() + .unwrap(); + let current = sign(&keys(KEY, None), EVENT_ID, timestamp, &request.body).unwrap(); + let previous = sign( + &keys(previous_key, None), + EVENT_ID, + timestamp, + &request.body, + ) + .unwrap(); + assert_eq!( + request.headers["webhook-signature"], + format!("{current} {previous}") + ); + } + + fn keys(current: &[u8], previous: Option<&[u8]>) -> DeliveryKeys { + DeliveryKeys::new( + DeliveryKey::new(current).unwrap(), + previous.map(|key| DeliveryKey::new(key).unwrap()), + ) + .unwrap() + } + #[tokio::test] async fn the_current_coordinator_admission_matrix_is_closed() { let item_refusals = [ @@ -756,7 +772,6 @@ mod tests { (413, "request.body-too-large"), (500, "runtime.failure"), (503, "audit.response-unavailable"), - (503, "event.source-unavailable"), (503, "service.unavailable"), ]; let answers = item_refusals @@ -791,6 +806,7 @@ mod tests { let fixture = FixtureReceiver::start(vec![ Answer::problem(409, "event.invalid"), Answer::problem(409, "future.problem"), + Answer::problem(503, "future.problem"), Answer { status: StatusCode::BAD_REQUEST, content_type: "application/json", @@ -800,7 +816,7 @@ mod tests { ]) .await; let (connector, receiver) = connector(&fixture); - for _ in 0..3 { + for _ in 0..4 { assert_eq!( connector .admit(&receiver, event(json!({"item": true})), 1, 1) @@ -815,35 +831,20 @@ mod tests { #[test] fn event_receiver_validation_is_value_free_and_bounded() { assert_eq!( - CoordinatorEventReceiver::new("Bad", "trigger", EVENT_TYPE, DATA_SCHEMA) - .expect_err("the workflow id is invalid"), + CoordinatorEventReceiver::new( + "Bad", + "trigger", + EVENT_TYPE, + DATA_SCHEMA, + keys(KEY, None) + ) + .expect_err("the workflow id is invalid"), CoordinatorEventConfigError::Invalid ); assert_eq!( - CoordinatorEventReceiver::new("workflow", "trigger", "", DATA_SCHEMA) + CoordinatorEventReceiver::new("workflow", "trigger", "", DATA_SCHEMA, keys(KEY, None)) .expect_err("the event type is empty"), CoordinatorEventConfigError::Invalid ); } - - #[test] - fn the_fixture_captures_only_the_twelve_closed_delivery_headers() { - let expected = [ - "ce-specversion", - "ce-id", - "ce-source", - "ce-type", - "ce-time", - "ce-dataschema", - "x-registry-event-generation", - "x-registry-delivery-attempt", - "x-registry-delivery-time", - "content-type", - "idempotency-key", - "x-registry-signature", - ]; - for name in expected { - HeaderName::from_bytes(name.as_bytes()).expect("a valid header name"); - } - } } diff --git a/crates/registry-adapter-core/src/checks.rs b/crates/registry-adapter-core/src/checks.rs index 59b04b5691..6d0a9360eb 100644 --- a/crates/registry-adapter-core/src/checks.rs +++ b/crates/registry-adapter-core/src/checks.rs @@ -4747,6 +4747,30 @@ pub fn check_project(workspace: &Workspace<'_>) -> Vec { "Name a record type the project declares.", )); } + // The listener answers the effective-contract, health and ready routes + // itself, so a binding whose concrete path is one of them would be + // advertised and never served. + if let Some(operation) = operation { + let concrete = crate::concrete_facade_path( + &operation.path, + operation.record_type_parameter.as_str(), + binding.record_type.as_str(), + ); + if [ + WELL_KNOWN_PATH, + registry_platform_httputil::probe::HEALTH_PATH, + registry_platform_httputil::probe::READY_PATH, + ] + .contains(&concrete.as_str()) + { + findings.push(finding( + CheckCode::ProjectReservedFacadePath, + &format!("{prefix}/recordType"), + "the binding's concrete facade path is reserved for the effective-contract, health or ready route", + "Rename the record type, or change the operation path, so the concrete path is not the effective-contract, health or ready path.", + )); + } + } // A search binding filters on declared fields of its bound record // type: the facade // offers exactly the declared list as typed equality query @@ -5869,8 +5893,10 @@ fn direct_route_closure<'a>( (closure, unresolved) } +/// The effective-contract route the Adapter serves on the facade listener. +const WELL_KNOWN_PATH: &str = "/.well-known/registry-adapter/effective-contract"; + fn async_status_path_collision_checks(workspace: &Workspace<'_>) -> Vec { - const WELL_KNOWN_PATH: &str = "/.well-known/registry-adapter/effective-contract"; let mut findings = Vec::new(); let statuses: Vec<(usize, &str, String)> = workspace .profile @@ -5909,8 +5935,9 @@ fn async_status_path_collision_checks(workspace: &Workspace<'_>) -> Vec, runtime: &AdapterRuntimeConfig) -> Vec { let mut findings = check_endpoint_bindings(workspace, &runtime.endpoint_bindings()); - if let Err(error) = runtime.oidc.check("oidc", true) { + if let Err(error) = runtime.oidc.check_without_posture("oidc", true) { findings.push(finding( CheckCode::RuntimeInvalidOrigin, "/oidc", @@ -6995,7 +7022,7 @@ fn check_token_endpoint( /// address, so the parse below would read every IPv6 loopback as /// non-loopback. fn is_loopback_origin(url: ®istry_platform_yaml::Url) -> bool { - literal_origin_address(url).is_some_and(|address| address.is_loopback()) + literal_origin_address(url).is_some_and(registry_platform_httputil::loopback::loopback_address) } /// The address literal a bound origin's host carries, when it carries @@ -7016,14 +7043,9 @@ fn literal_origin_address(url: ®istry_platform_yaml::Url) -> Option bool { - let parsed = url.to_url(); - if parsed + url.to_url() .host_str() - .is_some_and(|host| host.eq_ignore_ascii_case("localhost")) - { - return true; - } - literal_origin_address(url).is_some_and(|address| address.is_loopback()) + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// The one plain-HTTP rule: @@ -7046,9 +7068,11 @@ pub fn plain_http_origin_admitted( .iter() .any(|cidr| cidr.contains(address)), // A named host resolves at send, where the same containment rule - // runs on the answers; the check cannot resolve, so it defers - // instead of refusing what the send admits. - None => true, + // runs on the answers; the check cannot resolve, so it defers to the + // send. With an empty `allowedPrivateCidrs` the send admits no + // private address, so the check refuses the origin and names the + // missing range. + None => !allowed_private_cidrs.is_empty(), } } @@ -9250,6 +9274,67 @@ mod tests { ); } + /// A binding whose concrete path is the effective-contract, health or + /// ready route is refused, because the listener answers those routes + /// itself and never serves the binding. + #[test] + fn a_binding_on_a_reserved_facade_path_is_refused() { + for (path, record_type, reserved) in [ + ("/{type}", "health", true), + ("/{type}", "ready", true), + ( + "/.well-known/registry-adapter/{type}", + "effective-contract", + true, + ), + ("/{type}", "cases", false), + ("/health/{type}", "health", false), + ] { + let (mut profile, mut pack, mut project) = async_workspace_parts(); + let mut read = operation("cases-find", HttpMethod::Get); + read.path = path.to_string(); + read.path_parameters = UniqueList::new(vec![local("type")]).expect("parameters"); + read.record_type_parameter = local("type"); + read.record_id_parameter = None; + profile.operations = + UniqueIdList::new(vec![profile.operations[0].clone(), read]).expect("operations"); + let mut routes = pack.routes.into_vec(); + routes.push(RouteDefinition { + id: local("find-case"), + from: RouteFrom { + uri: direct("find-case"), + }, + steps: vec![to_get("case-api")], + }); + pack.routes = UniqueIdList::new(routes).expect("routes"); + let mut record_types = project.record_types.into_vec(); + record_types.push(RecordType { + name: local(record_type), + fields: record_types[0].fields.clone(), + }); + project.record_types = UniqueIdList::new(record_types).expect("record types"); + let mut bindings = project.bindings.into_vec(); + bindings.push(Binding { + async_completion: None, + id: local("find-case"), + operation: id("cases-find"), + record_type: local(record_type), + route: id("find-case"), + filters: UniqueList::new(Vec::new()).expect("empty"), + maximum_upstream_calls: BoundedU64::new(1).expect("budget"), + }); + project.bindings = UniqueIdList::new(bindings).expect("bindings"); + let findings = check_project(&workspace(&profile, &pack, &project)); + let reported = findings + .iter() + .any(|finding| finding.code == CheckCode::ProjectReservedFacadePath.code()); + assert_eq!( + reported, reserved, + "{path} with {record_type}: {findings:?}" + ); + } + } + /// A write operation needs a request envelope naming the record slot; /// a read operation needs none. #[test] @@ -13976,6 +14061,41 @@ mod tests { assert!( !codes(&check_runtime(&ws, &named)).contains(&CheckCode::RuntimeInsecureOrigin.code()) ); + // With no declared CIDR the send admits no private address, so the + // check refuses the named host and names the missing range. + let undeclared = runtime_builder(vec![oauth_binding("http://internal-api:8080")]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&undeclared); + assert_has( + &check_runtime(&ws, &undeclared), + CheckCode::RuntimeInsecureOrigin, + ); + // Every loopback spelling is the loopback exception; a name that only + // looks like it is a named host. + for origin in [ + "http://localhost:8081", + "http://127.0.0.2:8081", + "http://[::1]:8081", + "http://[::ffff:127.0.0.1]:8081", + ] { + let spelled = runtime_builder(vec![oauth_binding(origin)]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&spelled); + assert!( + !codes(&check_runtime(&ws, &spelled)) + .contains(&CheckCode::RuntimeInsecureOrigin.code()), + "{origin}" + ); + } + for origin in ["http://a.localhost:8081", "http://localhost.:8081"] { + let spelled = runtime_builder(vec![oauth_binding(origin)]); + let mut ws = workspace(&profile, &pack, &project); + ws.runtime = Some(&spelled); + assert_has( + &check_runtime(&ws, &spelled), + CheckCode::RuntimeInsecureOrigin, + ); + } } #[test] diff --git a/crates/registry-adapter-core/src/diagnostics.rs b/crates/registry-adapter-core/src/diagnostics.rs index 242c714a2f..2e138c8a67 100644 --- a/crates/registry-adapter-core/src/diagnostics.rs +++ b/crates/registry-adapter-core/src/diagnostics.rs @@ -103,6 +103,7 @@ pub enum CheckCode { ProjectPinDigestMismatch, ProjectPinVersionMismatch, ProjectRequiredParameterUnbound, + ProjectReservedFacadePath, ProjectTemplateNotInstantiated, ProjectTransformBindingUnknown, ProjectTransformEntrypoint, @@ -257,6 +258,7 @@ impl CheckCode { Self::ProjectPinDigestMismatch, Self::ProjectPinVersionMismatch, Self::ProjectRequiredParameterUnbound, + Self::ProjectReservedFacadePath, Self::ProjectTemplateNotInstantiated, Self::ProjectTransformBindingUnknown, Self::ProjectTransformEntrypoint, @@ -437,6 +439,7 @@ impl CheckCode { Self::ProjectPinDigestMismatch => "adapter.project.pin-digest-mismatch", Self::ProjectPinVersionMismatch => "adapter.project.pin-version-mismatch", Self::ProjectRequiredParameterUnbound => "adapter.project.required-parameter-unbound", + Self::ProjectReservedFacadePath => "adapter.project.reserved-facade-path", Self::ProjectTemplateNotInstantiated => "adapter.project.template-not-instantiated", Self::ProjectTransformBindingUnknown => "adapter.project.transform-binding-unknown", Self::ProjectTransformEntrypoint => "adapter.project.transform-entrypoint", @@ -653,6 +656,7 @@ impl CheckCode { | Self::ProjectPinDigestMismatch | Self::ProjectPinVersionMismatch | Self::ProjectRequiredParameterUnbound + | Self::ProjectReservedFacadePath | Self::ProjectTemplateNotInstantiated | Self::ProjectTransformBindingUnknown | Self::ProjectTransformEntrypoint diff --git a/crates/registry-adapter-core/src/profile.rs b/crates/registry-adapter-core/src/profile.rs index cd32a2a5ed..52d5460c5b 100644 --- a/crates/registry-adapter-core/src/profile.rs +++ b/crates/registry-adapter-core/src/profile.rs @@ -428,6 +428,15 @@ impl<'de> Deserialize<'de> for ProfileOperation { } } +/// The facade path of one bound operation: the record type in place of the +/// record-type parameter's placeholder, wherever the placeholder sits in the +/// path. The listener, the effective contract and the checks read the path +/// through this one rule. +#[must_use] +pub fn concrete_facade_path(path: &str, record_type_parameter: &str, record_type: &str) -> String { + path.replace(&format!("{{{record_type_parameter}}}"), record_type) +} + impl ProfileOperation { /// Whether the operation only reads: a GET, or a POST declaring /// `readOnly`. @@ -603,6 +612,23 @@ fn default_success_status() -> registry_platform_yaml::BoundedU32<200, 299> { #[cfg(test)] mod tests { + #[test] + fn the_concrete_facade_path_substitutes_a_whole_or_partial_segment() { + use super::concrete_facade_path; + assert_eq!( + concrete_facade_path("/v1/{type}/{id}", "type", "case"), + "/v1/case/{id}" + ); + assert_eq!( + concrete_facade_path("/v1/{type}.json", "type", "case"), + "/v1/case.json" + ); + assert_eq!( + concrete_facade_path("/v1/cases", "type", "case"), + "/v1/cases" + ); + } + use super::*; #[test] diff --git a/crates/registry-adapter-engine/Cargo.toml b/crates/registry-adapter-engine/Cargo.toml index fc26469fb2..a17bd766b8 100644 --- a/crates/registry-adapter-engine/Cargo.toml +++ b/crates/registry-adapter-engine/Cargo.toml @@ -58,6 +58,7 @@ registry-platform-script.workspace = true registry-platform-yaml.workspace = true [dev-dependencies] +registry-platform-httputil = { workspace = true, features = ["test-support"] } registry-platform-sqlite = { workspace = true, features = ["fixture"] } serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-adapter-engine/src/effective_contract.rs b/crates/registry-adapter-engine/src/effective_contract.rs index 388f6b58fb..9bc611ab47 100644 --- a/crates/registry-adapter-engine/src/effective_contract.rs +++ b/crates/registry-adapter-engine/src/effective_contract.rs @@ -316,8 +316,9 @@ fn effective_operation( .operations .get(&served.operation) .ok_or_else(|| ContractError::MissingOperation(served.operation.clone()))?; - let concrete_path = served.method_path.replace( - &format!("{{{}}}", served.record_type_parameter), + let concrete_path = registry_adapter_core::concrete_facade_path( + &served.method_path, + &served.record_type_parameter, &served.record_type, ); let target = served.target_contract.as_ref(); @@ -432,7 +433,7 @@ fn public_unserved_reason(code: &str) -> &'static str { } "adapter.operation.route-missing" => "the binding has no loaded route", "adapter.operation.reserved-facade-path" => { - "the facade path is reserved for the Adapter effective-contract route" + "the facade path is reserved for the Adapter effective-contract, health and ready routes" } "adapter.operation.cursor-key-missing" => { "the paginated operation has no configured cursor key" diff --git a/crates/registry-adapter-engine/src/egress.rs b/crates/registry-adapter-engine/src/egress.rs index 0532cc5b6e..30e94b6a1b 100644 --- a/crates/registry-adapter-engine/src/egress.rs +++ b/crates/registry-adapter-engine/src/egress.rs @@ -2137,21 +2137,19 @@ pub(crate) fn destination_profile(parsed_base: &url::Url) -> DestinationProfile } match parsed_base.scheme() { "https" => DestinationProfile::ProductionHttps, - _ if denotes_loopback(parsed_base) => DestinationProfile::LoopbackDevelopmentHttp, + _ if denotes_loopback(parsed_base) => DestinationProfile::LoopbackHttp, _ => DestinationProfile::PrivateServiceHttp, } } /// Whether the origin's host explicitly denotes loopback: the name /// `localhost` or a loopback address literal, the platform's own -/// admission rule for the development profile. +/// admission rule for the development profile. The destination policy pins +/// the name to loopback addresses when it connects. pub(crate) fn denotes_loopback(origin: &url::Url) -> bool { - match origin.host() { - Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), - None => false, - } + origin + .host_str() + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// Whether a destination profile admits a token endpoint: the same @@ -2163,7 +2161,7 @@ pub(crate) fn denotes_loopback(origin: &url::Url) -> bool { /// is admitted only under the feature that enables it. pub(crate) fn profile_admits_token_endpoints(profile: DestinationProfile) -> bool { match profile { - DestinationProfile::ProductionHttps | DestinationProfile::LoopbackDevelopmentHttp => true, + DestinationProfile::ProductionHttps | DestinationProfile::LoopbackHttp => true, #[cfg(feature = "postgres-test")] DestinationProfile::PinnedLoopbackHttpsTest => true, _ => false, @@ -3702,11 +3700,11 @@ mod tests { ); assert_eq!( destination_profile(&loopback), - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp ); assert_eq!( destination_profile(&localhost), - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp ); assert_eq!( destination_profile(&private), @@ -3716,6 +3714,26 @@ mod tests { destination_profile(&public_name), DestinationProfile::PrivateServiceHttp ); + for spelled in [ + "http://127.0.0.2:8080/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + let origin = url::Url::parse(spelled).expect("parsed"); + assert_eq!( + destination_profile(&origin), + DestinationProfile::LoopbackHttp, + "{spelled}" + ); + } + for spelled in ["http://a.localhost:8080/", "http://localhost.:8080/"] { + let origin = url::Url::parse(spelled).expect("parsed"); + assert_eq!( + destination_profile(&origin), + DestinationProfile::PrivateServiceHttp, + "{spelled}" + ); + } } /// Under the postgres-test feature an https loopback origin takes @@ -3751,7 +3769,7 @@ mod tests { DestinationProfile::ProductionHttps )); assert!(profile_admits_token_endpoints( - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp )); assert!(!profile_admits_token_endpoints( DestinationProfile::PrivateServiceHttp diff --git a/crates/registry-adapter-engine/src/job_sources.rs b/crates/registry-adapter-engine/src/job_sources.rs index cf94166b65..d4c5f9953e 100644 --- a/crates/registry-adapter-engine/src/job_sources.rs +++ b/crates/registry-adapter-engine/src/job_sources.rs @@ -272,7 +272,7 @@ impl JobRuntimeConfig { // platforms). A path that cannot be canonicalized is left to // the loader's own unreadable refusal. let absolute = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: registry_adapter_core::ADAPTER_JOB_RUNTIME_API_VERSION, kind: registry_adapter_core::ADAPTER_JOB_RUNTIME_KIND, }) @@ -2098,7 +2098,7 @@ endpoints: [] /// The job runtime config reads through the shared loader. #[test] fn the_loader_reads_the_job_runtime_config() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2112,7 +2112,7 @@ endpoints: [] /// reader's own code, pointer, and source position. #[test] fn an_undeclared_member_refuses_with_its_pointer_at_every_depth() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2147,7 +2147,7 @@ endpoints: [] /// shape. #[test] fn the_job_and_facade_envelopes_refuse_each_other() { - let job = registry_platform_config::RuntimeConfigLoader::new( + let job = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2161,7 +2161,7 @@ endpoints: [] .is_err(), "the job loader refuses the facade envelope" ); - let facade = registry_platform_config::RuntimeConfigLoader::new( + let facade = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, @@ -2207,7 +2207,7 @@ endpoints: [] /// and how to fix it, not only that the value is invalid. #[test] fn each_hook_ingress_refusal_names_its_rule_and_the_fix() { - let loader = registry_platform_config::RuntimeConfigLoader::new( + let loader = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, @@ -2261,7 +2261,7 @@ endpoints: [] } fn loader() -> registry_platform_config::RuntimeConfigLoader { - registry_platform_config::RuntimeConfigLoader::new( + registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: ADAPTER_JOB_RUNTIME_API_VERSION, kind: ADAPTER_JOB_RUNTIME_KIND, diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index f64cfb7595..05fd656b94 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -341,8 +341,9 @@ fn path_conflict(served: &[ServedOperation], candidate: &ServedOperation) -> Opt /// The facade path a served operation answers, with its record type in /// place of the record-type parameter. fn concrete_path(operation: &ServedOperation) -> String { - operation.method_path.replace( - &format!("{{{}}}", operation.record_type_parameter), + registry_adapter_core::concrete_facade_path( + &operation.method_path, + &operation.record_type_parameter, &operation.record_type, ) } @@ -509,11 +510,9 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { "declare at least one provider under secretProviders and give file.root an absolute path" } SecretError::Unavailable => { - "create the file under secretProviders.file.root or set the variable; a symlink reads as missing" - } - SecretError::UnsafeFile => { - "make it a regular file owned by the service user, mode 0600 or 0400, with one hard link" + "create the file under secretProviders.file.root or set the variable" } + SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::Read => "check that the service user can read the secret file", SecretError::InvalidValue => { "store a non-empty value with no NUL byte, within the secret size limit" @@ -681,7 +680,7 @@ fn load_inner( let absolute = std::fs::canonicalize(runtime_path).map_err(|_| LoadError::Unreadable { path: runtime_path.display().to_string(), })?; - let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { + let runtime = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, }) @@ -1226,14 +1225,21 @@ fn compile_binding( "the binding names no profile operation", ) })?; - let concrete_method_path = operation.path.replace( - &format!("{{{}}}", operation.record_type_parameter.as_str()), + let concrete_method_path = registry_adapter_core::concrete_facade_path( + &operation.path, + operation.record_type_parameter.as_str(), binding.record_type.as_str(), ); - if concrete_method_path == crate::effective_contract::WELL_KNOWN_PATH { + if [ + crate::effective_contract::WELL_KNOWN_PATH, + registry_platform_httputil::probe::HEALTH_PATH, + registry_platform_httputil::probe::READY_PATH, + ] + .contains(&concrete_method_path.as_str()) + { return Err(not_served( UnservedReason::ReservedFacadePath, - "the facade path is reserved for the Adapter effective-contract route", + "the facade path is reserved for the Adapter effective-contract, health and ready routes", )); } let is_post_read = @@ -2042,10 +2048,10 @@ mod tests { } assert_ne!(unsafe_file, missing, "the two causes must read differently"); assert!(unsafe_file.contains("unsafe"), "{unsafe_file}"); - assert!(unsafe_file.contains("0600 or 0400"), "{unsafe_file}"); - assert!(unsafe_file.contains("owned by"), "{unsafe_file}"); + assert!(unsafe_file.contains("0400 or 0600"), "{unsafe_file}"); + assert!(unsafe_file.contains("runtime user"), "{unsafe_file}"); assert!(missing.contains("unavailable"), "{missing}"); - assert!(missing.contains("symlink"), "{missing}"); + assert!(missing.contains("secretProviders.file.root"), "{missing}"); assert!(disabled.contains("disabled provider"), "{disabled}"); assert!(disabled.contains("secretProviders"), "{disabled}"); } diff --git a/crates/registry-adapter-job/Cargo.toml b/crates/registry-adapter-job/Cargo.toml index b3f705b5ea..cb64f9591a 100644 --- a/crates/registry-adapter-job/Cargo.toml +++ b/crates/registry-adapter-job/Cargo.toml @@ -21,6 +21,7 @@ default = [] # wake the interval pass loop early. The facade never enables or links it. job-hook = [ "dep:base64", + "dep:registry-platform-authcommon", "dep:futures", "dep:registry-platform-crypto", "dep:registry-platform-ratelimit", @@ -63,6 +64,7 @@ direct-breg = [ # Enables only the job host's platform-signed Coordinator event # destination. No Coordinator crate or client is linked. signed-coordinator-event = [ + "dep:registry-platform-crypto", "dep:registry-adapter-connectors", "dep:registry-platform-httputil", "registry-adapter-connectors/coordinator-event", @@ -90,10 +92,12 @@ required-features = ["job-hook", "postgres-test"] registry-adapter-engine.workspace = true registry-adapter-core.workspace = true registry-adapter-connectors = { workspace = true, optional = true } +registry-platform-authcommon = { workspace = true, optional = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-httputil = { workspace = true, optional = true } +registry-platform-loopback.workspace = true registry-platform-metrics.workspace = true registry-platform-ratelimit = { workspace = true, optional = true } registry-platform-yaml.workspace = true diff --git a/crates/registry-adapter-job/src/destination.rs b/crates/registry-adapter-job/src/destination.rs index 459aa1d73d..84557ced66 100644 --- a/crates/registry-adapter-job/src/destination.rs +++ b/crates/registry-adapter-job/src/destination.rs @@ -275,8 +275,9 @@ impl FixtureDestination { .rsplit_once(':') .map(|(host, _)| host) .unwrap_or(authority); - let loopback = matches!(host, "127.0.0.1" | "::1" | "[::1]" | "localhost"); - if !loopback { + // The fixture receiver is never a real hop, so the name `localhost` + // is accepted without pinning the connection. + if registry_platform_loopback::loopback_host(host).is_none() { return Err(format!( "the fixture url host {host} is not a loopback address; the fixture receiver runs on this machine" )); diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 0774d3bd57..0ead8853d8 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -18,6 +18,7 @@ use base64::{engine::general_purpose::STANDARD, Engine as _}; use futures::StreamExt as _; use registry_adapter_core::AdapterJob; use registry_adapter_engine::job_sources::{HookSourceConfig, JobRuntimeConfig}; +use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote}; use registry_platform_config::{ProtectedSecret, SecretError, SecretResolver}; use registry_platform_crypto::mac::constant_time_eq; use registry_platform_ratelimit::token_bucket::{ @@ -264,9 +265,7 @@ fn resolve_member( "the environment variable is not set" } SecretError::Unavailable => "the secret file is missing", - SecretError::UnsafeFile => { - "the secret file must be a regular file with mode 0400 or 0600" - } + SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::Read => "the secret file could not be read", SecretError::InvalidValue => "the secret is empty or contains a NUL byte", SecretError::ProviderDisabled => { @@ -365,35 +364,43 @@ impl BasicCredential { Ok(Self { username, password }) } - fn authenticates(&self, authorization: &[u8]) -> bool { + /// `Ok` for the exact canonical pair, else the check that refused it. + fn authenticates(&self, authorization: &[u8]) -> Result<(), FailedCheck> { + let malformed = FailedCheck::CredentialMalformed; if authorization.len() > MAX_BASIC_PAYLOAD_BYTES + 6 { - return false; + return Err(malformed); } let Some((scheme, payload)) = split_once(authorization, b' ') else { - return false; + return Err(malformed); }; - if !scheme.eq_ignore_ascii_case(b"Basic") - || payload.is_empty() + if !scheme.eq_ignore_ascii_case(b"Basic") { + return Err(FailedCheck::CredentialMissing); + } + if payload.is_empty() || payload.iter().any(u8::is_ascii_whitespace) || payload.len() > MAX_BASIC_PAYLOAD_BYTES { - return false; + return Err(malformed); } let Ok(mut decoded) = STANDARD.decode(payload).map(Zeroizing::new) else { - return false; + return Err(malformed); }; let canonical = Zeroizing::new(STANDARD.encode(decoded.as_slice())); if canonical.as_bytes() != payload { - return false; + return Err(malformed); } let Some(colon) = decoded.iter().position(|byte| *byte == b':') else { - return false; + return Err(malformed); }; let password = Zeroizing::new(decoded.split_off(colon + 1)); decoded.truncate(colon); let username_matches = constant_time_eq(decoded.as_slice(), self.username.expose_secret()); let password_matches = constant_time_eq(password.as_slice(), self.password.expose_secret()); - username_matches & password_matches + if username_matches & password_matches { + Ok(()) + } else { + Err(FailedCheck::SharedSecret) + } } } @@ -434,6 +441,9 @@ async fn receive_hook_until( if let Some(reason) = refusal_reason(answer.status()) { metrics.record_hook_refusal(reason); } + if let Some(note) = answer.extensions().get::() { + record_refusal!(metrics.refusals(), *note); + } answer } @@ -468,11 +478,11 @@ async fn answer_hook( None, ); } - if !authenticated(request.headers(), &source.credential) { - return response( + if let Err(check) = authenticated(request.headers(), &source.credential) { + return refusal( StatusCode::UNAUTHORIZED, "adapter.job.hook-unauthenticated", - None, + check, ); } let retry_after = match source.limiter.check("source", 1).await { @@ -491,10 +501,13 @@ async fn answer_hook( } }; if let Some(retry_after) = retry_after { - return response( - StatusCode::TOO_MANY_REQUESTS, - "adapter.job.hook-rate-limited", - Some(retry_after.as_secs_f64().ceil().max(1.0) as u64), + return noted( + response( + StatusCode::TOO_MANY_REQUESTS, + "adapter.job.hook-rate-limited", + Some(retry_after.as_secs_f64().ceil().max(1.0) as u64), + ), + FailedCheck::RateLimit, ); } let discarded = tokio::select! { @@ -532,17 +545,23 @@ async fn answer_hook( } } -fn authenticated(headers: &HeaderMap, credential: &BasicCredential) -> bool { +fn authenticated(headers: &HeaderMap, credential: &BasicCredential) -> Result<(), FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); let Some(value) = values.next() else { - return false; + return Err(FailedCheck::CredentialMissing); }; if values.next().is_some() { - return false; + return Err(FailedCheck::CredentialMalformed); } credential.authenticates(value.as_bytes()) } +/// Mark a response as the refusal of `check`, for the ingress to record. +fn noted(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum HookRefusal { BodyTooLarge, @@ -564,7 +583,28 @@ async fn discard_body(body: Body) -> Result { Ok(total) } +/// A refused caller's answer, carrying the check that refused it. Every 401 +/// or 403 is built here. +fn refusal(status: StatusCode, code: &'static str, check: FailedCheck) -> Response { + noted(answer(status, code, None), check) +} + +/// An answer that is not a refusal of the caller. A refusal status that +/// arrives here has no check to count, which a debug build refuses outright +/// and a release build logs. fn response(status: StatusCode, code: &'static str, retry_after: Option) -> Response { + if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + status = status.as_u16(), + code, + "a refusal was answered without its failed check" + ); + } + answer(status, code, retry_after) +} + +fn answer(status: StatusCode, code: &'static str, retry_after: Option) -> Response { let body = match code { "started" => r#"{"status":"started"}"#, "joined" => r#"{"status":"joined"}"#, @@ -604,6 +644,29 @@ mod tests { use std::io::Write as _; use std::os::unix::fs::PermissionsExt as _; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn an_unauthorized_answer_without_its_check_is_not_built() { + let _ = response( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", + None, + ); + } + + #[test] + fn an_unauthorized_answer_carries_its_check_and_challenge() { + let answer = refusal( + StatusCode::UNAUTHORIZED, + "adapter.job.hook-unauthenticated", + FailedCheck::SharedSecret, + ); + assert_eq!(answer.status(), StatusCode::UNAUTHORIZED); + assert!(answer.headers().contains_key(WWW_AUTHENTICATE)); + assert!(answer.extensions().get::().is_some()); + } + async fn test_server( path: &str, burst: u32, @@ -801,7 +864,7 @@ mod tests { "Basic {}", STANDARD.encode(b"kobo-webhook:correct horse battery staple") ); - assert!(credential.authenticates(exact.as_bytes())); + assert_eq!(credential.authenticates(exact.as_bytes()), Ok(())); for refused in [ String::new(), "Bearer token".to_string(), @@ -812,7 +875,10 @@ mod tests { STANDARD.encode(b"wrong:correct horse battery staple") ), ] { - assert!(!credential.authenticates(refused.as_bytes()), "{refused:?}"); + assert!( + credential.authenticates(refused.as_bytes()).is_err(), + "{refused:?}" + ); } assert_eq!(format!("{credential:?}"), "BasicCredential([REDACTED])"); } @@ -1104,6 +1170,82 @@ mod tests { ); } + #[tokio::test] + async fn each_refused_credential_is_counted_under_its_check_with_an_unchanged_answer() { + let (root, resolver) = secret_resolver(); + let source = Arc::new(HookSource { + credential: BasicCredential::resolve("kobo-submissions", &source_config(), &resolver) + .expect("the credential resolves"), + limiter: TokenBucketLimiter::new(TokenBucketConfig { + requests_per_minute: 60, + burst: 1, + }) + .expect("a bounded rate limit"), + }); + let metrics = Arc::new(JobMetrics::default()); + let state = IngressState { + sources: Arc::new(BTreeMap::from([("/hooks/kobo".to_string(), source)])), + gate: Arc::new(HookPassGate::default()), + metrics: Arc::clone(&metrics), + }; + let send = |headers: Vec| { + let mut request = Request::builder().method(Method::POST).uri("/hooks/kobo"); + for value in headers { + request = request.header(AUTHORIZATION, value); + } + receive_hook_until( + State(state.clone()), + request.body(Body::empty()).expect("a hook request"), + std::future::pending(), + ) + }; + let password = + std::fs::read_to_string(root.path().join("password")).expect("the synthetic password"); + let good = basic_header(&password); + let wrong = basic_header(&uuid::Uuid::new_v4().to_string()); + let unauthenticated = [ + (vec![], "credential-missing"), + (vec!["Bearer token".to_string()], "credential-missing"), + (vec![good.clone(), good.clone()], "credential-malformed"), + (vec!["Basic !!!".to_string()], "credential-malformed"), + (vec![wrong], "shared-secret"), + ]; + for (headers, check) in &unauthenticated { + let answer = send(headers.clone()).await; + assert_eq!(answer.status(), StatusCode::UNAUTHORIZED, "{check}"); + assert_eq!( + answer.headers().get(WWW_AUTHENTICATE), + Some(&HeaderValue::from_static( + "Basic realm=\"adapter-job-hook\", charset=\"UTF-8\"" + )) + ); + let body = axum::body::to_bytes(answer.into_body(), 1024) + .await + .expect("a static body"); + assert_eq!(&body[..], br#"{"code":"adapter.job.hook-unauthenticated"}"#); + } + assert_eq!( + send(vec![good.clone()]).await.status(), + StatusCode::ACCEPTED + ); + let limited = send(vec![good]).await; + assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(limited.headers().contains_key(RETRY_AFTER)); + let text = metrics.render(None); + let counted = |check: &str| { + let line = format!("adapter_job_request_refusals_total{{check=\"{check}\"}}"); + text.lines() + .find_map(|found| found.strip_prefix(&format!("{line} "))) + .unwrap_or_else(|| panic!("{check} is declared: {text}")) + .to_owned() + }; + assert_eq!(counted("credential-missing"), "2"); + assert_eq!(counted("credential-malformed"), "2"); + assert_eq!(counted("shared-secret"), "1"); + assert_eq!(counted("rate-limit"), "1"); + assert_eq!(counted("scope"), "0"); + } + #[test] fn every_refusal_status_maps_to_its_own_counted_reason() { let table = [ diff --git a/crates/registry-adapter-job/src/metrics.rs b/crates/registry-adapter-job/src/metrics.rs index d4e6d054ad..d5569c5122 100644 --- a/crates/registry-adapter-job/src/metrics.rs +++ b/crates/registry-adapter-job/src/metrics.rs @@ -74,6 +74,8 @@ pub const HOOK_REFUSALS: [&str; 8] = [ ]; pub struct JobMetrics { + #[cfg(feature = "job-hook")] + refusals: registry_platform_authcommon::RefusalRecorder, pass_failures: CounterVec, hook_refusals: CounterVec, sample_failures: CounterVec, @@ -99,6 +101,9 @@ impl Default for JobMetrics { let failures = singles(&PASS_FAILURES); let refusals = singles(&HOOK_REFUSALS); Self { + #[cfg(feature = "job-hook")] + refusals: registry_platform_authcommon::RefusalRecorder::new("adapter_job") + .expect(DECLARATION), pass_failures: CounterVec::new( "adapter_job_pass_failures_total", "Loop passes that did not settle their page, by reason.", @@ -158,6 +163,13 @@ impl JobMetrics { count(&self.hook_refusals, &[reason]); } + /// The recorder behind `adapter_job_request_refusals_total` and the + /// `request refused` log line of the hook ingress. + #[cfg(feature = "job-hook")] + pub(crate) fn refusals(&self) -> ®istry_platform_authcommon::RefusalRecorder { + &self.refusals + } + /// Count one scrape whose item counts could not be read. pub fn record_sample_failure(&self) { count(&self.sample_failures, &[]); @@ -176,6 +188,8 @@ impl JobMetrics { ] { counter.write(&mut out).expect(DECLARATION); } + #[cfg(feature = "job-hook")] + self.refusals.counter().write(&mut out).expect(DECLARATION); out.header( "adapter_job_items", Some("Items in the job store by state, sampled at scrape. Absent when the store could not be read."), diff --git a/crates/registry-adapter-job/src/postgres_source.rs b/crates/registry-adapter-job/src/postgres_source.rs index 998b94e0d1..86f73109b0 100644 --- a/crates/registry-adapter-job/src/postgres_source.rs +++ b/crates/registry-adapter-job/src/postgres_source.rs @@ -9,7 +9,6 @@ use std::collections::BTreeMap; use std::fmt; #[cfg(feature = "postgres-test")] -use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; @@ -228,10 +227,8 @@ impl PooledPostgresSource { } #[cfg(feature = "postgres-test")] PostgresSourceTls::Plaintext => { - let loopback = binding - .host - .parse::() - .is_ok_and(|address| address.is_loopback()); + let loopback = + registry_platform_loopback::loopback_literal(&binding.host).is_some(); if !loopback { return Err(format!( "the plaintext PostgreSQL test source {endpoint} is not numeric loopback; correct {}", diff --git a/crates/registry-adapter-job/src/rabbitmq_source.rs b/crates/registry-adapter-job/src/rabbitmq_source.rs index 25c1eb8c21..afec2f649c 100644 --- a/crates/registry-adapter-job/src/rabbitmq_source.rs +++ b/crates/registry-adapter-job/src/rabbitmq_source.rs @@ -44,8 +44,6 @@ use std::fmt; use std::future::Future; -#[cfg(feature = "rabbitmq-test-plaintext")] -use std::net::IpAddr; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; @@ -320,10 +318,7 @@ impl LapinRabbitMqSource { } #[cfg(feature = "rabbitmq-test-plaintext")] if matches!(config.tls, RabbitMqTls::PlaintextTest) - && !config - .host - .parse::() - .is_ok_and(|address| address.is_loopback()) + && registry_platform_loopback::loopback_literal(&config.host).is_none() { return Err(RabbitMqReadFault::InvalidBounds); } diff --git a/crates/registry-adapter-job/src/runtime_destination.rs b/crates/registry-adapter-job/src/runtime_destination.rs index c365f2b07d..610d6056d0 100644 --- a/crates/registry-adapter-job/src/runtime_destination.rs +++ b/crates/registry-adapter-job/src/runtime_destination.rs @@ -18,7 +18,11 @@ use registry_adapter_core::EndpointBinding; use registry_adapter_core::{AdapterJob, JobDestination}; use registry_adapter_engine::job::JobProgram; use registry_adapter_engine::job_sources::JobRuntimeConfig; -use registry_platform_config::SecretResolver; +use registry_platform_config::{SecretReference as DeliveryKeyReference, SecretResolver}; +#[cfg(feature = "signed-coordinator-event")] +use registry_platform_crypto::delivery_signature::DeliveryKeys; +#[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] +use registry_platform_crypto::delivery_signature::{distinct_delivery_keys, DeliveryKey}; #[cfg(feature = "signed-coordinator-event")] use registry_platform_yaml::ExternalId; use registry_platform_yaml::{BoundedU64, LocalId, SecretReference, Url}; @@ -72,13 +76,26 @@ enum RuntimeDestinationBinding { }, SignedCoordinatorEvent { base_url: Url, - signing_key_ref: SecretReference, + hmac_sha256_key_ref: DeliveryKeyReference, + #[serde(default)] + previous_hmac_sha256_key_ref: Option, + #[serde(default)] + revised_receiver: Option, attempt_timeout_milliseconds: BoundedU64<1, 10_000>, #[serde(default)] tls_trust_profile: Option, }, } +#[cfg_attr(not(feature = "signed-coordinator-event"), allow(dead_code))] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RevisedReceiverBinding { + hmac_sha256_key_ref: DeliveryKeyReference, + #[serde(default)] + previous_hmac_sha256_key_ref: Option, +} + /// Activate the one authored destination from its exact runtime binding. /// Missing features, bindings, secrets, trust material, and kind mismatches /// refuse startup. The fixture destination is never an operational fallback. @@ -89,6 +106,8 @@ pub async fn activate_destination<'a>( ) -> Result, String> { require_compiled_destination(&program.job.destination).map_err(not_compiled_message)?; let bindings = load_runtime_bindings(runtime)?; + #[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] + let keys = resolve_destination_keys(resolver, &bindings)?; match &program.job.destination { JobDestination::DirectBreg { binding, .. } => { let configured = bindings @@ -96,6 +115,7 @@ pub async fn activate_destination<'a>( .ok_or_else(|| missing_binding(binding))?; #[cfg(feature = "direct-breg")] { + drop(keys); activate_direct(program, configured, &runtime.core, resolver).await } #[cfg(not(feature = "direct-breg"))] @@ -110,7 +130,7 @@ pub async fn activate_destination<'a>( .ok_or_else(|| missing_binding(binding))?; #[cfg(feature = "signed-coordinator-event")] { - activate_signed(program, configured, &runtime.core, resolver) + activate_signed(program, configured, &runtime.core, resolver, keys) } #[cfg(not(feature = "signed-coordinator-event"))] { @@ -130,23 +150,46 @@ pub fn check_destination_runtime( ) -> Result<(), String> { require_compiled_destination(&job.destination).map_err(not_compiled_message)?; let bindings = load_runtime_bindings(runtime)?; - let (binding, expected) = match &job.destination { - JobDestination::DirectBreg { binding, .. } => (binding, "direct-breg"), - JobDestination::SignedCoordinatorEvent { binding, .. } => { - (binding, "signed-coordinator-event") - } + let binding = match &job.destination { + JobDestination::DirectBreg { binding, .. } + | JobDestination::SignedCoordinatorEvent { binding, .. } => binding, }; let configured = bindings .get(binding) .ok_or_else(|| missing_binding(binding))?; - let actual = match configured { - RuntimeDestinationBinding::DirectBreg { .. } => "direct-breg", - RuntimeDestinationBinding::SignedCoordinatorEvent { .. } => "signed-coordinator-event", - }; - if actual != expected { - return Err("the runtime destination kind does not match the job destination".to_string()); + match (&job.destination, configured) { + (JobDestination::DirectBreg { .. }, RuntimeDestinationBinding::DirectBreg { .. }) => Ok(()), + ( + JobDestination::SignedCoordinatorEvent { + revised_receiver, .. + }, + RuntimeDestinationBinding::SignedCoordinatorEvent { + revised_receiver: configured_revised, + .. + }, + ) => check_revised_receiver( + binding, + revised_receiver.is_some(), + configured_revised.is_some(), + ), + _ => Err("the runtime destination kind does not match the job destination".to_string()), + } +} + +fn check_revised_receiver( + binding: &LocalId, + authored: bool, + configured: bool, +) -> Result<(), String> { + match (authored, configured) { + (true, false) => Err(format!( + "add `destinations.{binding}.revisedReceiver.hmacSha256KeyRef` for the authored revised receiver" + )), + (false, true) => Err(format!( + "remove `destinations.{binding}.revisedReceiver` because the job declares no revised receiver" + )), + _ => Ok(()), } - Ok(()) } fn load_runtime_bindings( @@ -156,20 +199,44 @@ fn load_runtime_bindings( .destinations .as_ref() .ok_or_else(|| "the runtime config carries no destinations block".to_string())?; - let bindings = - serde_json::from_value::>(bindings.clone()) - .map_err(|error| { - // A missing member is named, because its name is the fix. - // Any other refusal stays value-free: serde's text for it - // can echo the refused value. - let text = error.to_string(); - if text.starts_with("missing field ") { - format!("the runtime destinations block was refused: {text}") - } else { - "the runtime destinations block was refused".to_string() + parse_runtime_bindings(bindings) +} + +fn parse_runtime_bindings( + bindings: &serde_json::Value, +) -> Result, String> { + if let Some(destinations) = bindings.as_object() { + for (id, binding) in destinations { + if binding.get("type").and_then(serde_json::Value::as_str) + != Some("signed-coordinator-event") + { + continue; + } + for (path, entry) in [ + (format!("destinations.{id}"), Some(binding)), + ( + format!("destinations.{id}.revisedReceiver"), + binding.get("revisedReceiver"), + ), + ] { + if entry.is_some_and(|entry| entry.get("signingKeyRef").is_some()) { + return Err(format!( + "replace `{path}.signingKeyRef` with `{path}.hmacSha256KeyRef`" + )); } - })?; - Ok(bindings) + } + } + } + serde_json::from_value(bindings.clone()).map_err(|error| { + // A missing member is named, because its name is the fix. + // Other serde diagnostics can echo refused values. + let text = error.to_string(); + if text.starts_with("missing field ") { + format!("the runtime destinations block was refused: {text}") + } else { + "the runtime destinations block was refused".to_string() + } + }) } fn missing_binding(binding: &LocalId) -> String { @@ -245,7 +312,7 @@ async fn activate_direct<'a>( .with_fetch_url_policy(if token_endpoint.is_https() { FetchUrlPolicy::strict() } else { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() }); if let Some(profile) = token_tls_trust_profile { let roots = registry_adapter_engine::auth::capture_ca_bundle(core, profile.as_str()) @@ -382,12 +449,105 @@ fn direct_breg_proposal_get_refusal(action: &str, profile: &str) -> String { ) } +#[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] +fn resolve_delivery_key( + resolver: &SecretResolver, + path: &str, + reference: &DeliveryKeyReference, +) -> Result { + let secret = resolver + .resolve_binary_reference(reference) + .map_err(|error| { + format!( + "could not resolve {path}: {error}. {}", + error.suggested_action() + ) + })?; + let bytes = secret.expose_secret(); + DeliveryKey::new(bytes).map_err(|error| { + let newline = if bytes.ends_with(b"\n") { + ", ending in a newline" + } else { + "" + }; + format!( + "invalid delivery key at `{path}` ({} bytes{newline}): {error}", + bytes.len() + ) + }) +} + +#[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] +fn resolve_destination_keys( + resolver: &SecretResolver, + bindings: &BTreeMap, +) -> Result, String> { + let mut keys = BTreeMap::new(); + for (id, binding) in bindings { + let RuntimeDestinationBinding::SignedCoordinatorEvent { + hmac_sha256_key_ref, + previous_hmac_sha256_key_ref, + revised_receiver, + .. + } = binding + else { + continue; + }; + let path = format!("destinations.{id}"); + let primary = ( + path.clone(), + hmac_sha256_key_ref, + previous_hmac_sha256_key_ref, + ); + let revised = revised_receiver.as_ref().map(|receiver| { + ( + format!("{path}.revisedReceiver"), + &receiver.hmac_sha256_key_ref, + &receiver.previous_hmac_sha256_key_ref, + ) + }); + for (path, current, previous) in std::iter::once(primary).chain(revised) { + for (member, reference) in [ + ("hmacSha256KeyRef", Some(current)), + ("previousHmacSha256KeyRef", previous.as_ref()), + ] { + if let Some(reference) = reference { + let path = format!("{path}.{member}"); + let key = resolve_delivery_key(resolver, &path, reference)?; + keys.insert(path, key); + } + } + } + } + distinct_delivery_keys(keys.iter().map(|(path, key)| (path.as_str(), key))).map_err(|error| { + let (first, second) = (error.first(), error.second()); + if second + .strip_suffix(".previousHmacSha256KeyRef") + .is_some_and(|receiver| first.strip_suffix(".hmacSha256KeyRef") == Some(receiver)) + { + return format!("{second} holds the same bytes as {first}. To rotate, write 32 new random bytes to the secret {first} references and keep the old bytes behind {second}."); + } + format!("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there.") + })?; + Ok(keys) +} + +#[cfg(feature = "signed-coordinator-event")] +fn take_receiver_keys(keys: &mut BTreeMap, path: &str) -> DeliveryKeys { + let current = keys + .remove(&format!("{path}.hmacSha256KeyRef")) + .expect("the inventory resolved the configured current key"); + let previous = keys.remove(&format!("{path}.previousHmacSha256KeyRef")); + DeliveryKeys::new(current, previous).expect("the inventory validated distinct key bytes") +} + #[cfg(feature = "signed-coordinator-event")] fn activate_signed<'a>( program: &'a JobProgram, configured: &RuntimeDestinationBinding, core: &AdapterEndpointBindings, resolver: &SecretResolver, + mut keys: BTreeMap, ) -> Result, String> { use registry_adapter_connectors::coordinator_event::{ CoordinatorEventConnector, CoordinatorEventReceiver, @@ -408,17 +568,29 @@ fn activate_signed<'a>( }; let RuntimeDestinationBinding::SignedCoordinatorEvent { base_url, - signing_key_ref, + revised_receiver: configured_revised, attempt_timeout_milliseconds, tls_trust_profile, + .. } = configured else { return Err("the runtime destination kind does not match the job destination".to_string()); }; + check_revised_receiver( + binding, + revised_receiver.is_some(), + configured_revised.is_some(), + )?; + let path = format!("destinations.{binding}"); + let primary_keys = take_receiver_keys(&mut keys, &path); + let revised_keys = configured_revised + .as_ref() + .map(|_| take_receiver_keys(&mut keys, &format!("{path}.revisedReceiver"))); + drop(keys); let profile = if base_url.is_https() { DestinationProfile::ProductionHttps } else { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp }; let private_cidrs = core .allowed_private_cidrs @@ -442,21 +614,18 @@ fn activate_signed<'a>( .install_configured_tls(material) .map_err(|_| "the signed-event destination TLS material was refused".to_string())?; } - let key = resolver - .resolve(signing_key_ref.as_str()) - .map_err(|_| "the signed-event key could not be resolved".to_string())?; let connector = Arc::new( CoordinatorEventConnector::new( Arc::new(policy), source, - key.expose_secret().to_vec(), Duration::from_millis(attempt_timeout_milliseconds.get()), ) .map_err(|_| "the signed-event destination configuration was refused".to_string())?, ); let selected = |selected_trigger: &str, selected_type: &str, - selected_schema: &str| + selected_schema: &str, + keys: DeliveryKeys| -> Result< crate::signed_coordinator_event::SignedCoordinatorEventReceiver, String, @@ -466,6 +635,7 @@ fn activate_signed<'a>( selected_trigger, selected_type, selected_schema, + keys, ) .map_err(|_| "the signed-event receiver configuration was refused".to_string())?; let identity = crate::signed_coordinator_event::receiver_identity( @@ -486,14 +656,16 @@ fn activate_signed<'a>( ), ) }; - let primary = selected(trigger.as_str(), event_type, data_schema)?; + let primary = selected(trigger.as_str(), event_type, data_schema, primary_keys)?; let revised = revised_receiver .as_ref() - .map(|receiver| { + .zip(revised_keys) + .map(|(receiver, keys)| { selected( receiver.trigger.as_str(), &receiver.event_type, &receiver.data_schema, + keys, ) }) .transpose()?; @@ -697,7 +869,7 @@ mod tests { "coordinator-main": { "type": "signed-coordinator-event", "baseUrl": "https://coordinator.example/", - "signingKeyRef": "secret:env/COORDINATOR_EVENT_KEY", + "hmacSha256KeyRef": "secret:env/COORDINATOR_EVENT_KEY", "attemptTimeoutMilliseconds": 3000, "tlsTrustProfile": "institution-ca" } @@ -709,7 +881,7 @@ mod tests { "coordinator-main": { "type": "signed-coordinator-event", "baseUrl": "https://coordinator.example/", - "signingKeyRef": "secret:env/COORDINATOR_EVENT_KEY" + "hmacSha256KeyRef": "secret:env/COORDINATOR_EVENT_KEY" } }); assert!( @@ -722,7 +894,7 @@ mod tests { "coordinator-main": { "type": "signed-coordinator-event", "baseUrl": "https://coordinator.example/", - "signingKeyRef": "secret:env/COORDINATOR_EVENT_KEY", + "hmacSha256KeyRef": "secret:env/COORDINATOR_EVENT_KEY", "attemptTimeoutMilliseconds": 3000, "fallbackUrl": "https://other.example/" } @@ -734,6 +906,249 @@ mod tests { ); } + #[test] + fn a_removed_signing_key_member_names_its_replacement() { + let value = serde_json::json!({ + "type": "signed-coordinator-event", + "baseUrl": "https://coordinator.example/", + "signingKeyRef": "secret:file/old-key", + "attemptTimeoutMilliseconds": 1000 + }); + for id in ["coordinator-main", "INVALID"] { + let message = parse_runtime_bindings(&serde_json::json!({(id): value})) + .expect_err("the retired member is refused"); + assert_eq!( + message, + format!("replace `destinations.{id}.signingKeyRef` with `destinations.{id}.hmacSha256KeyRef`") + ); + } + } + + #[cfg(feature = "signed-coordinator-event")] + #[test] + fn key_resolution_reports_missing_and_empty_files() { + use registry_platform_config::{SecretError, SecretProvider}; + let directory = tempfile::tempdir().unwrap(); + let empty = directory.path().join("empty-key"); + std::fs::write(&empty, []).unwrap(); + std::fs::set_permissions(empty, std::fs::Permissions::from_mode(0o600)).unwrap(); + let resolver = SecretResolver::new([SecretProvider::File], directory.path()).unwrap(); + let path = "destinations.coordinator-main"; + for (name, error) in [ + ("missing-key", SecretError::Unavailable), + ("empty-key", SecretError::InvalidValue), + ] { + let reference = + serde_json::from_value(serde_json::json!(format!("secret:file/{name}"))).unwrap(); + assert_eq!( + resolve_delivery_key(&resolver, &format!("{path}.hmacSha256KeyRef"), &reference) + .err() + .unwrap(), + format!( + "could not resolve {path}.hmacSha256KeyRef: {error}. {}", + error.suggested_action() + ) + ); + } + } + + #[cfg(feature = "signed-coordinator-event")] + #[tokio::test] + async fn duplicate_keys_refuse_every_job_using_the_runtime() { + let adapter = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../products/adapter"); + let example = adapter.join("examples/kobotoolbox-job"); + let runtime_path = example.join("job-runtime.coordinator.example.yaml"); + let mut runtime = JobRuntimeConfig::load(&runtime_path).unwrap(); + let directory = tempfile::tempdir().unwrap(); + for (name, value) in [ + ("active", 1), + ("previous", 2), + ("revised", 3), + ("duplicate", 2), + ("second-revised", 4), + ("kobo-token", b'x'), + ] { + let path = directory.path().join(name); + std::fs::write(&path, [value; 32]).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let resolver = Arc::new( + SecretResolver::new( + [registry_platform_config::SecretProvider::File], + directory.path(), + ) + .unwrap(), + ); + runtime.core.endpoints = serde_json::from_value(serde_json::json!([{ + "endpoint": "kobo-api", + "baseUrl": "https://kobo.example.invalid/api/v2/assets/aFixtureUid0000000000000000000001/data", + "credential": {"type": "static-authorization", "tokenRef": "secret:file/kobo-token"}, + }])) + .unwrap(); + let mut program = registry_adapter_engine::job::compile_job_with_runtime( + &adapter.join("packs/kobotoolbox/pack.yaml"), + &example.join("job.coordinator.yaml"), + &runtime, + Arc::clone(&resolver), + &example.join("profile.yaml"), + &example.join("project.yaml"), + ) + .expect("compile the signed job example"); + let destination = |key, previous| { + serde_json::json!({ + "type": "signed-coordinator-event", + "baseUrl": "http://127.0.0.1:41001", + "hmacSha256KeyRef": format!("secret:file/{key}"), + "previousHmacSha256KeyRef": previous, + "revisedReceiver": {"hmacSha256KeyRef": "secret:file/revised"}, + "attemptTimeoutMilliseconds": 1000, + }) + }; + let mut second = destination("duplicate", None); + second["revisedReceiver"]["hmacSha256KeyRef"] = + serde_json::json!("secret:file/second-revised"); + runtime.destinations = Some(serde_json::json!({ + "coordinator-first": destination("active", Some("secret:file/previous")), + "coordinator-second": second, + })); + let expected = "destinations.coordinator-first.previousHmacSha256KeyRef and destinations.coordinator-second.hmacSha256KeyRef resolve to the same key bytes. Give destinations.coordinator-second.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."; + for id in ["coordinator-first", "coordinator-second"] { + let JobDestination::SignedCoordinatorEvent { binding, .. } = + &mut program.job.destination + else { + panic!("the example selects a signed destination"); + }; + *binding = LocalId::new(id).unwrap(); + assert_eq!( + activate_destination(&program, &runtime, &resolver) + .await + .err() + .as_deref(), + Some(expected) + ); + } + } + + #[cfg(feature = "signed-coordinator-event")] + #[test] + fn revised_receiver_configuration_matches_the_authored_job() { + let binding = LocalId::new("coordinator-main").unwrap(); + let missing = check_revised_receiver(&binding, true, false).unwrap_err(); + assert!(missing + .contains("add `destinations.coordinator-main.revisedReceiver.hmacSha256KeyRef`")); + let unexpected = check_revised_receiver(&binding, false, true).unwrap_err(); + assert!(unexpected.contains("remove `destinations.coordinator-main.revisedReceiver`")); + } + + #[cfg(feature = "signed-coordinator-event")] + #[test] + fn trigger_keys_use_exact_bytes_and_name_invalid_or_reused_key_paths() { + let directory = tempfile::tempdir().unwrap(); + let resolver = SecretResolver::new( + [registry_platform_config::SecretProvider::File], + directory.path(), + ) + .unwrap(); + let path = "destinations.coordinator-main"; + let reference = |name: &str, bytes: &[u8]| { + let file = directory.path().join(name); + std::fs::write(&file, bytes).unwrap(); + std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600)).unwrap(); + serde_json::from_value::(serde_json::json!(format!( + "secret:file/{name}" + ))) + .unwrap() + }; + let binary = reference("binary", &[0; 32]); + assert!( + resolve_delivery_key(&resolver, &format!("{path}.hmacSha256KeyRef"), &binary).is_ok() + ); + let bindings = parse_runtime_bindings(&serde_json::json!({ + "coordinator-main": { + "type": "signed-coordinator-event", + "baseUrl": "http://127.0.0.1:41001", + "hmacSha256KeyRef": "secret:file/binary", + "revisedReceiver": {"hmacSha256KeyRef": "secret:file/same-bytes"}, + "attemptTimeoutMilliseconds": 1000 + } + })) + .unwrap(); + reference("same-bytes", &[0; 32]); + let message = resolve_destination_keys(&resolver, &bindings) + .err() + .unwrap(); + assert!(message.contains("destinations.coordinator-main.hmacSha256KeyRef")); + assert!(message.contains("destinations.coordinator-main.revisedReceiver.hmacSha256KeyRef")); + + let mut with_newline = vec![b'a'; 64]; + with_newline.push(b'\n'); + let revised_path = "destinations.coordinator-main.revisedReceiver"; + let too_long = reference("newline", &with_newline); + let message = resolve_delivery_key( + &resolver, + &format!("{revised_path}.hmacSha256KeyRef"), + &too_long, + ) + .err() + .unwrap(); + assert!(message.contains("destinations.coordinator-main.revisedReceiver.hmacSha256KeyRef")); + assert!(message.contains("65 bytes") && message.contains("newline")); + let secret_text = reference("secret-text", b"whsec_synthetic-canary-not-key-bytes"); + let message = resolve_delivery_key( + &resolver, + &format!("{path}.previousHmacSha256KeyRef"), + &secret_text, + ) + .err() + .unwrap(); + assert!(message.contains("destinations.coordinator-main.previousHmacSha256KeyRef")); + assert!(message.contains("whsec_") && message.contains("bytes")); + assert!(!message.contains("synthetic-canary")); + } + + #[cfg(feature = "signed-coordinator-event")] + #[test] + fn a_previous_key_equal_to_its_current_key_explains_rotation() { + let directory = tempfile::tempdir().unwrap(); + let resolver = SecretResolver::new( + [registry_platform_config::SecretProvider::File], + directory.path(), + ) + .unwrap(); + for (name, value) in [("primary", 1), ("revised", 2)] { + let file = directory.path().join(name); + std::fs::write(&file, [value; 32]).unwrap(); + std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + for receiver in ["primary", "revised"] { + let mut destination = serde_json::json!({ + "type": "signed-coordinator-event", + "baseUrl": "http://127.0.0.1:41001", + "hmacSha256KeyRef": "secret:file/primary", + "revisedReceiver": {"hmacSha256KeyRef": "secret:file/revised"}, + "attemptTimeoutMilliseconds": 1000 + }); + let mut path = "destinations.coordinator-main".to_owned(); + let binding = if receiver == "primary" { + &mut destination + } else { + path.push_str(".revisedReceiver"); + &mut destination["revisedReceiver"] + }; + binding["previousHmacSha256KeyRef"] = + serde_json::json!(format!("secret:file/{receiver}")); + let bindings = + parse_runtime_bindings(&serde_json::json!({"coordinator-main": destination})) + .unwrap(); + let previous = format!("{path}.previousHmacSha256KeyRef"); + let current = format!("{path}.hmacSha256KeyRef"); + assert_eq!( + resolve_destination_keys(&resolver, &bindings).unwrap_err(), + format!("{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}.") + ); + } + } + /// A direct BReg binding states its client assertion audience, the /// authorization server's issuer identifier RFC 10070 section 4 makes /// its sole value, and the refusal of one that does not names the member. @@ -798,7 +1213,7 @@ mod tests { "coordinator-main": { "type": "signed-coordinator-event", "baseUrl": base_url, - "signingKeyRef": format!("secret:file/{key}"), + "hmacSha256KeyRef": format!("secret:file/{key}"), "attemptTimeoutMilliseconds": 1000 } } @@ -832,16 +1247,16 @@ mod tests { .expect("the snapshot destination binding"); let RuntimeDestinationBinding::SignedCoordinatorEvent { base_url, - signing_key_ref, + hmac_sha256_key_ref, .. } = configured else { panic!("the snapshot selects signed coordinator events") }; assert_eq!(base_url.as_str(), "http://127.0.0.1:41001"); - assert_eq!(signing_key_ref.as_str(), "secret:file/old-key"); + assert_eq!(hmac_sha256_key_ref.as_str(), "secret:file/old-key"); let secret = resolver - .resolve(signing_key_ref.as_str()) + .resolve_binary_reference(hmac_sha256_key_ref) .expect("snapshot A resolves its own key"); assert_eq!(secret.expose_secret(), b"old-snapshot-secret"); } diff --git a/crates/registry-adapter-job/src/signed_coordinator_event.rs b/crates/registry-adapter-job/src/signed_coordinator_event.rs index 08bf9edaa1..c139c6c871 100644 --- a/crates/registry-adapter-job/src/signed_coordinator_event.rs +++ b/crates/registry-adapter-job/src/signed_coordinator_event.rs @@ -95,7 +95,7 @@ pub struct SignedCoordinatorEventDestination { impl SignedCoordinatorEventDestination { /// Bind the primary trigger and an optional revised trigger under one - /// shared destination authority, source, and signing key. + /// shared destination authority and source, with keys on each trigger. #[must_use] pub fn new( connector: Arc, @@ -341,7 +341,7 @@ mod tests { registry_platform_httputil::destination::EventDestinationPolicy::new( "coordinator-test", "http://127.0.0.1:9/", - registry_platform_httputil::destination::DestinationProfile::LoopbackDevelopmentHttp, + registry_platform_httputil::destination::DestinationProfile::LoopbackHttp, &[], ) .expect("the inert destination policy freezes"), @@ -350,7 +350,6 @@ mod tests { CoordinatorEventConnector::new( policy, "urn:registry-adapter:job:case-daily", - vec![0x55; 32], std::time::Duration::from_secs(1), ) .expect("the inert connector freezes"), @@ -361,6 +360,12 @@ mod tests { "submitted", "org.example.case-submitted.v1", "urn:example:schema:case-submitted:v1", + registry_platform_crypto::delivery_signature::DeliveryKeys::new( + registry_platform_crypto::delivery_signature::DeliveryKey::new(&[0x55; 32]) + .unwrap(), + None, + ) + .unwrap(), ) .expect("the primary receiver freezes"), [0x11; 32], diff --git a/crates/registry-adapter-job/tests/job_file_host.rs b/crates/registry-adapter-job/tests/job_file_host.rs index f0040f11ee..a90a5469a6 100644 --- a/crates/registry-adapter-job/tests/job_file_host.rs +++ b/crates/registry-adapter-job/tests/job_file_host.rs @@ -188,7 +188,7 @@ fn runtime_json(source: &Path, component: &str) -> String { "destinations": {"coordinator-test": { "type": "signed-coordinator-event", "baseUrl": "http://127.0.0.1:9/events", - "signingKeyRef": "secret:env/JOB_TEST_SIGNING_KEY", + "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} }); @@ -249,6 +249,44 @@ fn the_actual_check_accepts_a_file_source_when_the_host_feature_is_present() { assert_eq!(report["source"]["route"], "kobo-submissions"); } +/// The check's findings: standard output and error together. +fn check_findings(fixture: &FileFixture) -> String { + let output = run_check(fixture); + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +#[cfg(feature = "signed-coordinator-event")] +#[test] +fn a_named_plain_http_endpoint_needs_a_declared_private_range() { + let fixture = FileFixture::new("csv", "file", 1_048_576); + let declared = std::fs::read_to_string(&fixture.runtime).expect("the runtime config"); + let named = declared.replace( + "https://cases.example.invalid", + "http://cases.internal.example", + ); + assert_ne!(named, declared, "the fixture names an https endpoint"); + let empty = named.replace( + "\"allowedPrivateCidrs\": [\n \"10.0.0.0/8\"\n ]", + "\"allowedPrivateCidrs\": []", + ); + assert_ne!(empty, named, "the fixture declares one private range"); + + std::fs::write(&fixture.runtime, &empty).expect("the runtime config"); + assert!( + check_findings(&fixture).contains("adapter.runtime.insecure-origin"), + "an empty list admits no private address" + ); + std::fs::write(&fixture.runtime, &named).expect("the runtime config"); + assert!( + !check_findings(&fixture).contains("adapter.runtime.insecure-origin"), + "a declared range admits the named host" + ); +} + #[tokio::test] async fn csv_and_jsonl_values_cross_the_existing_destination_seam() { let cases = [ diff --git a/crates/registry-adapter-job/tests/postgres_job.rs b/crates/registry-adapter-job/tests/postgres_job.rs index 358d922aa8..90c6f6e463 100644 --- a/crates/registry-adapter-job/tests/postgres_job.rs +++ b/crates/registry-adapter-job/tests/postgres_job.rs @@ -3430,7 +3430,7 @@ fn add_unresolved_non_store_secrets(fixture: &JobFixture) { "coordinator-test": { "type": "signed-coordinator-event", "baseUrl": "https://coordinator.example.invalid", - "signingKeyRef": "secret:env/JOB_UNRESOLVED_DESTINATION_KEY", + "hmacSha256KeyRef": "secret:env/JOB_UNRESOLVED_DESTINATION_KEY", "attemptTimeoutMilliseconds": 3000 } }); diff --git a/crates/registry-adapter-job/tests/postgres_source_host.rs b/crates/registry-adapter-job/tests/postgres_source_host.rs index d762ff9953..82fe283572 100644 --- a/crates/registry-adapter-job/tests/postgres_source_host.rs +++ b/crates/registry-adapter-job/tests/postgres_source_host.rs @@ -817,7 +817,7 @@ fn runtime_yaml(binding: &DatabaseBinding, query_kind: SourceQuery) -> String { "coordinator-test": { "type": "signed-coordinator-event", "baseUrl": "http://127.0.0.1:9/events", - "signingKeyRef": "secret:env/JOB_TEST_SIGNING_KEY", + "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 } } diff --git a/crates/registry-adapter-job/tests/sftp_cli_host.rs b/crates/registry-adapter-job/tests/sftp_cli_host.rs index 05f56d06a2..4910f9826c 100644 --- a/crates/registry-adapter-job/tests/sftp_cli_host.rs +++ b/crates/registry-adapter-job/tests/sftp_cli_host.rs @@ -177,7 +177,7 @@ fn runtime_json(server: &SftpSourceServer) -> Vec { "destinations": {"coordinator-test": { "type": "signed-coordinator-event", "baseUrl": "http://127.0.0.1:9/events", - "signingKeyRef": "secret:env/JOB_TEST_SIGNING_KEY", + "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} })) diff --git a/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs b/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs index d3bca6242b..5190099d45 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_native.rs @@ -46,6 +46,7 @@ use registry_adapter_job::signed_coordinator_event::{ SignedCoordinatorEventDestination, SignedCoordinatorEventReceiver, }; use registry_adapter_job::store::{self, ItemStatus}; +use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; use registry_platform_httputil::destination::{DestinationProfile, EventDestinationPolicy}; use registry_platform_testing::{fixtures, TestActorKind, TestAuthorizationServer, TestClient}; @@ -53,6 +54,12 @@ use serde_json::{json, Value}; use tokio_postgres::{Config as PgConfig, NoTls}; const KEY: &[u8] = &[0x5a; 32]; +const REVISED_KEY: &[u8] = &[0x6a; 32]; + +fn delivery_keys(key: &[u8]) -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap() +} + const WORKFLOW: &str = "register-household"; const PRIMARY_TRIGGER: &str = "submission-received"; const REVISED_TRIGGER: &str = "submission-revised"; @@ -364,11 +371,9 @@ impl NativeCoordinator { ("admission-key", &[0x48; 32]), ("audit-key", &[0x49; 32]), ("event-key", KEY), + ("revised-event-key", REVISED_KEY), ("client-key", fixtures::ED25519_PRIVATE_JWK.as_bytes()), - ( - "review-completion-token", - casework.completion_token().as_bytes(), - ), + ("review-completion-key", casework.completion_key()), ] { private_file(&root.path().join(name), contents); } @@ -405,12 +410,15 @@ impl NativeCoordinator { }, "completion": { "recipientBinding": casework_native_service::RECIPIENT_BINDING, - "bearerTokenRef": "secret:file/review-completion-token" + "hmacSha256KeyRef": "secret:file/review-completion-key" }, "resultCheckSeconds": 900 } }, - "eventSources": {"adapter": {"source": SOURCE, "signingKeyRef": "secret:file/event-key"}}, + "eventSources": {"adapter": {"source": SOURCE, "triggers": {(WORKFLOW): { + (PRIMARY_TRIGGER): {"hmacSha256KeyRef": "secret:file/event-key"}, + (REVISED_TRIGGER): {"hmacSha256KeyRef": "secret:file/revised-event-key"} + }}}}, "deployment": { "databaseId": format!("adapter-native-{suffix}"), "runtimeRole": role, "packages": [{"root": package, "expectedDigest": package_digest}], @@ -746,23 +754,24 @@ async fn assert_revised_run_used_unresolved_review( fn maintained_destination(base_url: &str, policy_name: &str) -> SignedCoordinatorEventDestination { let policy = Arc::new( - EventDestinationPolicy::new( - policy_name, - base_url, - DestinationProfile::LoopbackDevelopmentHttp, - &[], - ) - .expect("the maintained event policy freezes"), + EventDestinationPolicy::new(policy_name, base_url, DestinationProfile::LoopbackHttp, &[]) + .expect("the maintained event policy freezes"), ); let connector = Arc::new( - CoordinatorEventConnector::new(policy, SOURCE, KEY.to_vec(), Duration::from_secs(3)) + CoordinatorEventConnector::new(policy, SOURCE, Duration::from_secs(3)) .expect("the maintained event connector freezes"), ); SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new(WORKFLOW, PRIMARY_TRIGGER, EVENT_TYPE, DATA_SCHEMA) - .expect("the maintained primary receiver freezes"), + CoordinatorEventReceiver::new( + WORKFLOW, + PRIMARY_TRIGGER, + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the maintained primary receiver freezes"), [0x11; 32], ), Some(SignedCoordinatorEventReceiver::new( @@ -771,6 +780,7 @@ fn maintained_destination(base_url: &str, policy_name: &str) -> SignedCoordinato REVISED_TRIGGER, REVISED_EVENT_TYPE, REVISED_DATA_SCHEMA, + delivery_keys(REVISED_KEY), ) .expect("the maintained revised receiver freezes"), [0x12; 32], @@ -885,13 +895,13 @@ async fn a_lost_native_event_answer_recovers_the_same_coordinator_run() { EventDestinationPolicy::new( "adapter-native-coordinator", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the native event policy freezes"), ); let connector = Arc::new( - CoordinatorEventConnector::new(policy, SOURCE, KEY.to_vec(), Duration::from_secs(3)) + CoordinatorEventConnector::new(policy, SOURCE, Duration::from_secs(3)) .expect("the native event connector freezes"), ); let fixture = job_fixture::JobFixture::start( @@ -908,9 +918,14 @@ async fn a_lost_native_event_answer_recovers_the_same_coordinator_run() { configure_maintained_job(&fixture.job); let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime) .expect("the native job compiles"); - let receiver = - CoordinatorEventReceiver::new(WORKFLOW, PRIMARY_TRIGGER, EVENT_TYPE, DATA_SCHEMA) - .expect("the native primary receiver freezes"); + let receiver = CoordinatorEventReceiver::new( + WORKFLOW, + PRIMARY_TRIGGER, + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the native primary receiver freezes"); let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new(receiver, [0x11; 32]), @@ -920,6 +935,7 @@ async fn a_lost_native_event_answer_recovers_the_same_coordinator_run() { REVISED_TRIGGER, REVISED_EVENT_TYPE, REVISED_DATA_SCHEMA, + delivery_keys(REVISED_KEY), ) .expect("the revised receiver freezes"), [0x12; 32], @@ -1193,13 +1209,13 @@ async fn postgres_source_reaches_native_coordinator_and_reviews_a_revised_row() EventDestinationPolicy::new( "adapter-native-coordinator-postgres", &coordinator.origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the native PostgreSQL event policy freezes"), ); let connector = Arc::new( - CoordinatorEventConnector::new(policy, SOURCE, KEY.to_vec(), Duration::from_secs(3)) + CoordinatorEventConnector::new(policy, SOURCE, Duration::from_secs(3)) .expect("the native PostgreSQL event connector freezes"), ); let fixture = job_fixture::JobFixture::start( @@ -1219,9 +1235,14 @@ async fn postgres_source_reaches_native_coordinator_and_reviews_a_revised_row() compile_job(&fixture.pack, &fixture.job, &fixture.runtime).expect("the SQL job compiles"); activate_postgres_sources(&mut program, &source.resolver()) .expect("the production PostgreSQL source host activates"); - let receiver = - CoordinatorEventReceiver::new(WORKFLOW, PRIMARY_TRIGGER, EVENT_TYPE, DATA_SCHEMA) - .expect("the native primary receiver freezes"); + let receiver = CoordinatorEventReceiver::new( + WORKFLOW, + PRIMARY_TRIGGER, + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the native primary receiver freezes"); let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new(receiver, [0x11; 32]), @@ -1231,6 +1252,7 @@ async fn postgres_source_reaches_native_coordinator_and_reviews_a_revised_row() REVISED_TRIGGER, REVISED_EVENT_TYPE, REVISED_DATA_SCHEMA, + delivery_keys(REVISED_KEY), ) .expect("the native revised receiver freezes"), [0x12; 32], diff --git a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs index 503c362f01..3f9adbb541 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs @@ -35,18 +35,48 @@ use registry_adapter_job::signed_coordinator_event::{ }; use registry_adapter_job::store::{self, ItemStatus}; use registry_platform_config::{SecretProvider, SecretResolver}; -use registry_platform_hooks::receiver::{verify_delivery, DeliveryFreshness, SignedDelivery}; -use registry_platform_hooks::{EnvelopeLimits, HookEnvelope}; +use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; +use registry_platform_hooks::receiver::{verify_hook_delivery, DeliveryFreshness, HookDelivery}; +use registry_platform_hooks::HookEnvelope; use registry_platform_httputil::destination::{DestinationProfile, EventDestinationPolicy}; use serde_json::json; use tokio_postgres::{Config as PgConfig, NoTls}; const KEY: &[u8] = &[0x5a; 32]; +const REVISED_KEY: &[u8] = &[0x6a; 32]; + +fn delivery_keys(key: &[u8]) -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap() +} + const TARGET: &str = "/v1/events/case-ingestion/submitted"; const SOURCE: &str = "urn:registrystack:adapter:synthetic"; const EVENT_TYPE: &str = "case.submitted"; const DATA_SCHEMA: &str = "urn:example:case-submitted:v1"; +fn trigger_key(trigger: &str) -> &'static [u8] { + if trigger == "submitted" { + KEY + } else { + REVISED_KEY + } +} + +fn verify_event(headers: &HeaderMap, body: &[u8], key: &[u8]) -> HookEnvelope { + verify_hook_delivery( + HookDelivery { + headers: headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())), + body, + keys: &delivery_keys(key), + }, + DeliveryFreshness::default_at(SystemTime::now()), + ) + .expect("the job sent a valid platform signature") + .envelope +} + #[derive(Clone, Default)] struct Receiver { runs: Arc>>, @@ -58,28 +88,7 @@ async fn admit( headers: HeaderMap, body: Bytes, ) -> impl IntoResponse { - let pairs = headers - .iter() - .map(|(name, value)| (name.as_str(), value.as_bytes())) - .collect::>(); - let verified = verify_delivery( - SignedDelivery { - method: "POST", - request_target: TARGET, - headers: pairs, - body: &body, - key: KEY, - }, - DeliveryFreshness::CallerEnforced, - ) - .expect("the job sent a valid platform signature"); - let envelope = HookEnvelope::from_canonical_bytes(&body, &EnvelopeLimits::default()) - .expect("the job sent a canonical hook envelope"); - assert_eq!(verified.id, envelope.id); - assert_eq!(verified.source, envelope.source); - assert_eq!(verified.event_type, envelope.event_type); - assert_eq!(verified.data_schema, envelope.dataschema); - assert_eq!(verified.idempotency_key, envelope.id); + let envelope = verify_event(&headers, &body, KEY); let mut runs = receiver.runs.lock().expect("the receiver run lock"); let first = !runs.contains_key(&envelope.id); @@ -180,7 +189,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { "coordinator-test": { "type": "signed-coordinator-event", "baseUrl": format!("http://127.0.0.1:{}/", address.port()), - "signingKeyRef": format!("secret:env/{KEY_ENV}"), + "hmacSha256KeyRef": format!("secret:env/{KEY_ENV}"), "attemptTimeoutMilliseconds": 2000 } }); @@ -250,13 +259,13 @@ async fn a_lost_signed_event_answer_recovers_one_run_through_the_job_store() { EventDestinationPolicy::new( "adapter-coordinator-events", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the loopback event policy freezes"), ); let connector = Arc::new( - CoordinatorEventConnector::new(policy, SOURCE, KEY.to_vec(), Duration::from_secs(2)) + CoordinatorEventConnector::new(policy, SOURCE, Duration::from_secs(2)) .expect("the signed event connector freezes"), ); let fixture = job_fixture::JobFixture::start( @@ -273,9 +282,14 @@ async fn a_lost_signed_event_answer_recovers_one_run_through_the_job_store() { .await; let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime).expect("the job compiles"); - let event_receiver = - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the primary receiver freezes"); + let event_receiver = CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the primary receiver freezes"); let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new(event_receiver, [0x11; 32]), @@ -343,13 +357,12 @@ async fn pending_job_version_drift_stops_before_wire_and_restore_recovers() { EventDestinationPolicy::new( "adapter-coordinator-body-drift", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), ), SOURCE, - KEY.to_vec(), Duration::from_secs(2), ) .expect("the signed event connector freezes"), @@ -371,8 +384,14 @@ async fn pending_job_version_drift_stops_before_wire_and_restore_recovers() { let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the primary receiver freezes"), + CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the primary receiver freezes"), [0x11; 32], ), None, @@ -475,13 +494,12 @@ async fn a_submicrosecond_event_time_keeps_identical_retry_bytes_after_store_rou EventDestinationPolicy::new( "adapter-coordinator-submicrosecond", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), ), SOURCE, - KEY.to_vec(), Duration::from_secs(2), ) .expect("the signed event connector freezes"), @@ -489,8 +507,14 @@ async fn a_submicrosecond_event_time_keeps_identical_retry_bytes_after_store_rou let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the primary receiver freezes"), + CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the primary receiver freezes"), [0x11; 32], ), None, @@ -678,20 +702,24 @@ async fn coordinator_item_and_deployment_failures_never_fall_back() { EventDestinationPolicy::new( "adapter-coordinator-problems", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the problem event policy freezes"), ), SOURCE, - KEY.to_vec(), Duration::from_secs(2), ) .expect("the problem connector freezes"), ); - let event_receiver = - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the primary receiver freezes"); + let event_receiver = CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the primary receiver freezes"); let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new(event_receiver, [0x11; 32]), @@ -772,21 +800,8 @@ async fn scripted( headers: HeaderMap, body: Bytes, ) -> axum::response::Response { - let pairs = headers - .iter() - .map(|(name, value)| (name.as_str(), value.as_bytes())) - .collect::>(); - verify_delivery( - SignedDelivery { - method: "POST", - request_target: uri.path(), - headers: pairs, - body: &body, - key: KEY, - }, - DeliveryFreshness::CallerEnforced, - ) - .expect("the job sent a valid platform signature"); + let trigger = uri.path().rsplit('/').next().unwrap(); + verify_event(&headers, &body, trigger_key(trigger)); receiver .targets .lock() @@ -847,29 +862,40 @@ async fn scripted_destination( EventDestinationPolicy::new( "adapter-coordinator-refused-retry", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), ), SOURCE, - KEY.to_vec(), Duration::from_secs(2), ) .expect("the signed event connector freezes"), ); let revised = revised_trigger.then(|| { SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new("case-ingestion", "revised", "case.revised", DATA_SCHEMA) - .expect("the revised receiver freezes"), + CoordinatorEventReceiver::new( + "case-ingestion", + "revised", + "case.revised", + DATA_SCHEMA, + delivery_keys(REVISED_KEY), + ) + .expect("the revised receiver freezes"), [0x22; 32], ) }); let destination = SignedCoordinatorEventDestination::new( connector, SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new("case-ingestion", "submitted", EVENT_TYPE, DATA_SCHEMA) - .expect("the primary receiver freezes"), + CoordinatorEventReceiver::new( + "case-ingestion", + "submitted", + EVENT_TYPE, + DATA_SCHEMA, + delivery_keys(KEY), + ) + .expect("the primary receiver freezes"), [0x11; 32], ), revised, @@ -1365,29 +1391,13 @@ async fn admitting( headers: HeaderMap, body: Bytes, ) -> axum::response::Response { - let pairs = headers - .iter() - .map(|(name, value)| (name.as_str(), value.as_bytes())) - .collect::>(); - verify_delivery( - SignedDelivery { - method: "POST", - request_target: uri.path(), - headers: pairs, - body: &body, - key: KEY, - }, - DeliveryFreshness::CallerEnforced, - ) - .expect("the job sent a valid platform signature"); - let envelope = HookEnvelope::from_canonical_bytes(&body, &EnvelopeLimits::default()) - .expect("the job sent a canonical hook envelope"); let trigger = uri .path() .rsplit('/') .next() .expect("the path names a trigger") .to_string(); + let envelope = verify_event(&headers, &body, trigger_key(&trigger)); receiver .requests .lock() @@ -1467,8 +1477,14 @@ async fn start_admitting_receiver( fn revision_destination(base_url: &str, revised: &str) -> SignedCoordinatorEventDestination { let receiver = |trigger: &str, event_type: &str| { SignedCoordinatorEventReceiver::new( - CoordinatorEventReceiver::new("case-ingestion", trigger, event_type, DATA_SCHEMA) - .expect("the receiver freezes"), + CoordinatorEventReceiver::new( + "case-ingestion", + trigger, + event_type, + DATA_SCHEMA, + delivery_keys(trigger_key(trigger)), + ) + .expect("the receiver freezes"), receiver_identity(&CoordinatorReceiverDigestContext { binding: REVISION_BINDING, base_url, @@ -1487,13 +1503,12 @@ fn revision_destination(base_url: &str, revised: &str) -> SignedCoordinatorEvent EventDestinationPolicy::new( REVISION_BINDING, base_url, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("the event policy freezes"), ), SOURCE, - KEY.to_vec(), Duration::from_secs(2), ) .expect("the signed event connector freezes"), diff --git a/crates/registry-adapter-job/tests/support/casework_native_service.rs b/crates/registry-adapter-job/tests/support/casework_native_service.rs index dbf2dcc99d..c5d1b9f5f2 100644 --- a/crates/registry-adapter-job/tests/support/casework_native_service.rs +++ b/crates/registry-adapter-job/tests/support/casework_native_service.rs @@ -147,7 +147,7 @@ impl Drop for OwnedSchema { pub struct Casework { pub origin: String, pub binding: Value, - completion_token: String, + completion_key: [u8; 32], staff_token: String, _process: Process, _owned: OwnedSchema, @@ -255,11 +255,9 @@ impl Casework { .bytes() .await .expect("read the synthetic issuer JWKS body"); - let completion_token = format!( - "{}{}", - uuid::Uuid::new_v4().simple(), - uuid::Uuid::new_v4().simple() - ); + let mut completion_key = [0_u8; 32]; + completion_key[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes()); + completion_key[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes()); for (name, bytes) in [ ("database", scoped_database.as_bytes()), ("jwks", jwks.as_ref()), @@ -267,7 +265,7 @@ impl Casework { "audit-key", b"synthetic-casework-audit-key-0123456789".as_slice(), ), - ("completion-token", completion_token.as_bytes()), + ("completion-key", completion_key.as_slice()), ] { private_file(&root.path().join(name), bytes); } @@ -298,7 +296,7 @@ impl Casework { "contextProviders": {}, "reviewCompletionDestinations": {"coordinator": { "url": format!("{coordinator_origin}/v1/review-completions"), - "bearerTokenRef": "secret:file/completion-token", + "hmacSha256KeyRef": "secret:file/completion-key", "attemptTimeoutMilliseconds": 5000, "maximumAttempts": 10, "retryDelaySeconds": 1 @@ -396,7 +394,7 @@ impl Casework { Self { origin, binding, - completion_token, + completion_key, staff_token, _process: process, _owned: OwnedSchema { database, schema }, @@ -404,8 +402,8 @@ impl Casework { } } - pub fn completion_token(&self) -> &str { - &self.completion_token + pub fn completion_key(&self) -> &[u8] { + &self.completion_key } pub async fn approve(&self, requester_reference: &str) -> String { diff --git a/crates/registry-adapter-job/tests/support/kobo_native_source.rs b/crates/registry-adapter-job/tests/support/kobo_native_source.rs index c5cc8488d3..5b28211f6a 100644 --- a/crates/registry-adapter-job/tests/support/kobo_native_source.rs +++ b/crates/registry-adapter-job/tests/support/kobo_native_source.rs @@ -166,6 +166,7 @@ impl MaintainedKoboSource { .as_bytes(), ); private_file(&root.path().join("event-key"), &[0x5a; 32]); + private_file(&root.path().join("revised-event-key"), &[0x6a; 32]); let runtime = root.path().join("runtime.json"); let base_url = format!("http://{address}{}", DATA_PATH.trim_end_matches('/')); private_file( @@ -186,7 +187,8 @@ impl MaintainedKoboSource { "destinations": {"household-workflow": { "type": "signed-coordinator-event", "baseUrl": "http://127.0.0.1:9/", - "signingKeyRef": "secret:file/event-key", + "hmacSha256KeyRef": "secret:file/event-key", + "revisedReceiver": {"hmacSha256KeyRef": "secret:file/revised-event-key"}, "attemptTimeoutMilliseconds": 1000 }}, "store": { diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index 06ed52e255..798c1b2166 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -81,7 +81,7 @@ registry-platform-yaml.workspace = true axum.workspace = true clap.workspace = true jsonwebtoken.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } rustls.workspace = true rhai.workspace = true serde.workspace = true @@ -101,6 +101,6 @@ proptest.workspace = true # dependency. rcgen.workspace = true tokio-rustls.workspace = true -registry-platform-testing.workspace = true +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } tempfile.workspace = true serde_norway.workspace = true diff --git a/crates/registry-adapter/src/facade.rs b/crates/registry-adapter/src/facade.rs index 6126c81b99..99b55ea458 100644 --- a/crates/registry-adapter/src/facade.rs +++ b/crates/registry-adapter/src/facade.rs @@ -57,6 +57,8 @@ use crate::engine::route::{ run_async_status_poll, run_served_route_until, AsyncStatusPollKind, RouteContext, RouteFailure, EXCHANGE_DEADLINE, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; + use crate::govstack::consultation::{CAPABILITIES_PATH, MOUNT_PATH}; use crate::govstack::correlation::RequestCorrelation; use crate::idempotent::{ @@ -66,6 +68,7 @@ use crate::idempotent::{ }; use crate::journal::{self, JournalEvent}; use crate::serve::{Authenticator, Caller, CallerRefusal}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote}; const REQUEST_ID_HEADER: &str = "x-registry-request-id"; const WRITE_REQUEST_DIGEST_DOMAIN: &[u8] = b"registry-adapter:write-request:v2\0"; @@ -335,8 +338,23 @@ pub fn router(state: Arc) -> Router { } }), ); + let ready = Arc::clone(&state); + router = router + .route( + HEALTH_PATH, + get(|| async { probe_response(StatusCode::OK, HEALTH_BODY) }).fallback(probe_refusal), + ) + .route( + READY_PATH, + get(move || { + let shared = Arc::clone(&ready); + async move { readiness(shared).await } + }) + .fallback(probe_refusal), + ); let unmatched = Arc::clone(&state); let metrics = Arc::clone(&state.metrics); + let refusals = state.metrics.refusals(); router .fallback(move |correlation: Option>| { let shared = Arc::clone(&unmatched); @@ -353,6 +371,10 @@ pub fn router(state: Arc) -> Router { ) } }) + .layer(middleware::from_fn_with_state( + refusals, + crate::metrics::record_refusals, + )) .layer(middleware::from_fn_with_state( metrics, crate::metrics::count_requests, @@ -503,6 +525,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotAcceptable, StatusCode::NOT_ACCEPTABLE, + None, ) .await; } @@ -529,6 +552,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + None, ) .await; }; @@ -592,6 +616,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + Some(FailedCheck::Visibility), ) .await; } @@ -616,13 +641,13 @@ async fn answer_async_status( &physical_request_id, ); }; - if !admits_stored( + if let Err(check) = admitted( &state.loaded.project, &caller, metadata.profile_operation(), metadata.record_type(), ) { - return refuse_call( + let response = refuse_call( state, operation, &caller, @@ -630,8 +655,16 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeForbidden, StatusCode::FORBIDDEN, + Some(check), ) .await; + return with_declared_scope( + response, + check, + &state.loaded.project, + metadata.profile_operation(), + metadata.record_type(), + ); } let event = |kind: &'static str, detail: Option, at: SystemTime| { ( @@ -774,6 +807,7 @@ async fn answer_async_status( &physical_request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + Some(FailedCheck::Visibility), ) .await; } @@ -946,6 +980,47 @@ async fn answer_async_status( } } +/// Body of a readiness probe that finds the journal unusable. It is a +/// constant: it names no project, source, client or database error. +const NOT_READY_BODY: &str = r#"{"status":"not-ready"}"#; + +/// A probe answer: a constant JSON body, no request id, no journal event. +fn probe_response(status: StatusCode, body: &'static str) -> Response { + let mut response = (status, body).into_response(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + no_store(response) +} + +/// A probe path called with a method other than GET. The answer is empty so +/// it does not vary with the project's problem document. +async fn probe_refusal() -> Response { + let mut response = no_store(StatusCode::METHOD_NOT_ALLOWED.into_response()); + response + .headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("GET")); + response +} + +/// Unauthenticated readiness: whether the journal migration set is exactly +/// the set this binary supports and the runtime role holds its privileges. +/// It touches no source, appends no journal event, and answers a constant +/// body whatever the project or the cause of a failure. +async fn readiness(state: Arc) -> Response { + let journal_ready = match state.journal.get().await { + Ok(client) => journal::ready(&client).await.unwrap_or(false), + Err(_) => false, + }; + if journal_ready { + probe_response(StatusCode::OK, READY_BODY) + } else { + tracing::error!("the readiness probe found the journal unusable"); + probe_response(StatusCode::SERVICE_UNAVAILABLE, NOT_READY_BODY) + } +} + /// Return the immutable startup contract only to an authenticated machine /// caller and only while the live journal migration set is exactly the set /// this binary supports. This readiness check deliberately does not touch an @@ -1153,6 +1228,7 @@ async fn answer( &request_id, ErrorClass::FacadeNotAcceptable, StatusCode::NOT_ACCEPTABLE, + None, ) .await; } @@ -1165,11 +1241,17 @@ async fn answer( &request_id, ErrorClass::FacadeNotFound, StatusCode::NOT_FOUND, + None, ) .await; } - if !admits(&state.loaded.project, &caller, operation) { - return refuse_call( + if let Err(check) = admitted( + &state.loaded.project, + &caller, + operation.operation.as_str(), + operation.record_type.as_str(), + ) { + let response = refuse_call( state, operation, &caller, @@ -1177,8 +1259,16 @@ async fn answer( &request_id, ErrorClass::FacadeForbidden, StatusCode::FORBIDDEN, + Some(check), ) .await; + return with_declared_scope( + response, + check, + &state.loaded.project, + operation.operation.as_str(), + operation.record_type.as_str(), + ); } if !effective_contract_matches(headers, &state.effective_contract.digest) { return refuse_contract_pin(state, operation, &caller, &request_id).await; @@ -1254,6 +1344,7 @@ async fn answer( &request_id, ErrorClass::FacadeUnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE, + None, ) .await; } @@ -1268,6 +1359,7 @@ async fn answer( &request_id, ErrorClass::FacadePayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE, + None, ) .await; } @@ -1438,6 +1530,7 @@ async fn answer( &request_id, ErrorClass::OutcomeNotFound, StatusCode::NOT_FOUND, + None, ) .await; } @@ -3372,71 +3465,168 @@ fn journal_fault(error: &tokio_postgres::Error) -> String { } async fn authenticate(state: &FacadeState, headers: &HeaderMap) -> Result { - let Some(token) = bearer_token(headers) else { - state.authenticator.log_header_refusal(); - return Err(CallerRefusal::Unauthenticated); - }; + let token = bearer_token(headers).map_err(CallerRefusal::Unauthenticated)?; state.authenticator.authenticate(token).await } -/// The bearer credential of the `Authorization` header, if it carries one. -fn bearer_token(headers: &HeaderMap) -> Option<&str> { - let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?; - let (scheme, token) = value.split_once(' ')?; - (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) +/// The bearer credential of the `Authorization` header, or the check its +/// header failed: absent or another scheme is a missing credential, an +/// unreadable or empty one is a malformed credential. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let value = headers + .get(header::AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + let Some((scheme, token)) = value.split_once(' ') else { + return Err(if value.eq_ignore_ascii_case("bearer") { + FailedCheck::CredentialMalformed + } else { + FailedCheck::CredentialMissing + }); + }; + if !scheme.eq_ignore_ascii_case("bearer") { + return Err(FailedCheck::CredentialMissing); + } + if token.is_empty() { + return Err(FailedCheck::CredentialMalformed); + } + Ok(token) +} + +/// Guard for every answer built from a status and an optional failed check: +/// a 401 or 403 names the check that refused the caller. One that arrives +/// without it has nothing to count, which a debug build refuses outright and a +/// release build logs. +pub(crate) fn require_refusal_check(status: StatusCode, check: Option) { + if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) && check.is_none() { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + status = status.as_u16(), + "a refusal was answered without its failed check" + ); + } +} + +/// The claim the verifier reads a caller's scopes from. +pub(crate) const SCOPE_CLAIM: &str = "scope"; + +/// The values the operator declared for a scope refusal of the operation on +/// the record type: the scope claim, and the access profile that names the +/// operation and record type with the scopes it requires. When no profile or +/// more than one names them, only the claim is declared. Nothing here comes +/// from the caller's token. +fn declared_scope(project: &AdapterProject, operation: &str, record_type: &str) -> DeclaredScope { + let mut naming = project.access_profiles.iter().filter(|profile| { + profile.operations.iter().any(|id| id.as_str() == operation) + && profile + .record_types + .iter() + .any(|name| name.as_str() == record_type) + }); + let declared = DeclaredScope::new(SCOPE_CLAIM); + match (naming.next(), naming.next()) { + (Some(profile), None) => { + let declared = declared.with_access_profile(profile.id.as_str()); + if profile.scopes.is_empty() { + declared + } else { + declared.with_required_scope( + profile + .scopes + .iter() + .map(|scope| scope.as_str()) + .collect::>() + .join(" "), + ) + } + } + _ => declared, + } +} + +/// Attach the declared scope values to a scope refusal, for the recording +/// layer. Any other refusal is returned as it is. +fn with_declared_scope( + mut response: Response, + check: FailedCheck, + project: &AdapterProject, + operation: &str, + record_type: &str, +) -> Response { + if check == FailedCheck::Scope { + response + .extensions_mut() + .insert(declared_scope(project, operation, record_type)); + } + response +} + +/// Mark a response as the refusal of `check`, for the recording layer. +fn noted(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response } /// Whether some access profile the caller's scopes satisfy admits the /// operation on the record type. A profile that names no scope admits /// nobody: an empty requirement is not a satisfied one. fn admits(project: &AdapterProject, caller: &Caller, operation: &ServedOperation) -> bool { - project.access_profiles.iter().any(|profile| { - !profile.scopes.is_empty() - && profile - .scopes - .iter() - .all(|scope| caller.scopes.iter().any(|held| held == scope.as_str())) - && profile - .operations - .iter() - .any(|id| id.as_str() == operation.operation) - && profile - .record_types - .iter() - .any(|name| name.as_str() == operation.record_type) - }) + admitted( + project, + caller, + operation.operation.as_str(), + operation.record_type.as_str(), + ) + .is_ok() } -fn admits_stored( +/// The check a refused call failed: `Scope` when no profile's scopes are all +/// held, `Operation` when some profile is held and none names the operation +/// on the record type. +fn admitted( project: &AdapterProject, caller: &Caller, profile_operation: &str, record_type: &str, -) -> bool { - project.access_profiles.iter().any(|profile| { - !profile.scopes.is_empty() - && profile +) -> Result<(), FailedCheck> { + let mut scoped = false; + for profile in &project.access_profiles { + if profile.scopes.is_empty() + || !profile .scopes .iter() .all(|scope| caller.scopes.iter().any(|held| held == scope.as_str())) - && profile - .operations - .iter() - .any(|id| id.as_str() == profile_operation) + { + continue; + } + scoped = true; + if profile + .operations + .iter() + .any(|id| id.as_str() == profile_operation) && profile .record_types .iter() .any(|name| name.as_str() == record_type) + { + return Ok(()); + } + } + Err(if scoped { + FailedCheck::Operation + } else { + FailedCheck::Scope }) } fn refusal_response(profile: Problems<'_>, refusal: CallerRefusal, request_id: &str) -> Response { let (class, status) = match refusal { - CallerRefusal::Unauthenticated => { + CallerRefusal::Unauthenticated(_) => { (ErrorClass::FacadeUnauthenticated, StatusCode::UNAUTHORIZED) } CallerRefusal::Unavailable if profile.profile.is_govstack_consultation() => { - return consultation_unavailable(request_id); + return noted(consultation_unavailable(request_id), refusal.failed_check()); } CallerRefusal::Unavailable => (ErrorClass::Facade, StatusCode::SERVICE_UNAVAILABLE), }; @@ -3446,7 +3636,7 @@ fn refusal_response(profile: Problems<'_>, refusal: CallerRefusal, request_id: & .headers_mut() .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); } - response + noted(response, refusal.failed_check()) } /// The members of a record a route may wrap its domain fields in, beside the @@ -3718,6 +3908,9 @@ pub(crate) struct Refusal { /// maps to the fixed request member holding it. validation_pointers: Vec, detail: Option<&'static str>, + /// The check a caller refusal failed, for the operator-side counter and + /// log. `None` for a request that is merely invalid. + check: Option, } trait LoadedProblems { @@ -3759,6 +3952,7 @@ impl Refusal { write_problem: Some(code), validation_pointers: Vec::new(), detail: None, + check: None, } } @@ -3770,6 +3964,7 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, } } @@ -3781,6 +3976,19 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, + } + } + + /// The refusal of a cursor the codec would not open. A cursor that fails + /// authentication was tampered with or minted for another caller, + /// binding or client, and the two are one by construction, so the check + /// is `Ownership`. + fn from_cursor(refusal: CursorRefusal) -> Self { + Self { + check: matches!(refusal, CursorRefusal::Unauthenticated) + .then_some(FailedCheck::Ownership), + ..Self::invalid_cursor(refusal.reason()) } } @@ -3792,6 +4000,7 @@ impl Refusal { write_problem: None, validation_pointers: Vec::new(), detail: None, + check: None, } } } @@ -3900,7 +4109,7 @@ fn open_search( let binding = cursor_binding(state, operation, caller, filters); let sealed = codec .open(cursor, &binding, SystemTime::now()) - .map_err(|refusal: CursorRefusal| Refusal::invalid_cursor(refusal.reason()))?; + .map_err(Refusal::from_cursor)?; let (size, continuation) = unwrap_continuation(sealed).ok_or_else(|| Refusal::invalid_cursor("malformed"))?; (Some(continuation), Some(size)) @@ -4515,7 +4724,11 @@ fn seal_next( /// Answer a verified caller's refused call (403, or a record type the /// operation does not serve) after journaling it as `callRefused` with the /// class and status only. The refusal is also logged, so an operator sees it -/// without reading the journal. +/// without reading the journal. `check` names the check a caller refusal (403, +/// or a concealing 404) failed, for the operator-side counter and log; it is +/// `None` for an answer that is not a refusal of the caller, such as an +/// unsupported media type. +#[allow(clippy::too_many_arguments)] async fn refuse_call( state: &FacadeState, operation: &ServedOperation, @@ -4524,7 +4737,9 @@ async fn refuse_call( request_id: &str, class: ErrorClass, status: StatusCode, + check: Option, ) -> Response { + require_refusal_check(status, check); let profile = state.loaded.problems(); tracing::warn!( class = class.class(), @@ -4549,7 +4764,11 @@ async fn refuse_call( request_id, ); } - facade_problem(profile, class, status, record_type, request_id) + let response = facade_problem(profile, class, status, record_type, request_id); + match check { + Some(check) => noted(response, check), + None => response, + } } /// Refuse a verified and admitted call whose supplied whole-contract pin is @@ -4750,7 +4969,7 @@ async fn refuse_request( ) }; let mut failure = exchange_failure_detail(profile, refusal.class); - failure["reason"] = Value::String(refusal.reason); + failure["reason"] = Value::String(refusal.reason.clone()); if operation.write_support.is_some() { let code = refusal.write_problem.or_else(|| { (refusal.status == StatusCode::UNPROCESSABLE_ENTITY).then_some("invalid-content") @@ -4777,6 +4996,22 @@ async fn refuse_request( ); } warn_exchange_failed(refusal.class, refusal.status); + let check = refusal.check; + let response = refusal_answer(profile, operation, record_type, request_id, &refusal); + match check { + Some(check) => noted(response, check), + None => response, + } +} + +/// The answer a refused request gets, rendered from its class and status. +fn refusal_answer( + profile: Problems<'_>, + operation: &ServedOperation, + record_type: &str, + request_id: &str, + refusal: &Refusal, +) -> Response { if let Some(code) = refusal.write_problem { return govstack_problem(code, refusal.status, request_id); } @@ -5159,6 +5394,63 @@ mod generated_properties; mod tests { use super::*; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_forbidden_answer_without_its_check_is_not_built() { + require_refusal_check(StatusCode::FORBIDDEN, None); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn an_unauthorized_answer_without_its_check_is_not_built() { + require_refusal_check(StatusCode::UNAUTHORIZED, None); + } + + #[test] + fn answers_with_a_check_or_that_are_not_caller_refusals_are_built() { + require_refusal_check(StatusCode::FORBIDDEN, Some(FailedCheck::Scope)); + require_refusal_check(StatusCode::NOT_FOUND, None); + require_refusal_check(StatusCode::NOT_ACCEPTABLE, None); + } + + #[test] + fn a_scope_refusal_declares_the_claim_and_the_profile_that_names_the_operation() { + let project = example_project(json!(["records.read"])); + let named = declared_scope(&project, "records-get", "person"); + assert_eq!(named.scope_claim(), "scope"); + assert_eq!(named.required_scope(), Some("records.read")); + assert_eq!(named.access_profile(), Some("records-reader")); + // No profile names the operation, so only the claim is declared. + let unnamed = declared_scope(&project, "records-purge", "person"); + assert_eq!(unnamed.scope_claim(), "scope"); + assert_eq!(unnamed.required_scope(), None); + assert_eq!(unnamed.access_profile(), None); + } + + #[test] + fn only_a_scope_refusal_carries_declared_values() { + let project = example_project(json!(["records.read"])); + let answer = || StatusCode::FORBIDDEN.into_response(); + let scope = with_declared_scope( + answer(), + FailedCheck::Scope, + &project, + "records-get", + "person", + ); + assert!(scope.extensions().get::().is_some()); + let operation = with_declared_scope( + answer(), + FailedCheck::Operation, + &project, + "records-get", + "person", + ); + assert!(operation.extensions().get::().is_none()); + } + fn lookup_filters(value: &str) -> serde_json::Map { json!({"selector": "by-record-id", "values": {"record-id": value}}) .as_object() @@ -5704,6 +5996,88 @@ mod tests { assert!(!admits(&example_project(json!([])), &caller, &operation)); } + #[test] + fn a_refused_call_names_the_check_it_failed() { + let caller = Caller { + reference: "caller".to_owned(), + issuer: "https://issuer.example.invalid".to_owned(), + client_id: "case-portal".to_owned(), + scopes: vec!["records.read".to_owned()], + }; + let project = example_project(json!(["records.read"])); + assert_eq!(admitted(&project, &caller, "records-get", "person"), Ok(())); + // The caller holds the profile's scope but the profile names no such + // operation or record type. + assert_eq!( + admitted(&project, &caller, "records-purge", "person"), + Err(FailedCheck::Operation) + ); + assert_eq!( + admitted(&project, &caller, "records-get", "household"), + Err(FailedCheck::Operation) + ); + // No profile's scopes are all held, and a profile with no scope + // admits nobody. + let stranger = Caller { + scopes: vec!["other.scope".to_owned()], + ..caller + }; + assert_eq!( + admitted(&project, &stranger, "records-get", "person"), + Err(FailedCheck::Scope) + ); + assert_eq!( + admitted( + &example_project(json!([])), + &stranger, + "records-get", + "person" + ), + Err(FailedCheck::Scope) + ); + } + + #[test] + fn a_bearer_header_names_the_check_it_failed() { + let with = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_str(value).expect("a header value"), + ); + } + headers + }; + assert_eq!(bearer_token(&with(Some("Bearer abc"))), Ok("abc")); + assert_eq!(bearer_token(&with(Some("bearer abc"))), Ok("abc")); + assert_eq!( + bearer_token(&with(None)), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&with(Some("Basic YWJj"))), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&with(Some("Bearer"))), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + bearer_token(&with(Some("Bearer "))), + Err(FailedCheck::CredentialMalformed) + ); + let mut unreadable = HeaderMap::new(); + unreadable.insert( + header::AUTHORIZATION, + HeaderValue::from_bytes(b"Bearer \xff").expect("opaque bytes"), + ); + assert_eq!( + bearer_token(&unreadable), + Err(FailedCheck::CredentialMalformed) + ); + } + fn person_schema() -> Value { json!({ "type": "object", diff --git a/crates/registry-adapter/src/metrics.rs b/crates/registry-adapter/src/metrics.rs index 2eba64ebf6..7b9428e703 100644 --- a/crates/registry-adapter/src/metrics.rs +++ b/crates/registry-adapter/src/metrics.rs @@ -21,7 +21,7 @@ use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use axum::extract::{MatchedPath, State}; use axum::http::header::CONTENT_TYPE; @@ -31,6 +31,7 @@ use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::Router; use registry_adapter_core::ErrorClass; +use registry_platform_authcommon::{DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, CONTENT_TYPE as METRICS_CONTENT_TYPE, }; @@ -68,7 +69,20 @@ const UPSTREAM_CLASSES: [ErrorClass; 11] = [ /// `adapter_retention_sweep_failures_total`. const SWEEP_STORES: [&str; 3] = ["journal", "idempotency", "other"]; +/// The process's refusal recorder: one counter and one log budget for every +/// listener of this process, the facade and the payment routes alike. +static REFUSALS: OnceLock> = OnceLock::new(); + +/// The recorder behind `adapter_request_refusals_total` and the +/// `request refused` log line. +pub fn refusal_recorder() -> Arc { + Arc::clone( + REFUSALS.get_or_init(|| Arc::new(RefusalRecorder::new("adapter").expect(DECLARATION))), + ) +} + pub struct Metrics { + refusals: Arc, requests: CounterVec, upstream_failures: CounterVec, journal_write_failures: CounterVec, @@ -88,6 +102,7 @@ impl Default for Metrics { let sweep: Vec<[&str; 1]> = SWEEP_STORES.iter().map(|s| [*s]).collect(); let sweep: Vec<&[&str]> = sweep.iter().map(|s| s.as_slice()).collect(); Self { + refusals: refusal_recorder(), requests: CounterVec::new( "adapter_http_requests_total", "Answered facade HTTP requests, by route template, method, and status class.", @@ -118,6 +133,12 @@ impl Default for Metrics { } impl Metrics { + /// The recorder that counts and logs every refused request. + #[must_use] + pub fn refusals(&self) -> Arc { + Arc::clone(&self.refusals) + } + /// Count one answered request under its closed labels. pub fn record_request(&self, route: &str, method: &Method, status: StatusCode) { count( @@ -158,6 +179,7 @@ impl Metrics { &self.upstream_failures, &self.journal_write_failures, &self.sweep_failures, + self.refusals.counter(), ] { counter.write(&mut out).expect(DECLARATION); } @@ -222,6 +244,22 @@ pub async fn count_requests( response } +/// Count and log every refused request once, under the check its answer +/// carries in the response extensions. The extension is not serialized, so +/// no byte of the answer depends on it. +pub async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + let declared = response.extensions().get::(); + registry_platform_authcommon::record_refusal!(recorder, *note, declared = declared); + } + response +} + /// The router the metrics listener serves: the counters and nothing else. pub fn metrics_router(metrics: Arc) -> Router { Router::new() @@ -353,6 +391,88 @@ mod tests { )); } + #[test] + fn the_refusal_counter_declares_every_check_and_publishes_it_at_zero() { + let text = Metrics::default().render(); + let declared = text + .lines() + .filter(|line| line.starts_with("adapter_request_refusals_total{check=\"")) + .count(); + assert_eq!(declared, registry_platform_authcommon::FailedCheck::COUNT); + } + + /// The refusal line a scope refusal writes, driven through the recording + /// layer with the scope values the answer carries. + async fn refusal_line(check: registry_platform_authcommon::FailedCheck) -> String { + use registry_platform_testing::CapturedDiagnosticLogs; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + let recorder = Arc::new(RefusalRecorder::new("adapter_test").expect("recorder")); + let app = Router::new() + .route( + "/", + get(move || async move { + let mut response = StatusCode::FORBIDDEN.into_response(); + response.extensions_mut().insert(RefusalNote::new(check)); + response.extensions_mut().insert( + DeclaredScope::new("scope") + .with_required_scope("records.read") + .with_access_profile("records-reader"), + ); + response + }), + ) + .layer(axum::middleware::from_fn_with_state( + recorder, + record_refusals, + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback test listener"); + let address = listener.local_addr().expect("the bound address"); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let logs = CapturedDiagnosticLogs::default(); + let _guard = tracing::dispatcher::set_default(&logs.subscriber()); + let mut stream = tokio::net::TcpStream::connect(address) + .await + .expect("connect"); + stream + .write_all( + b"GET / HTTP/1.1\r\nhost: test\r\nauthorization: Bearer canary-token-scope\r\nconnection: close\r\n\r\n", + ) + .await + .expect("send"); + let mut answer = Vec::new(); + stream.read_to_end(&mut answer).await.expect("read"); + assert!(answer.starts_with(b"HTTP/1.1 403")); + logs.text() + } + + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_values_and_no_token_value() { + let text = refusal_line(registry_platform_authcommon::FailedCheck::Scope).await; + assert!(text.contains("\"scope_claim\":\"scope\""), "{text}"); + assert!( + text.contains("\"required_scope\":\"records.read\""), + "{text}" + ); + assert!( + text.contains("\"access_profile\":\"records-reader\""), + "{text}" + ); + assert!(!text.contains("canary-token-scope"), "{text}"); + } + + #[tokio::test] + async fn a_refusal_other_than_scope_names_no_declared_values() { + let text = refusal_line(registry_platform_authcommon::FailedCheck::Operation).await; + assert!(text.contains("request refused"), "{text}"); + assert!(!text.contains("scope_claim"), "{text}"); + assert!(!text.contains("required_scope"), "{text}"); + } + fn text_has(metrics: &Metrics, line: &str) -> bool { metrics.render().lines().any(|found| found == line) } diff --git a/crates/registry-adapter/src/payments/g2p_model.rs b/crates/registry-adapter/src/payments/g2p_model.rs index d78c7d15ee..5afb0df99f 100644 --- a/crates/registry-adapter/src/payments/g2p_model.rs +++ b/crates/registry-adapter/src/payments/g2p_model.rs @@ -14,6 +14,7 @@ use super::{ }, }; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use registry_platform_httputil::loopback::loopback_address; use registry_platform_yaml::SecretReference; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; @@ -1070,9 +1071,11 @@ fn provider_base_url(value: &str) -> bool { if url.scheme() != "http" { return false; } + // An address literal only: the name `localhost` is refused here, where + // no resolved address is available to pin it. match url.host() { - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Ipv4(address)) => loopback_address(address.into()), + Some(url::Host::Ipv6(address)) => loopback_address(address.into()), Some(url::Host::Domain(_)) | None => false, } } @@ -1156,3 +1159,26 @@ fn currency_scale<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result::deserialize(deserializer) .map(|value| u8::try_from(value.get()).expect("the bounded scale fits in u8")) } + +#[cfg(test)] +mod tests { + use super::provider_base_url; + + #[test] + fn a_plain_http_provider_must_be_a_loopback_address_literal() { + for accepted in [ + "http://127.0.0.1/", + "http://[::1]/", + "https://provider.example/", + ] { + assert!(provider_base_url(accepted), "{accepted}"); + } + for refused in [ + "http://localhost/", + "http://10.0.0.1/", + "http://provider.example/", + ] { + assert!(!provider_base_url(refused), "{refused}"); + } + } +} diff --git a/crates/registry-adapter/src/payments/g2p_service.rs b/crates/registry-adapter/src/payments/g2p_service.rs index e1530d4e7b..9eb40dc398 100644 --- a/crates/registry-adapter/src/payments/g2p_service.rs +++ b/crates/registry-adapter/src/payments/g2p_service.rs @@ -22,7 +22,9 @@ use registry_platform_crypto::transit_rsa_no_oid::{ TransitRsaNoOidKeyConfig, TransitRsaNoOidSigner, TransitRsaNoOidVerifier, }; use registry_platform_httputil::client::BearerToken; -use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, ServiceBaseUrl, +}; use serde::Serialize; use serde_json::Value; use std::{collections::BTreeMap, future::Future, pin::Pin, sync::Arc, time::Duration}; @@ -322,7 +324,8 @@ impl HttpG2pProvider { .send() .await .map_err(|_| G2pProviderError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| G2pProviderError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| G2pProviderError::Unavailable)?; let status = response.status().as_u16(); let body = read_bounded(response, 131_072) .await @@ -417,7 +420,7 @@ impl G2pProviderPort for HttpG2pProvider { .execute(prepared) .await .map_err(|_| G2pProviderError::OutcomeUnknown)?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| G2pProviderError::OutcomeUnknown)?; let status = response.status().as_u16(); let signature = match &response_trust { diff --git a/crates/registry-adapter/src/payments/g2p_store.rs b/crates/registry-adapter/src/payments/g2p_store.rs index 96726c214d..a025a0e81f 100644 --- a/crates/registry-adapter/src/payments/g2p_store.rs +++ b/crates/registry-adapter/src/payments/g2p_store.rs @@ -74,6 +74,18 @@ pub enum DispatchAuthorization { Hold(G2pAttempt), } +/// The table privileges a runtime role needs for the G2P tables when +/// `payments.yaml` declares a disbursement connection. Startup checks them, +/// and `adapter serve` grants those a split runtime role lacks. +pub const RUNTIME_GRANTS: [(&str, &[&str]); 3] = [ + ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_g2p_commands", &["SELECT", "INSERT"]), + ("adapter_g2p_events", &["SELECT", "INSERT"]), +]; +/// The sequence the events table draws its identifiers from. A runtime role +/// needs USAGE on it. +pub const RUNTIME_SEQUENCE: &str = "adapter_g2p_events_sequence_seq"; + impl G2pStore { pub fn new(pool: Pool, deployment: String) -> Self { Self { pool, deployment } @@ -105,11 +117,7 @@ impl G2pStore { pub async fn check_privileges(&self) -> Result<(), G2pError> { let client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; - for (table, privileges) in [ - ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"][..]), - ("adapter_g2p_commands", &["SELECT", "INSERT"][..]), - ("adapter_g2p_events", &["SELECT", "INSERT"][..]), - ] { + for (table, privileges) in RUNTIME_GRANTS { if !crate::journal::missing_table_privileges(&client, table, privileges) .await .map_err(|_| G2pError::Unavailable)? @@ -121,7 +129,7 @@ impl G2pStore { let row = client .query_one( "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", - &[&"adapter_g2p_events_sequence_seq"], + &[&RUNTIME_SEQUENCE], ) .await .map_err(|_| G2pError::Unavailable)?; diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 0356db8157..d3898bb1c6 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -14,7 +14,7 @@ use super::{ }, provider_mapping::{PaymentMappingProgram, PaymentMappingRegistry}, registry::BregBridge, - service::{PaymentService, SyntheticProvider}, + service::{PaymentFailure, PaymentService, SyntheticProvider}, store::{migrate, PaymentStore}, }; use crate::serve::{Authenticator, Caller, CallerRefusal, ServeError}; @@ -22,6 +22,7 @@ use axum::{ body::Bytes, extract::{DefaultBodyLimit, Path as RoutePath, State}, http::{HeaderMap, HeaderValue, StatusCode, Uri}, + middleware, response::{IntoResponse, Response}, routing::{get, post}, Json, Router, @@ -32,6 +33,7 @@ use registry_payment_protocol::{ PaymentProblem, PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, RecordReceipt, RequestCollection, RequestDisbursement, }; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote}; use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, }; @@ -108,7 +110,7 @@ pub fn contract(config: &PaymentsConfig) -> serde_json::Value { pub fn load_config(path: &Path) -> Result { let absolute = std::fs::canonicalize(path) .map_err(|_| refused("payment configuration could not be read"))?; - let config = RuntimeConfigLoader::new(RuntimeEnvelope { + let config = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) @@ -224,157 +226,200 @@ fn load_provider_packs(paths: &[PathBuf]) -> Result Result { - let config = load_config(path)?; - let packs = load_provider_packs(provider_pack_paths)?; - for connection in &config.connections { - let Some(pin) = connection.binding.provider_pack.as_ref() else { - if connection.binding.simulation { - continue; +/// A payment configuration whose packs, mapping and credentials are settled, +/// before any database work: the caller migrates and grants, then builds the +/// router over the runtime pool. +pub(crate) struct PreparedPayments { + config: PaymentsConfig, + packs: LoadedPaymentPacks, + resolver: Arc, + authenticator: Authenticator, + g2p_provider: HttpG2pProvider, + deployment: String, +} + +impl PreparedPayments { + pub(crate) async fn prepare( + runtime: &AdapterRuntimeConfig, + path: &Path, + provider_pack_paths: &[PathBuf], + ) -> Result { + let config = load_config(path)?; + let packs = load_provider_packs(provider_pack_paths)?; + for connection in &config.connections { + let Some(pin) = connection.binding.provider_pack.as_ref() else { + if connection.binding.simulation { + continue; + } + return Err(refused("payment connection must pin the provider pack")); + }; + let pack = packs.for_pin(pin)?; + if pack.connector != connection.binding.connector_kind() + || !pack.capabilities.contains(&PaymentCapability::Collection) + { + return Err(refused( + "payment provider pack lacks collection capability or connector", + )); + } + if matches!( + &connection.binding.provider, + super::config::CollectionProvider::Http { .. } + ) && !mapping_auth_matches( + pack.mapping + .as_ref() + .and_then(|mapping| mapping.collection.as_ref()), + PaymentProviderAuth::Bearer, + ) { + return Err(refused( + "payment provider collection mapping requires unsupported authentication", + )); } - return Err(refused("payment connection must pin the provider pack")); - }; - let pack = packs.for_pin(pin)?; - if pack.connector != connection.binding.connector_kind() - || !pack.capabilities.contains(&PaymentCapability::Collection) - { - return Err(refused( - "payment provider pack lacks collection capability or connector", - )); - } - if matches!( - &connection.binding.provider, - super::config::CollectionProvider::Http { .. } - ) && !mapping_auth_matches( - pack.mapping - .as_ref() - .and_then(|mapping| mapping.collection.as_ref()), - PaymentProviderAuth::Bearer, - ) { - return Err(refused( - "payment provider collection mapping requires unsupported authentication", - )); - } - } - for connection in &config.disbursements { - let pack = packs.for_pin(&connection.binding.provider_pack)?; - if pack.connector != ConnectorKind::AdapterPaymentHttpV1 - || !pack.capabilities.contains(&PaymentCapability::Disbursement) - { - return Err(refused( - "payment provider pack lacks generic HTTP disbursement capability", - )); } - if !mapping_auth_matches( - pack.mapping - .as_ref() - .and_then(|mapping| mapping.disbursement.as_ref()), - connection.binding.provider.auth_profile(), - ) { - return Err(refused( + for connection in &config.disbursements { + let pack = packs.for_pin(&connection.binding.provider_pack)?; + if pack.connector != ConnectorKind::AdapterPaymentHttpV1 + || !pack.capabilities.contains(&PaymentCapability::Disbursement) + { + return Err(refused( + "payment provider pack lacks generic HTTP disbursement capability", + )); + } + if !mapping_auth_matches( + pack.mapping + .as_ref() + .and_then(|mapping| mapping.disbursement.as_ref()), + connection.binding.provider.auth_profile(), + ) { + return Err(refused( "payment provider disbursement mapping authentication differs from the connection", )); - } - if !live_disbursement_auth_supported(connection.binding.provider.auth_profile()) { - return Err(refused( + } + if !live_disbursement_auth_supported(connection.binding.provider.auth_profile()) { + return Err(refused( "payment provider disbursement authentication is not implemented by the live host", )); + } } - } - let resolver = Arc::new(resolver(runtime)?); - for connection in &config.connections { - for reference in [ - &connection.binding.provider_credential_ref, - &connection.binding.registry.credential_ref, - ] { - let value = resolver - .resolve(reference.as_str()) - .map_err(|_| refused("a payment credential could not be resolved"))?; - let value = std::str::from_utf8(value.expose_secret()) - .map_err(|_| refused("a payment credential was refused"))?; - registry_platform_httputil::client::BearerToken::new(value.to_owned()) - .map_err(|_| refused("a payment credential was refused"))?; + let resolver = Arc::new(resolver(runtime)?); + for connection in &config.connections { + for reference in [ + &connection.binding.provider_credential_ref, + &connection.binding.registry.credential_ref, + ] { + let value = resolver + .resolve(reference.as_str()) + .map_err(|_| refused("a payment credential could not be resolved"))?; + let value = std::str::from_utf8(value.expose_secret()) + .map_err(|_| refused("a payment credential was refused"))?; + registry_platform_httputil::client::BearerToken::new(value.to_owned()) + .map_err(|_| refused("a payment credential was refused"))?; + } } - } - for connection in &config.disbursements { - let references = [ - connection.binding.provider.credential_ref(), - &connection.binding.registry.credential_ref, - ]; - for reference in references { - let value = resolver - .resolve(reference.as_str()) - .map_err(|_| refused("a payment credential could not be resolved"))?; - let value = std::str::from_utf8(value.expose_secret()) - .map_err(|_| refused("a payment credential was refused"))?; - registry_platform_httputil::client::BearerToken::new(value.to_owned()) - .map_err(|_| refused("a payment credential was refused"))?; + for connection in &config.disbursements { + let references = [ + connection.binding.provider.credential_ref(), + &connection.binding.registry.credential_ref, + ]; + for reference in references { + let value = resolver + .resolve(reference.as_str()) + .map_err(|_| refused("a payment credential could not be resolved"))?; + let value = std::str::from_utf8(value.expose_secret()) + .map_err(|_| refused("a payment credential was refused"))?; + registry_platform_httputil::client::BearerToken::new(value.to_owned()) + .map_err(|_| refused("a payment credential was refused"))?; + } } - } - let authenticator = crate::serve::authenticator(runtime, &resolver).await?; - let migration = crate::serve::pool(&runtime.database, &resolver, true)?; - { - let mut client = migration - .get() + let authenticator = crate::serve::authenticator(runtime, &resolver).await?; + // Transit signer and verifier setup reads no database, so a wrong + // socket, mount or key refuses here, before any grant. + let g2p_provider_bindings = config + .disbursements + .iter() + .map(|connection| connection.binding.provider.clone()) + .collect::>(); + let g2p_provider = HttpG2pProvider::initialize(resolver.clone(), &g2p_provider_bindings) .await - .map_err(|_| refused("payment migration database unavailable"))?; - migrate(&mut client) + .map_err(|_| refused("payment disbursement authentication initialization failed"))?; + Ok(Self { + config, + packs, + resolver, + authenticator, + g2p_provider, + deployment: runtime.id.as_str().to_owned(), + }) + } + + /// Create the collection and G2P tables as the migration role. + pub(crate) async fn migrate(client: &mut deadpool_postgres::Client) -> Result<(), ServeError> { + migrate(client) .await .map_err(|_| refused("payment database migration failed"))?; - migrate_g2p(&mut client) + migrate_g2p(client) .await - .map_err(|_| refused("G2P database migration failed"))?; + .map_err(|_| refused("G2P database migration failed")) } - let store = PaymentStore::new(pool.clone(), runtime.id.as_str().to_owned()); - store - .check_privileges() - .await - .map_err(|_| refused("payment runtime role lacks required table or sequence privileges"))?; - let g2p_store = G2pStore::new(pool.clone(), runtime.id.as_str().to_owned()); - if !config.disbursements.is_empty() { - g2p_store - .check_privileges() - .await - .map_err(|_| refused("G2P runtime role lacks required table or sequence privileges"))?; + + /// What the runtime role must hold: the collection tables, and the G2P + /// tables when a disbursement connection is declared. + pub(crate) fn requirements(&self) -> crate::serve::Requirements { + crate::serve::Requirements::payments(!self.config.disbursements.is_empty()) } - let g2p_provider_bindings = config - .disbursements - .iter() - .map(|connection| connection.binding.provider.clone()) - .collect::>(); - let g2p_provider = HttpG2pProvider::initialize(resolver.clone(), &g2p_provider_bindings) - .await - .map_err(|_| refused("payment disbursement authentication initialization failed"))?; - let g2p = G2pService::new( - g2p_store, - Arc::new(BregG2pBridge::new(resolver.clone())), - Arc::new(g2p_provider), - ); - let g2p = if let Some(mapping) = packs.mapping.clone() { - g2p.with_mapping(mapping) - } else { - g2p - }; - let disbursements = config.disbursements.clone(); - let service = PaymentService::new( - config, - store, - Arc::new(BregBridge::new(resolver.clone())), - Arc::new(SyntheticProvider::new(resolver, packs.mapping)), - ) - .map_err(|_| refused("payment service was refused"))?; - let state = Arc::new(HttpState { - authenticator, - service, - g2p, - disbursements, - }); - Ok(Router::new() + + pub(crate) async fn into_router( + self, + pool: deadpool_postgres::Pool, + ) -> Result { + let Self { + config, + packs, + resolver, + authenticator, + g2p_provider, + deployment, + } = self; + let store = PaymentStore::new(pool.clone(), deployment.clone()); + store.check_privileges().await.map_err(|_| { + refused("payment runtime role lacks required table or sequence privileges") + })?; + let g2p_store = G2pStore::new(pool.clone(), deployment.clone()); + if !config.disbursements.is_empty() { + g2p_store.check_privileges().await.map_err(|_| { + refused("G2P runtime role lacks required table or sequence privileges") + })?; + } + let g2p = G2pService::new( + g2p_store, + Arc::new(BregG2pBridge::new(resolver.clone())), + Arc::new(g2p_provider), + ); + let g2p = if let Some(mapping) = packs.mapping.clone() { + g2p.with_mapping(mapping) + } else { + g2p + }; + let disbursements = config.disbursements.clone(); + let service = PaymentService::new( + config, + store, + Arc::new(BregBridge::new(resolver.clone())), + Arc::new(SyntheticProvider::new(resolver, packs.mapping)), + ) + .map_err(|_| refused("payment service was refused"))?; + let state = Arc::new(HttpState { + authenticator, + service, + g2p, + disbursements, + }); + Ok(payment_router(state)) + } +} + +/// The payment routes over `state`, with the refusal recording layer. +fn payment_router(state: Arc) -> Router { + Router::new() .route("/v1/payments/{connection}/collections", post(request)) .route( "/v1/payments/{connection}/collections/receipt", @@ -405,7 +450,11 @@ pub async fn load_router( post(record_provider_confirmation), ) .layer(DefaultBodyLimit::max(MAX_PAYMENT_BODY_BYTES)) - .with_state(state)) + .layer(middleware::from_fn_with_state( + crate::metrics::refusal_recorder(), + crate::metrics::record_refusals, + )) + .with_state(state) } pub async fn run_only( @@ -415,7 +464,7 @@ pub async fn run_only( ) -> Result<(), ServeError> { let absolute = std::fs::canonicalize(runtime_path) .map_err(|_| refused("runtime configuration could not be read"))?; - let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { + let runtime = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: registry_adapter_core::ADAPTER_RUNTIME_API_VERSION, kind: registry_adapter_core::ADAPTER_RUNTIME_KIND, }) @@ -424,8 +473,20 @@ pub async fn run_only( .map_err(|_| refused("runtime configuration was refused"))? .config; let resolver = resolver(&runtime)?; + let prepared = PreparedPayments::prepare(&runtime, payments_path, provider_pack_paths).await?; let pool = crate::serve::pool(&runtime.database, &resolver, false)?; - let router = load_router(&runtime, payments_path, provider_pack_paths, pool).await?; + { + let migration = crate::serve::pool(&runtime.database, &resolver, true)?; + let mut client = migration + .get() + .await + .map_err(|_| refused("payment migration database unavailable"))?; + PreparedPayments::migrate(&mut client).await?; + // When the grant step makes no grant, the privilege check in + // `into_router` refuses a role that lacks one. + crate::serve::grant_when_split(&mut client, &pool, &prepared.requirements()).await?; + } + let router = prepared.into_router(pool).await?; let shutdown = crate::serve::shutdown_signal()?; let listener = tokio::net::TcpListener::bind(runtime.listener.bind.0) .await @@ -438,28 +499,46 @@ pub async fn run_only( } async fn caller(state: &HttpState, headers: &HeaderMap) -> Result { - let value = - single_header(headers, "authorization").map_err(|_| HttpError(Error::Unauthenticated))?; - let bearer = value - .strip_prefix("Bearer ") - .ok_or(HttpError(Error::Unauthenticated))?; + let mut values = headers.get_all("authorization").iter(); + let value = match (values.next(), values.next()) { + (Some(value), None) => value.to_str().ok(), + (None, _) => { + return Err(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMissing, + )) + } + _ => None, + } + .ok_or(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMalformed, + ))?; + let bearer = value.strip_prefix("Bearer ").ok_or(HttpError::refused( + Error::Unauthenticated, + FailedCheck::CredentialMissing, + ))?; state .authenticator .authenticate(bearer) .await - .map_err(|error| { - HttpError(match error { - CallerRefusal::Unauthenticated => Error::Unauthenticated, - CallerRefusal::Unavailable => Error::Unavailable, - }) + .map_err(|error| match error { + CallerRefusal::Unauthenticated(_) => { + HttpError::refused(Error::Unauthenticated, error.failed_check()) + } + CallerRefusal::Unavailable => { + HttpError::refused(Error::Unavailable, FailedCheck::KeySourceUnavailable) + } }) } fn single_header<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, HttpError> { let mut values = headers.get_all(name).iter(); match (values.next(), values.next()) { - (Some(value), None) => value.to_str().map_err(|_| HttpError(Error::InvalidRequest)), - _ => Err(HttpError(Error::InvalidRequest)), + (Some(value), None) => value + .to_str() + .map_err(|_| HttpError::plain(Error::InvalidRequest)), + _ => Err(HttpError::plain(Error::InvalidRequest)), } } fn body(headers: &HeaderMap, uri: &Uri, bytes: &[u8]) -> Result { @@ -467,24 +546,25 @@ fn body(headers: &HeaderMap, uri: &Uri, bytes: &[u8]) -> Re || uri.query().is_some() || single_header(headers, "content-type")? != "application/json" { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } // The payment wire contract requires named fields in a JSON object. if !bytes.trim_ascii_start().starts_with(b"{") { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let mut decoder = serde_json::Deserializer::from_slice(bytes); - let request = T::deserialize(&mut decoder).map_err(|_| HttpError(Error::InvalidRequest))?; + let request = + T::deserialize(&mut decoder).map_err(|_| HttpError::plain(Error::InvalidRequest))?; decoder .end() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; Ok(request) } fn collection(value: &str) -> Result { Uuid::parse_str(value) .ok() .filter(|id| !id.is_nil()) - .ok_or(HttpError(Error::InvalidRequest)) + .ok_or(HttpError::plain(Error::InvalidRequest)) } async fn request( @@ -546,7 +626,7 @@ async fn read( ) -> Result { let caller = caller(&state, &headers).await?; if uri.query().is_some() || !bytes.is_empty() { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let id = collection(&id)?; let result = state.service.read(&connection, &caller, id).await; @@ -572,7 +652,7 @@ async fn record_receipt( let id = collection(&id)?; let request: RecordReceipt = body(&headers, &uri, &bytes)?; if request.collection_id != id { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let key = single_header(&headers, "idempotency-key")?; let result = state @@ -601,39 +681,45 @@ async fn g2p_connection<'a>( .disbursements .iter() .find(|entry| entry.id == id) - .ok_or(Error::NotFound) + .ok_or(PaymentFailure::concealing(Error::NotFound)) .and_then(|connection| { - if !connection.allowed_clients.contains(&caller.client_id) - || !caller.scopes.contains(&connection.required_scope) - { - Err(Error::Forbidden) + if !connection.allowed_clients.contains(&caller.client_id) { + Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::RequesterClient, + )) + } else if !caller.scopes.contains(&connection.required_scope) { + Err(PaymentFailure::scope_refused( + &connection.id, + &connection.required_scope, + )) } else { Ok(connection) } }); - if let Err(error) = selected { + if let Err(failure) = &selected { state .service - .audit_access(caller, operation, None, Some(error)) + .audit_access(caller, operation, None, Some(failure.code)) .await - .map_err(|_| HttpError(Error::Unavailable))?; + .map_err(|_| HttpError::plain(Error::Unavailable))?; } - selected.map_err(HttpError) + selected.map_err(HttpError::from) } fn g2p_principal(caller: &Caller) -> Result { super::model::digest(&[&caller.issuer, &caller.client_id, &caller.reference]) } -fn g2p_error(error: G2pError) -> Error { - match error { +fn g2p_error(error: G2pError) -> PaymentFailure { + PaymentFailure::concealing(match error { G2pError::InvalidRequest => Error::InvalidRequest, G2pError::Conflict => Error::Conflict, G2pError::NotFound => Error::NotFound, G2pError::Unavailable => Error::Unavailable, G2pError::OutcomeUnknown => Error::OutcomeUnknown, G2pError::RecoveryHeld => Error::RecoveryHeld, - } + }) } fn disbursement_accepted(attempt: &G2pAttempt) -> Result { @@ -704,17 +790,17 @@ async fn request_disbursement( let request: RequestDisbursement = body(&headers, &uri, &bytes)?; request .validate() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let selected = g2p_connection(&state, &connection, &caller, "request-disbursement").await?; let result = state .g2p .request_disbursement( &connection, - &g2p_principal(&caller).map_err(HttpError)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, request.instruction_record_id, request.instruction_version, @@ -723,7 +809,7 @@ async fn request_disbursement( ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_accepted(&attempt)); + .and_then(|attempt| disbursement_accepted(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -747,24 +833,24 @@ async fn disbursement_receipt( let request: RequestDisbursement = body(&headers, &uri, &bytes)?; request .validate() - .map_err(|_| HttpError(Error::InvalidRequest))?; + .map_err(|_| HttpError::plain(Error::InvalidRequest))?; let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } g2p_connection(&state, &connection, &caller, "request-disbursement-receipt").await?; let result = state .g2p .request_receipt( &connection, - &g2p_principal(&caller).map_err(HttpError)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, request.instruction_record_id, request.instruction_version, ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_accepted(&attempt)); + .and_then(|attempt| disbursement_accepted(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -786,16 +872,20 @@ async fn read_disbursement( ) -> Result { let caller = caller(&state, &headers).await?; if uri.query().is_some() || !bytes.is_empty() { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } g2p_connection(&state, &connection, &caller, "read-disbursement").await?; let id = collection(&id)?; let result = state .g2p - .disbursement_status(&connection, &g2p_principal(&caller).map_err(HttpError)?, id) + .disbursement_status( + &connection, + &g2p_principal(&caller).map_err(HttpError::plain)?, + id, + ) .await .map_err(g2p_error) - .and_then(|attempt| disbursement_status(&attempt)); + .and_then(|attempt| disbursement_status(&attempt).map_err(PaymentFailure::from)); finish( &state, &caller, @@ -819,26 +909,26 @@ async fn record_provider_confirmation( let id = collection(&id)?; let request: RecordProviderConfirmation = body(&headers, &uri, &bytes)?; if request.disbursement_id != id { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } let key = single_header(&headers, "idempotency-key")?; if !super::config::text(key, 128) { - return Err(HttpError(Error::InvalidRequest)); + return Err(HttpError::plain(Error::InvalidRequest)); } g2p_connection(&state, &connection, &caller, "record-provider-confirmation").await?; let result = state .g2p .record_provider_confirmation( &connection, - &g2p_principal(&caller).map_err(HttpError)?, + &g2p_principal(&caller).map_err(HttpError::plain)?, key, id, ) .await .map_err(g2p_error) - .and_then(|attempt| { + .and_then(|attempt| -> Result<_, PaymentFailure> { if attempt.state != G2pAttemptState::ConfirmationRecorded { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } let status = disbursement_status(&attempt)?; let confirmation = ProviderConfirmation { @@ -875,14 +965,19 @@ async fn finish( id: Option, mutation: bool, status: StatusCode, - result: Result, + result: Result, ) -> Result { state .service - .audit_access(caller, operation, id, result.as_ref().err().copied()) + .audit_access( + caller, + operation, + id, + result.as_ref().err().map(|failure| failure.code), + ) .await .map_err(|_| { - HttpError(if mutation { + HttpError::plain(if mutation { Error::OutcomeUnknown } else { Error::Unavailable @@ -890,7 +985,7 @@ async fn finish( })?; result .map(|value| headers((status, Json(value)).into_response())) - .map_err(HttpError) + .map_err(HttpError::from) } /// The attempt an accepted request names, recorded in its audit event. @@ -907,21 +1002,58 @@ impl AuditedAttempt for DisbursementAccepted { self.disbursement_id } } -fn audited_attempt(result: &Result) -> Option { +fn audited_attempt(result: &Result) -> Option { result.as_ref().ok().map(AuditedAttempt::attempt_id) } -struct HttpError(Error); +/// A payment error with, for a refused caller, the check it failed. +struct HttpError { + code: Error, + check: Option, + declared: Option, +} +impl HttpError { + fn plain(code: Error) -> Self { + Self { + code, + check: None, + declared: None, + } + } + fn refused(code: Error, check: FailedCheck) -> Self { + Self { + code, + check: Some(check), + declared: None, + } + } +} +impl From for HttpError { + fn from(failure: PaymentFailure) -> Self { + Self { + code: failure.code, + check: failure.check, + declared: failure.declared, + } + } +} impl IntoResponse for HttpError { fn into_response(self) -> Response { - let problem = PaymentProblem::from(self.0); + let problem = PaymentProblem::from(self.code); let status = StatusCode::from_u16(problem.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + crate::facade::require_refusal_check(status, self.check); let mut response = (status, Json(problem)).into_response(); response.headers_mut().insert( "content-type", HeaderValue::from_static("application/problem+json"), ); + if let Some(check) = self.check { + response.extensions_mut().insert(RefusalNote::new(check)); + } + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } headers(response) } } @@ -948,10 +1080,44 @@ fn refused(message: &str) -> ServeError { ServeError::Configuration(format!("adapter.payment.configuration: {message}")) } +#[cfg(all(test, feature = "postgres-test"))] +mod refusal_tests; + #[cfg(test)] mod tests { use super::*; + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_forbidden_payment_answer_without_its_check_is_not_built() { + let _ = HttpError::plain(Error::Forbidden).into_response(); + } + + #[test] + fn a_payment_scope_refusal_carries_the_connection_and_its_declared_scope() { + let response = HttpError::from(PaymentFailure::scope_refused( + "mifos-main", + "payments.write", + )) + .into_response(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let declared = response + .extensions() + .get::() + .expect("the declared scope values"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("payments.write")); + assert_eq!(declared.access_profile(), Some("mifos-main")); + } + + #[test] + fn a_forbidden_payment_answer_carries_its_check() { + let response = HttpError::refused(Error::Forbidden, FailedCheck::Scope).into_response(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(response.extensions().get::().is_some()); + } + #[test] fn payment_body_requires_a_closed_json_object() { let mut headers = HeaderMap::new(); @@ -980,7 +1146,10 @@ mod tests { assert!( matches!( body::(&headers, &uri, invalid.as_bytes()), - Err(HttpError(Error::InvalidRequest)) + Err(HttpError { + code: Error::InvalidRequest, + .. + }) ), "unexpected result for {invalid}" ); @@ -992,7 +1161,10 @@ mod tests { at_limit.push(b' '); assert!(matches!( body::(&headers, &uri, &at_limit), - Err(HttpError(Error::InvalidRequest)) + Err(HttpError { + code: Error::InvalidRequest, + .. + }) )); } @@ -1014,15 +1186,15 @@ mod tests { simulation: false, }; assert_eq!( - audited_attempt(&Ok(collection.clone())), + audited_attempt::<_, Error>(&Ok(collection.clone())), Some(collection.collection_id) ); assert_eq!( - audited_attempt(&Ok(disbursement.clone())), + audited_attempt::<_, Error>(&Ok(disbursement.clone())), Some(disbursement.disbursement_id) ); assert_eq!( - audited_attempt::(&Err(Error::OutcomeUnknown)), + audited_attempt::(&Err(Error::OutcomeUnknown)), None ); } diff --git a/crates/registry-adapter/src/payments/http/refusal_tests.rs b/crates/registry-adapter/src/payments/http/refusal_tests.rs new file mode 100644 index 0000000000..0bbde657ba --- /dev/null +++ b/crates/registry-adapter/src/payments/http/refusal_tests.rs @@ -0,0 +1,393 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Every refusal of a payment caller, through the real routes over a real +//! journal: the answer is frozen against a checked-in golden file (status, +//! the fixed headers and the body), and the refusal counter rises by one under +//! the check that refused. +//! +//! `ADAPTER_WRITE_GOLDEN=1` rewrites the golden file. Without it the answers +//! are compared to the file. Needs `ADAPTER_TEST_DATABASE_URL`; without it the +//! test fails on the spot. +use super::*; +use registry_platform_config::SecretProvider; +use registry_platform_testing::{ + access_token_test_key, jwks_from_private_jwk, sign_compact_jwt_with_key, +}; +use serde_json::{json, Value}; +use std::time::{SystemTime, UNIX_EPOCH}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "registry-adapter-test"; +const GOLDEN: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/golden/payment_refusals.json" +); + +fn runtime() -> AdapterRuntimeConfig { + serde_json::from_value(json!({ + "id": "payment-refusals", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": ISSUER, + "audience": AUDIENCE, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-keys.json"} + }, + "allowedClients": ["coordinator", "other"], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") +} + +fn payments() -> PaymentsConfig { + serde_json::from_value(json!({"connections":[{ + "id":"fees","institutionId":"ministry","serviceId":"permit","allowedClients":["coordinator"],"requiredScope":"payments:collections", + "binding":{"simulation":true,"currency":"USD","currencyScale":2,"providerCredentialRef":"secret:env/SIMULATOR_TOKEN","providerCredentialIdentity":"producer","replayWindowSeconds":3600, + "provider":{"type":"simulator","connection":{"baseUrl":"http://127.0.0.1:8099/","tenant":"pilot","biller":"ministry","billerName":"Ministry","callbackUrl":"https://programme.example.test/callback","payerFiBic":"SIMBANK"}}, + "registry":{"baseUrl":"http://127.0.0.1:8080/","recordType":"service-fee-bill","recordRoute":"service-fee-bills","readProfile":"reporter","bindProfile":"binder","receiptProfile":"reporter","bindAction":"bind-payment-attempt","receiptAction":"record-payment-receipt","credentialRef":"secret:env/REPORTER_TOKEN","credentialIdentity":"payment-adapter"} + }}]})) + .expect("the payment configuration parses") +} + +fn token( + key: ®istry_platform_crypto::PrivateJwk, + client: &str, + scope: &str, + exp: u64, +) -> String { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("epoch") + .as_secs(); + sign_compact_jwt_with_key( + key, + "at+jwt", + "canary-resource-key", + json!({ + "iss": ISSUER, "aud": AUDIENCE, "sub": "workflow-service", "client_id": client, + "scope": scope, "iat": now, "nbf": now, "exp": exp, + "jti": Uuid::new_v4().to_string(), + }), + ) +} + +/// One request over a fresh connection: status, head, JSON body. +async fn send( + port: u16, + method: &str, + path: &str, + authorization: &[&str], + body: Option<&Value>, +) -> (u16, String, Value) { + let mut request = + format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); + for value in authorization { + request.push_str(&format!("Authorization: {value}\r\n")); + } + let payload = body.map(Value::to_string).unwrap_or_default(); + if body.is_some() { + request.push_str(&format!( + "Content-Type: application/json\r\nIdempotency-Key: key-1\r\nContent-Length: {}\r\n", + payload.len() + )); + } + request.push_str("\r\n"); + request.push_str(&payload); + let mut stream = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("connect the payment router"); + stream + .write_all(request.as_bytes()) + .await + .expect("write the request"); + let mut raw = String::new(); + stream + .read_to_string(&mut raw) + .await + .expect("read the answer"); + let (head, body) = raw.split_once("\r\n\r\n").expect("a header block"); + let status = head + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .expect("a status line"); + ( + status, + head.to_owned(), + serde_json::from_str(body).unwrap_or(Value::Null), + ) +} + +/// A case: name, check, method, path, authorization headers, body. +type Case<'a> = ( + &'a str, + &'a str, + &'a str, + String, + Vec, + Option<&'a Value>, +); + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().skip(1).find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +fn frozen(status: u16, head: &str, body: &Value) -> Value { + let mut body = body.clone(); + if let Some(object) = body.as_object_mut() { + for member in ["traceId", "requestId"] { + if object.contains_key(member) { + object.insert(member.to_owned(), json!("")); + } + } + } + json!({ + "status": status, + "content-type": header(head, "content-type"), + "www-authenticate": header(head, "www-authenticate"), + "retry-after": header(head, "retry-after"), + "cache-control": header(head, "cache-control"), + "x-content-type-options": header(head, "x-content-type-options"), + "traceparent-present": header(head, "traceparent").is_some(), + "body": body, + }) +} + +#[tokio::test] +async fn every_payment_refusal_keeps_its_answer_and_is_counted_under_its_check() { + let signing_key = access_token_test_key(jsonwebtoken::Algorithm::ES256); + let directory = tempfile::tempdir().expect("a scratch directory"); + let root = directory.path().canonicalize().expect("physical directory"); + let key_file = root.join("issuer-keys.json"); + std::fs::write(&key_file, jwks_from_private_jwk(&signing_key).to_string()) + .expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let resolver = Arc::new(SecretResolver::new([SecretProvider::File], root).expect("resolver")); + let authenticator = crate::serve::authenticator(&runtime(), &resolver) + .await + .expect("the authenticator builds over the static key set"); + + let url = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("postgres-test requires ADAPTER_TEST_DATABASE_URL"); + let manager = deadpool_postgres::Manager::new( + url.parse().expect("a database url"), + tokio_postgres::NoTls, + ); + let pool = deadpool_postgres::Pool::builder(manager) + .max_size(8) + .build() + .expect("a pool"); + { + let mut client = pool.get().await.expect("a connection"); + migrate(&mut client).await.expect("the payment tables"); + } + let deployment = format!("payment-refusals-{}", Uuid::new_v4()); + let service = PaymentService::new( + payments(), + PaymentStore::new(pool.clone(), deployment.clone()), + Arc::new(BregBridge::new(resolver.clone())), + Arc::new(SyntheticProvider::new(resolver.clone(), None)), + ) + .expect("the payment service"); + let g2p = G2pService::new( + G2pStore::new(pool, deployment), + Arc::new(BregG2pBridge::new(resolver.clone())), + Arc::new(HttpG2pProvider::new(resolver)), + ); + let state = Arc::new(HttpState { + authenticator, + service, + g2p, + disbursements: Vec::new(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind a probe port"); + let port = listener.local_addr().expect("the probe port").port(); + tokio::spawn(async move { + axum::serve(listener, payment_router(state)) + .await + .expect("the payment router serves"); + }); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("epoch") + .as_secs(); + let good = |client: &str, scope: &str| { + format!("Bearer {}", token(&signing_key, client, scope, now + 300)) + }; + let expired = format!( + "Bearer {}", + token( + &signing_key, + "coordinator", + "payments:collections", + now - 3_600 + ) + ); + let stranger = good("stranger", "payments:collections"); + let forged = { + let other = access_token_test_key(jsonwebtoken::Algorithm::ES256); + format!( + "Bearer {}", + token(&other, "coordinator", "payments:collections", now + 300) + ) + }; + let member = good("coordinator", "payments:collections"); + let other_client = good("other", "payments:collections"); + let no_scope = good("coordinator", "other.scope"); + let collection = json!({"billId": Uuid::new_v4(), "billVersion": 1}); + let disbursement = json!({"instructionRecordId": Uuid::new_v4(), "instructionVersion": 1}); + let known = "/v1/payments/fees/collections"; + let missing_attempt = format!("{known}/{}", Uuid::new_v4()); + + let counter = |check: &str| { + crate::metrics::refusal_recorder() + .counter() + .get(&[check]) + .expect("every check is declared") + }; + let mut answers = serde_json::Map::new(); + // Each case: name, check, method, path, authorization headers, body. + let cases: Vec = vec![ + ( + "no-authorization", + "credential-missing", + "POST", + known.into(), + vec![], + Some(&collection), + ), + ( + "basic-scheme", + "credential-missing", + "POST", + known.into(), + vec!["Basic YWJjOmRlZg==".into()], + Some(&collection), + ), + ( + "two-authorization-headers", + "credential-malformed", + "POST", + known.into(), + vec![member.clone(), member.clone()], + Some(&collection), + ), + ( + "not-a-compact-token", + "credential-malformed", + "POST", + known.into(), + vec!["Bearer not-a-token".into()], + Some(&collection), + ), + ( + "unknown-signer", + "token-signature", + "POST", + known.into(), + vec![forged], + Some(&collection), + ), + ( + "expired", + "token-time", + "POST", + known.into(), + vec![expired], + Some(&collection), + ), + ( + "unlisted-client", + "token-client", + "POST", + known.into(), + vec![stranger], + Some(&collection), + ), + ( + "unknown-connection", + "visibility", + "POST", + "/v1/payments/nowhere/collections".into(), + vec![member.clone()], + Some(&collection), + ), + ( + "client-not-allowed", + "requester-client", + "POST", + known.into(), + vec![other_client], + Some(&collection), + ), + ( + "scope-not-held", + "scope", + "POST", + known.into(), + vec![no_scope], + Some(&collection), + ), + ( + "unknown-attempt", + "visibility", + "GET", + missing_attempt, + vec![member.clone()], + None, + ), + ( + "unknown-disbursement-connection", + "visibility", + "POST", + "/v1/payments/nowhere/disbursements".into(), + vec![member.clone()], + Some(&disbursement), + ), + ]; + let mut deltas: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for (name, check, method, path, authorization, body) in &cases { + let before = counter(check); + let headers: Vec<&str> = authorization.iter().map(String::as_str).collect(); + let (status, head, answer) = send(port, method, path, &headers, *body).await; + answers.insert((*name).to_owned(), frozen(status, &head, &answer)); + *deltas.entry(check).or_default() += counter(check) - before; + } + let answers = Value::Object(answers); + if std::env::var_os("ADAPTER_WRITE_GOLDEN").is_some() { + std::fs::write( + GOLDEN, + serde_json::to_string_pretty(&answers).expect("serialize the golden") + "\n", + ) + .expect("write the golden file"); + } + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(GOLDEN).expect("the golden file is checked in"), + ) + .expect("the golden file is JSON"); + assert_eq!(answers, golden, "a payment refusal answer changed"); + let mut wanted: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for (_, check, ..) in &cases { + *wanted.entry(check).or_default() += 1; + } + assert_eq!( + deltas, wanted, + "each refusal is counted once under its check" + ); +} diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs index 25a5348bc8..456892aee7 100644 --- a/crates/registry-adapter/src/payments/service.rs +++ b/crates/registry-adapter/src/payments/service.rs @@ -25,9 +25,12 @@ use registry_payment_protocol::{ RegistryReceipt, RequestCollection, }; use registry_payment_simulator_connector::{ConnectorError, Observation, SimulatorClient}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_config::SecretResolver; use registry_platform_httputil::client::BearerToken; -use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, ServiceBaseUrl, +}; use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; use tokio::sync::Semaphore; use uuid::Uuid; @@ -236,7 +239,7 @@ impl ProviderPort for SyntheticProvider { .execute(request) .await .map_err(|_| ConnectorError::Unknown)?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| ConnectorError::Unknown)?; let status = response.status().as_u16(); let body = read_bounded(response, 131_072) @@ -488,7 +491,7 @@ impl SyntheticProvider { ConnectorError::Unavailable } })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { if prepared.method == PaymentHttpMethod::Post { ConnectorError::Unknown } else { @@ -623,17 +626,27 @@ impl PaymentService { .await } - fn connection(&self, id: &str, caller: &Caller) -> Result<&PaymentConnection, Error> { - let connection = self - .config - .connections - .iter() - .find(|c| c.id == id) - .ok_or(Error::NotFound)?; - if !connection.allowed_clients.contains(&caller.client_id) - || !caller.scopes.contains(&connection.required_scope) - { - return Err(Error::Forbidden); + fn connection(&self, id: &str, caller: &Caller) -> Result<&PaymentConnection, PaymentFailure> { + let connection = + self.config + .connections + .iter() + .find(|c| c.id == id) + .ok_or(PaymentFailure::refused( + Error::NotFound, + FailedCheck::Visibility, + ))?; + if !connection.allowed_clients.contains(&caller.client_id) { + return Err(PaymentFailure::refused( + Error::Forbidden, + FailedCheck::RequesterClient, + )); + } + if !caller.scopes.contains(&connection.required_scope) { + return Err(PaymentFailure::scope_refused( + &connection.id, + &connection.required_scope, + )); } Ok(connection) } @@ -642,13 +655,16 @@ impl PaymentService { attempt: &Attempt, connection: &PaymentConnection, principal: &str, - ) -> Result<(), Error> { + ) -> Result<(), PaymentFailure> { if attempt.connection != connection.id || attempt.principal != principal || attempt.bill.institution_id != connection.institution_id || attempt.bill.service_id != connection.service_id { - return Err(Error::NotFound); + return Err(PaymentFailure::refused( + Error::NotFound, + FailedCheck::Ownership, + )); } Ok(()) } @@ -659,7 +675,7 @@ impl PaymentService { caller: &Caller, key: &str, request: &RequestCollection, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; request.validate().map_err(|_| Error::InvalidRequest)?; @@ -701,7 +717,7 @@ impl PaymentService { || view.state != BillState::DueUnbound || view.attempt_id.is_some() { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let provider_command = self .provider @@ -761,7 +777,7 @@ impl PaymentService { .read_bill(&attempt.binding, attempt.bill.bill_id) .await?; if !bill.matches_binding(&attempt) || bill.state != BillState::AttemptBound { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let preflight = self .provider @@ -789,7 +805,7 @@ impl PaymentService { .save(&attempt, "provider.unknown") .await .map_err(|_| Error::OutcomeUnknown)?; - return Err(Error::OutcomeUnknown); + return Err(Error::OutcomeUnknown.into()); } }; attempt.transfer_id = Some(submission.transfer_id); @@ -863,7 +879,7 @@ impl PaymentService { caller: &Caller, key: &str, request: &RequestCollection, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; request.validate().map_err(|_| Error::InvalidRequest)?; @@ -873,10 +889,14 @@ impl PaymentService { .lookup_command(id, &principal, "request", key, &digest(request)?) .await? .ok_or(Error::ReceiptUnresolved)?; - let attempt = self.store.get(saved).await?; + let attempt = self + .store + .get(saved) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&attempt, connection, &principal)?; if attempt.transfer_id.is_none() { - return Err(Error::ReceiptUnresolved); + return Err(Error::ReceiptUnresolved.into()); } Ok(attempt.acceptance()) } @@ -886,7 +906,7 @@ impl PaymentService { id: &str, caller: &Caller, collection: Uuid, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; let principal = principal(caller)?; let _permit = self @@ -894,7 +914,11 @@ impl PaymentService { .clone() .try_acquire_owned() .map_err(|_| Error::Unavailable)?; - let initial = self.store.get(collection).await?; + let initial = self + .store + .get(collection) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&initial, connection, &principal)?; let mut lock_client = self .store @@ -938,7 +962,7 @@ impl PaymentService { .as_ref() .is_some_and(|old| observation.observed_at < old.observed_at) { - return Err(Error::ProviderProtocol); + return Err(Error::ProviderProtocol.into()); } attempt.observation = Some(observation); self.store.save(&attempt, "provider.observed").await?; @@ -951,7 +975,7 @@ impl PaymentService { caller: &Caller, key: &str, collection: Uuid, - ) -> Result { + ) -> Result { let connection = self.connection(id, caller)?; validate_key(key)?; let principal = principal(caller)?; @@ -960,7 +984,11 @@ impl PaymentService { .clone() .try_acquire_owned() .map_err(|_| Error::Unavailable)?; - let initial = self.store.get(collection).await?; + let initial = self + .store + .get(collection) + .await + .map_err(PaymentFailure::concealing)?; Self::authorize(&initial, connection, &principal)?; self.store .claim_command( @@ -991,7 +1019,7 @@ impl PaymentService { } let status = attempt.status(); if status.state != CollectionState::Confirmed { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } let reference = status.provider_reference.ok_or(Error::Conflict)?; match &attempt.binding.provider { @@ -1001,15 +1029,15 @@ impl PaymentService { // Released PH-EE Operations `SUCCESS` is only a provider // observation. It cannot satisfy the BReg Action that advances // this bill to `paid` and authorizes service issuance. - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } CollectionProvider::Http { .. } if !status.simulation => { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } CollectionProvider::Simulator { .. } | CollectionProvider::Mifos { .. } | CollectionProvider::Http { .. } => { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } } let receipt = RegistryReceipt { @@ -1038,7 +1066,7 @@ impl PaymentService { return Ok(receipt); } if !view.matches_binding(&attempt) || view.state != BillState::AttemptBound { - return Err(Error::Conflict); + return Err(Error::Conflict.into()); } if attempt.report_action.is_none() { let mut inputs = binding_inputs(&attempt)?; @@ -1065,7 +1093,7 @@ impl PaymentService { self.store.save(&attempt, "receipt.prepared").await?; } if attempt.receipt_digest.as_ref() != Some(&receipt_digest) { - return Err(Error::RecoveryHeld); + return Err(Error::RecoveryHeld.into()); } let result = self .registry @@ -1081,7 +1109,7 @@ impl PaymentService { .await .map_err(|_| Error::OutcomeUnknown)?; if !observed.matches_receipt(&attempt, &receipt, &receipt_digest) { - return Err(result.err().unwrap_or(Error::OutcomeUnknown)); + return Err(result.err().unwrap_or(Error::OutcomeUnknown).into()); } attempt.receipt = Some(receipt.clone()); self.store @@ -1123,6 +1151,65 @@ fn validate_key(key: &str) -> Result<(), Error> { } } +/// A payment error and, when the caller was refused, the check it failed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PaymentFailure { + pub code: Error, + pub check: Option, + /// For a scope refusal, the values the operator declared. Never read from + /// the caller's token. + pub declared: Option, +} + +impl PaymentFailure { + pub(crate) fn refused(code: Error, check: FailedCheck) -> Self { + Self { + code, + check: Some(check), + declared: None, + } + } + + /// A caller that lacks the scope the connection requires. The recording + /// layer names the connection and its declared scope on the log line. + pub(crate) fn scope_refused(connection_id: &str, required_scope: &str) -> Self { + Self { + declared: Some( + DeclaredScope::new(crate::facade::SCOPE_CLAIM) + .with_required_scope(required_scope) + .with_access_profile(connection_id), + ), + ..Self::refused(Error::Forbidden, FailedCheck::Scope) + } + } + + /// A lookup that found nothing is a refusal for the check that conceals + /// existence; any other error carries no check. + pub(crate) fn concealing(code: Error) -> Self { + if code == Error::NotFound { + Self::refused(code, FailedCheck::Visibility) + } else { + code.into() + } + } +} + +impl From for PaymentFailure { + fn from(code: Error) -> Self { + Self { + code, + check: None, + declared: None, + } + } +} + +impl PartialEq for PaymentFailure { + fn eq(&self, other: &Error) -> bool { + self.code == *other + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-adapter/src/payments/store.rs b/crates/registry-adapter/src/payments/store.rs index 3201d38097..528213345f 100644 --- a/crates/registry-adapter/src/payments/store.rs +++ b/crates/registry-adapter/src/payments/store.rs @@ -58,6 +58,18 @@ pub struct PaymentStore { pub(crate) deployment: String, } +/// The table privileges a runtime role needs for the collection tables. +/// Startup checks them, and `adapter serve` grants those a split runtime role +/// lacks. +pub const RUNTIME_GRANTS: [(&str, &[&str]); 3] = [ + ("adapter_payment_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_payment_commands", &["SELECT", "INSERT"]), + ("adapter_payment_events", &["SELECT", "INSERT"]), +]; +/// The sequence the events table draws its identifiers from. A runtime role +/// needs USAGE on it. +pub const RUNTIME_SEQUENCE: &str = "adapter_payment_events_sequence_seq"; + impl PaymentStore { pub fn new(pool: Pool, deployment: String) -> Self { Self { pool, deployment } @@ -77,14 +89,7 @@ impl PaymentStore { pub async fn check_privileges(&self) -> Result<(), Error> { let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; - for (table, privileges) in [ - ( - "adapter_payment_attempts", - &["SELECT", "INSERT", "UPDATE"][..], - ), - ("adapter_payment_commands", &["SELECT", "INSERT"][..]), - ("adapter_payment_events", &["SELECT", "INSERT"][..]), - ] { + for (table, privileges) in RUNTIME_GRANTS { if !crate::journal::missing_table_privileges(&client, table, privileges) .await .map_err(|_| Error::Unavailable)? @@ -96,7 +101,7 @@ impl PaymentStore { let row = client .query_one( "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", - &[&"adapter_payment_events_sequence_seq"], + &[&RUNTIME_SEQUENCE], ) .await .map_err(|_| Error::Unavailable)?; diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 77f693e66b..76733a9606 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -12,14 +12,14 @@ use std::time::{Duration, SystemTime}; use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; use registry_adapter_core::AdapterRuntimeConfig; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, FailedCheck}; use registry_platform_config::{ DatabaseConfig, JwksSource, SecretReference as ConfigSecretReference, SecretResolver, }; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - AuthenticationStage, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, - OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use registry_platform_yaml::SecretReference; use thiserror::Error; @@ -76,12 +76,23 @@ pub struct Caller { /// Why a request has no caller. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CallerRefusal { - /// The credential is absent or was refused. - Unauthenticated, + /// The credential is absent or was refused, at the named check. + Unauthenticated(FailedCheck), /// The verifier could not reach a verdict (issuer or key set outage). Unavailable, } +impl CallerRefusal { + /// The check the request failed, for the operator-side counter and log. + #[must_use] + pub const fn failed_check(self) -> FailedCheck { + match self { + Self::Unauthenticated(check) => check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + /// The longest subject the journal's caller reference column holds. const MAXIMUM_SUBJECT_BYTES: usize = 256; @@ -90,32 +101,11 @@ pub struct Authenticator { } impl Authenticator { - /// Log the refusal of a request whose `Authorization` header is absent, - /// not text, or not a bearer credential, so every 401 leaves the same - /// value-free, rate-limited trace as a refused token. - pub fn log_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Header, - "Adapter authentication refused" - ); - } - pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Header, - "Adapter authentication refused" - ); - CallerRefusal::Unauthenticated - })?; + validate_compact_access_token(token) + .map_err(|_| CallerRefusal::Unauthenticated(FailedCheck::CredentialMalformed))?; let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Adapter authentication refused" - ); + let check = error.failed_check(); match error { OidcError::Transport(_) | OidcError::BoundedRead(_) @@ -127,19 +117,16 @@ impl Authenticator { | OidcError::EmptyKeySet | OidcError::MissingIssuer | OidcError::ConflictingEndpointConfiguration => CallerRefusal::Unavailable, - _ => CallerRefusal::Unauthenticated, + _ => CallerRefusal::Unauthenticated(check), } })?; // An exchanged token names the authority whose assertion produced // it. This runtime declares no assertion authority, so it admits // no exchanged token. if verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Client, - "Adapter authentication refused: an exchanged credential arrived at a deployment that declares no assertion authority" - ); - return Err(CallerRefusal::Unauthenticated); + return Err(CallerRefusal::Unauthenticated( + FailedCheck::TokenAssertionIssuer, + )); } let issuer = verified .claims @@ -150,14 +137,7 @@ impl Authenticator { && issuer.len() <= MAX_CALLER_ISSUER_BYTES && !issuer.contains('\0') }) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Profile, - "Adapter authentication refused: the issuer is absent or unusable for caller isolation" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClaims))?; let client_id = verified .matched_client_id() .ok() @@ -168,14 +148,7 @@ impl Authenticator { && !client.contains('\0') }) .map(str::to_owned) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Client, - "Adapter authentication refused: the admitted client identity is unavailable" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClient))?; let reference = verified .claims .sub @@ -185,14 +158,7 @@ impl Authenticator { && subject.len() <= MAXIMUM_SUBJECT_BYTES && !subject.contains('\0') }) - .ok_or_else(|| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - AuthenticationStage::Profile, - "Adapter authentication refused: the subject is absent or unusable as a caller reference" - ); - CallerRefusal::Unauthenticated - })?; + .ok_or(CallerRefusal::Unauthenticated(FailedCheck::TokenClaims))?; Ok(Caller { reference, issuer, @@ -239,12 +205,20 @@ pub(crate) async fn authenticator( JwksFetcherConfig::defaults(), network.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolver .resolve(document_ref) .map_err(|_| invalid("the static key document could not be resolved"))?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| invalid("the static key document was refused"))?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The document is the operator's own file, so its text names the + // rule it breaks and never a key value. + OidcError::StaticKeySet(refused) => invalid(&format!( + "the static key document is not a usable key set: {refused}" + )), + _ => invalid("the static key document was refused"), + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -672,6 +646,357 @@ pub async fn run_configured( } } +/// The table privileges the runtime role needs for a deployment, by table: +/// the journal and the migration ledger always, idempotency state when it +/// serves a write, the artifact fence when it declares an asynchronous or +/// resumable write, and the checkpoint bindings when it declares a resumable +/// write. Startup grants those the runtime role lacks and then checks them all. +fn runtime_requirements( + serves_write: bool, + declares_recovery: bool, + declares_resume: bool, +) -> Vec<(&'static str, &'static [&'static str])> { + let mut required: Vec<(&'static str, &'static [&'static str])> = vec![ + ("adapter_journal_events", &journal::RUNTIME_PRIVILEGES), + ("adapter_schema_migrations", &["SELECT"]), + ]; + if serves_write { + required.extend(idempotent::WRITE_RUNTIME_GRANTS); + } + if declares_recovery { + required.push(idempotent::RECOVERY_RUNTIME_GRANTS); + } + if declares_resume { + required.push(idempotent::RESUME_RUNTIME_GRANTS); + } + required +} + +/// Everything a runtime role must hold for a deployment: table privileges, by +/// table, and USAGE on sequences. Startup grants what the role lacks, then +/// checks it. +pub(crate) struct Requirements { + pub(crate) tables: Vec<(&'static str, &'static [&'static str])>, + pub(crate) sequences: Vec<&'static str>, +} + +impl Requirements { + /// What the payment host requires: the collection tables always, and the + /// G2P tables when a disbursement connection is declared. + pub(crate) fn payments(disbursements: bool) -> Self { + let mut required = Self { + tables: crate::payments::store::RUNTIME_GRANTS.to_vec(), + sequences: vec![crate::payments::store::RUNTIME_SEQUENCE], + }; + if disbursements { + required + .tables + .extend(crate::payments::g2p_store::RUNTIME_GRANTS); + required + .sequences + .push(crate::payments::g2p_store::RUNTIME_SEQUENCE); + } + required + } + + pub(crate) fn extend(&mut self, other: Self) { + self.tables.extend(other.tables); + self.sequences.extend(other.sequences); + } +} + +/// The advisory-lock key the grant step holds for its transaction, so +/// replicas starting together do not rewrite the same catalog rows at once. +/// Its ASCII bytes spell `adap_gnt`. +const GRANT_LOCK_KEY: i64 = 0x6164_6170_5f67_6e74; + +/// A PostgreSQL identifier, quoted. +fn quote_identifier(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +/// The server's own message for a failed statement, without its position or +/// the statement text. +fn database_message(error: &tokio_postgres::Error) -> String { + error + .as_db_error() + .map_or_else(|| error.to_string(), |db| db.message().to_owned()) +} + +fn grant_error(error: &tokio_postgres::Error) -> ServeError { + ServeError::Configuration(format!("database grants: {}", database_message(error))) +} + +/// The `privileges` that `grantee` lacks on `relation` (an already-quoted, +/// schema-qualified name), in the given order; all of them when the relation +/// does not exist. +async fn missing_for( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + relation: &str, + privileges: &[&'static str], +) -> Result, tokio_postgres::Error> { + let names = privileges.to_vec(); + let held = transaction + .query( + "SELECT coalesce(has_table_privilege($1, to_regclass($2), privilege), false) \ + FROM unnest($3::text[]) WITH ORDINALITY AS wanted(privilege, position) \ + ORDER BY position", + &[&grantee, &relation, &names], + ) + .await?; + Ok(privileges + .iter() + .zip(held.iter()) + .filter(|(_, row)| !row.get::<_, bool>(0)) + .map(|(privilege, _)| *privilege) + .collect()) +} + +/// Whether `grantee` lacks USAGE on `relation`, a sequence given as an +/// already-quoted, schema-qualified name; true when it does not exist. +async fn lacks_sequence_usage( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + relation: &str, +) -> Result { + let held: bool = transaction + .query_one( + "SELECT coalesce(has_sequence_privilege($1, to_regclass($2), 'USAGE'), false)", + &[&grantee, &relation], + ) + .await? + .get(0); + Ok(!held) +} + +/// Everything `grantee` still lacks of `required` and of `USAGE` on `schema`, +/// as "PRIVILEGES on object" phrases. +async fn lacking( + transaction: &tokio_postgres::Transaction<'_>, + grantee: &str, + schema: &str, + required: &Requirements, +) -> Result, tokio_postgres::Error> { + let mut lacking = Vec::new(); + for (table, privileges) in &required.tables { + let missing = missing_for( + transaction, + grantee, + &format!("{schema}.{table}"), + privileges, + ) + .await?; + if !missing.is_empty() { + lacking.push(format!("{} on {table}", missing.join(", "))); + } + } + for sequence in &required.sequences { + if lacks_sequence_usage(transaction, grantee, &format!("{schema}.{sequence}")).await? { + lacking.push(format!("USAGE on sequence {sequence}")); + } + } + let usage: bool = transaction + .query_one( + "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", + &[&grantee], + ) + .await? + .get(0); + if !usage { + lacking.push(format!("USAGE on schema {schema}")); + } + Ok(lacking) +} + +/// Grant `grantee`, the runtime session's own role, each privilege in +/// `required` it lacks and `USAGE` on the schema the migrations ran in, from +/// the migration session in one transaction under an advisory lock. A start +/// that finds everything in place issues no GRANT. Nothing beyond `required` +/// is granted: no default privileges, no grant on the idempotency migration +/// ledger. +/// +/// When something is missing and the role has members, no grant is made, +/// because they would inherit it: the privilege check that follows then +/// decides, as it does for a hand-granted deployment. A member that holds +/// ADMIN OPTION on the role and has no members of its own does not count. It +/// already controls the role, as the role that created it does in the layout +/// the shared provisioning plan builds. PostgreSQL ignores or refuses a GRANT the +/// migration role has no right to make, so each privilege is checked again +/// before the commit, and a shortfall rolls everything back. +/// +/// Returns whether `grantee` ends holding everything `required` names: false +/// when the members rule made no grant. +async fn grant_runtime_privileges( + client: &mut deadpool_postgres::Client, + grantee: &str, + required: &Requirements, +) -> Result { + let transaction = client.transaction().await.map_err(|e| grant_error(&e))?; + transaction + .query_one("SELECT pg_advisory_xact_lock($1)", &[&GRANT_LOCK_KEY]) + .await + .map_err(|e| grant_error(&e))?; + let schema: Option = transaction + .query_one("SELECT quote_ident(current_schema())", &[]) + .await + .map_err(|e| grant_error(&e))? + .get(0); + let schema = schema.ok_or_else(|| { + ServeError::Configuration( + "database: the migration role's search path names no schema to grant USAGE on" + .to_owned(), + ) + })?; + let missing = lacking(&transaction, grantee, &schema, required) + .await + .map_err(|e| grant_error(&e))?; + if missing.is_empty() { + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Ok(true); + } + let has_members: bool = transaction + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_auth_members m \ + JOIN pg_roles r ON r.oid = m.roleid \ + WHERE r.rolname = $1 \ + AND m.member NOT IN (SELECT a.member FROM pg_auth_members a \ + WHERE a.roleid = r.oid AND a.admin_option \ + AND NOT EXISTS (SELECT 1 FROM pg_auth_members g \ + WHERE g.roleid = a.member)))", + &[&grantee], + ) + .await + .map_err(|e| grant_error(&e))? + .get(0); + if has_members { + tracing::warn!( + role = grantee, + "the runtime role has members, so no privilege is granted to it automatically" + ); + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Ok(false); + } + let mut granted = 0_usize; + let quoted_grantee = quote_identifier(grantee); + for (table, privileges) in &required.tables { + let missing = missing_for( + &transaction, + grantee, + &format!("{schema}.{table}"), + privileges, + ) + .await + .map_err(|e| grant_error(&e))?; + if missing.is_empty() { + continue; + } + granted += missing.len(); + let missing = missing.join(", "); + transaction + .batch_execute(&format!( + "GRANT {missing} ON TABLE {schema}.{table} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant {missing} on {table} to the runtime role: {}", + database_message(&error) + )) + })?; + } + for sequence in &required.sequences { + if !lacks_sequence_usage(&transaction, grantee, &format!("{schema}.{sequence}")) + .await + .map_err(|e| grant_error(&e))? + { + continue; + } + granted += 1; + transaction + .batch_execute(&format!( + "GRANT USAGE ON SEQUENCE {schema}.{sequence} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant USAGE on sequence {sequence} to the runtime role: {}", + database_message(&error) + )) + })?; + } + let usage: bool = transaction + .query_one( + "SELECT has_schema_privilege($1, current_schema(), 'USAGE')", + &[&grantee], + ) + .await + .map_err(|e| grant_error(&e))? + .get(0); + if !usage { + granted += 1; + transaction + .batch_execute(&format!( + "GRANT USAGE ON SCHEMA {schema} TO {quoted_grantee}" + )) + .await + .map_err(|error| { + ServeError::Configuration(format!( + "database: could not grant USAGE on schema {schema} to the runtime role: {}", + database_message(&error) + )) + })?; + } + let still_lacking = lacking(&transaction, grantee, &schema, required) + .await + .map_err(|e| grant_error(&e))?; + if !still_lacking.is_empty() { + transaction.rollback().await.map_err(|e| grant_error(&e))?; + return Err(ServeError::Configuration(format!( + "database: after its grants the runtime role still lacks {}; PostgreSQL ignores or refuses a grant the migration role has no right to make, most likely because the migration role does not own the object, so the grants were rolled back (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role says what to grant by hand)", + still_lacking.join("; lacks ") + ))); + } + transaction.commit().await.map_err(|e| grant_error(&e))?; + tracing::info!( + role = grantee, + privileges = granted, + "granted the runtime role the privileges it lacked" + ); + Ok(true) +} + +/// Grant the runtime session's role what `required` names, from `migration`, +/// when the two sessions are different roles. The grantee is the role the +/// runtime session proves it holds, read before any grant: a runtime URL +/// naming `public`, a role that cannot log in or a wrong password fails here, +/// and the URL's text never chooses who receives privileges. One role on both +/// sessions issues no grant and returns false, as `grant_runtime_privileges` +/// does when its members rule made none. +pub(crate) async fn grant_when_split( + migration: &mut deadpool_postgres::Client, + runtime: &Pool, + required: &Requirements, +) -> Result { + let runtime_role: String = runtime + .get() + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))? + .get(0); + let migration_role: String = migration + .query_one("SELECT current_user::text", &[]) + .await + .map_err(|error| ServeError::Configuration(format!("database: {error}")))? + .get(0); + if runtime_role == migration_role { + return Ok(false); + } + grant_runtime_privileges(migration, &runtime_role, required).await +} + async fn run_facade( project_directory: &std::path::Path, profile_path: Option<&std::path::Path>, @@ -738,8 +1063,55 @@ async fn run_facade( .to_owned(), )); } + let declares_recovery = loaded + .served + .iter() + .any(|served| served.async_completion.is_some() || served.resume.is_some()); + let declares_resume = loaded.served.iter().any(|served| served.resume.is_some()); + // A configuration this refuses grants nothing: it settles before any + // database work. + let response_retention_seconds = if serves_write { + let retention = loaded.runtime.idempotency.ok_or_else(|| { + ServeError::Configuration( + "idempotency.responseRetentionSeconds is required when a write is served" + .to_owned(), + ) + })?; + let seconds = retention.response_retention_seconds.get(); + if loaded.served.iter().any(|served| { + served + .write_support + .as_ref() + .is_some_and(|support| source_replay_window_seconds(support) < seconds) + }) { + return Err(ServeError::Configuration( + "a source write replay window is shorter than idempotency.responseRetentionSeconds; increase the source replayWindowSeconds or reduce response retention" + .to_owned(), + )); + } + Some(seconds) + } else { + None + }; + // The payment configuration, packs and credentials settle before any + // database work, so a refusal grants nothing. + let payments = match payments_path { + Some(path) => Some( + crate::payments::http::PreparedPayments::prepare( + &loaded.runtime, + path, + payment_provider_pack, + ) + .await?, + ), + None => None, + }; let shutdown = shutdown_signal()?; let migration = pool(&loaded.runtime.database, &loaded.resolver, true)?; + let journal = pool(&loaded.runtime.database, &loaded.resolver, false)?; + // Whether the grant step found the runtime role holding everything the + // deployment requires in the schema the migrations ran in. + let grants_verified; { let mut client = migration .get() @@ -751,13 +1123,18 @@ async fn run_facade( idempotent::migrate(&mut client).await.map_err(|error| { ServeError::Configuration(format!("idempotency migration: {error}")) })?; + if payments.is_some() { + crate::payments::http::PreparedPayments::migrate(&mut client).await?; + } + let mut required = Requirements { + tables: runtime_requirements(serves_write, declares_recovery, declares_resume), + sequences: Vec::new(), + }; + if let Some(payments) = &payments { + required.extend(payments.requirements()); + } + grants_verified = grant_when_split(&mut client, &journal, &required).await?; } - let journal = pool(&loaded.runtime.database, &loaded.resolver, false)?; - let declares_recovery = loaded - .served - .iter() - .any(|served| served.async_completion.is_some() || served.resume.is_some()); - let declares_resume = loaded.served.iter().any(|served| served.resume.is_some()); { // A runtime role that lacks a grant this deployment uses is refused // here, not at its first journal write, write claim or retention tick. @@ -765,19 +1142,7 @@ async fn run_facade( .get() .await .map_err(|error| ServeError::Configuration(format!("database runtime: {error}")))?; - let mut required: Vec<(&str, &[&'static str])> = vec![ - ("adapter_journal_events", &journal::RUNTIME_PRIVILEGES), - ("adapter_schema_migrations", &["SELECT"]), - ]; - if serves_write { - required.extend(idempotent::WRITE_RUNTIME_GRANTS); - } - if declares_recovery { - required.push(idempotent::RECOVERY_RUNTIME_GRANTS); - } - if declares_resume { - required.push(idempotent::RESUME_RUNTIME_GRANTS); - } + let required = runtime_requirements(serves_write, declares_recovery, declares_resume); let mut lacking = Vec::new(); for (table, privileges) in required { let missing = journal::missing_table_privileges(&client, table, privileges) @@ -790,44 +1155,26 @@ async fn run_facade( } } if !lacking.is_empty() { + let remedy = if grants_verified { + "the role holds them in the schema the migrations ran in, so the runtime session's search path most likely resolves a different schema; point the runtime database URL's search path at the migration schema" + } else { + "grant them to the runtime role" + }; return Err(ServeError::Configuration(format!( - "database: the runtime role lacks {}; grant them to the runtime role (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role lists every grant)", + "database: the runtime role lacks {}; {remedy} (https://docs.registrystack.org/operate/adapter/#grant-the-runtime-database-role lists every grant)", lacking.join("; lacks "), ))); } } let journal_window = journal_retention(loaded.runtime.audit.retention_days.get()); let journal_sweep_pool = journal.clone(); - let idempotency = match (serves_write, loaded.runtime.idempotency) { - (true, Some(retention)) => { - let response_retention_seconds = retention.response_retention_seconds.get(); - if loaded.served.iter().any(|served| { - served.write_support.as_ref().is_some_and(|support| { - source_replay_window_seconds(support) < response_retention_seconds - }) - }) { - return Err(ServeError::Configuration( - "a source write replay window is shorter than idempotency.responseRetentionSeconds; increase the source replayWindowSeconds or reduce response retention" - .to_owned(), - )); - } - Some(( - PostgresIdempotencyStore::new( - journal.clone(), - Duration::from_secs(response_retention_seconds), - ) - .map_err(|error| ServeError::Configuration(format!("idempotency: {error}")))?, - Duration::from_secs(response_retention_seconds), - )) - } - (true, None) => { - return Err(ServeError::Configuration( - "idempotency.responseRetentionSeconds is required when a write is served" - .to_owned(), - )); - } - (false, _) => None, - }; + let idempotency = response_retention_seconds + .map(|seconds| { + PostgresIdempotencyStore::new(journal.clone(), Duration::from_secs(seconds)) + .map(|store| (store, Duration::from_secs(seconds))) + .map_err(|error| ServeError::Configuration(format!("idempotency: {error}"))) + }) + .transpose()?; let artifact_digest = loaded_artifact_digest(&loaded.deployment)?; // Only a deployment that declares an asynchronous or resumable write // touches the durable artifact fence. Activation advances it and is @@ -851,16 +1198,8 @@ async fn run_facade( let async_recovery = async_recovery_admission(&loaded)?; let async_retention = idempotency.as_ref().map(|(_, retention)| *retention); let facade_idempotency = idempotency.as_ref().map(|(store, _)| store.clone()); - let payments_router = match payments_path { - Some(path) => Some( - crate::payments::http::load_router( - &loaded.runtime, - path, - payment_provider_pack, - journal.clone(), - ) - .await?, - ), + let payments_router = match payments { + Some(payments) => Some(payments.into_router(journal.clone()).await?), None => None, }; let address: SocketAddr = loaded.runtime.listener.bind.0; @@ -998,10 +1337,152 @@ fn tolerate_metrics_shutdown_timeout(result: std::io::Result<()>) -> std::io::Re } } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] mod tests { use super::*; + fn static_key_runtime() -> AdapterRuntimeConfig { + serde_json::from_value(serde_json::json!({ + "id": "static-key-set", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": "https://issuer.example.test", + "audience": "registry-adapter-test", + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-keys.json"} + }, + "allowedClients": ["coordinator"], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") + } + + async fn authenticator_over(keys: &serde_json::Value) -> Result { + use std::os::unix::fs::PermissionsExt; + let directory = tempfile::tempdir().expect("a scratch directory"); + let root = directory.path().canonicalize().expect("physical directory"); + let file = root.join("issuer-keys.json"); + std::fs::write(&file, keys.to_string()).expect("write the key set"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + let resolver = SecretResolver::new([registry_platform_config::SecretProvider::File], root) + .expect("resolver"); + authenticator(&static_key_runtime(), &resolver).await + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_the_rule_text() { + let private = + registry_platform_testing::access_token_test_key(jsonwebtoken::Algorithm::ES256); + let mut keys = registry_platform_testing::jwks_from_private_jwk(&private); + keys["keys"][0]["d"] = serde_json::json!("AQAB"); + let Err(ServeError::Configuration(text)) = authenticator_over(&keys).await else { + panic!("a key set holding a private member is refused"); + }; + assert!( + text.contains("not a usable key set"), + "the refusal names the key set: {text}" + ); + assert!( + text.len() > "oidc: the static key document is not a usable key set: ".len(), + "the rule text follows: {text}" + ); + assert!(!text.contains("AQAB"), "no key value in the text: {text}"); + } + + #[tokio::test] + async fn a_static_key_set_with_a_public_ext_member_loads() { + let private = + registry_platform_testing::access_token_test_key(jsonwebtoken::Algorithm::ES256); + let mut keys = registry_platform_testing::jwks_from_private_jwk(&private); + keys["keys"][0]["ext"] = serde_json::json!(true); + authenticator_over(&keys) + .await + .map(|_| ()) + .expect("a public key set with ext loads"); + } + + #[test] + fn runtime_requirements_follow_the_deployment_feature_set() { + const JOURNAL: (&str, &[&str]) = + ("adapter_journal_events", &["INSERT", "SELECT", "DELETE"]); + const LEDGER: (&str, &[&str]) = ("adapter_schema_migrations", &["SELECT"]); + const ENTRIES: (&str, &[&str]) = ( + "adapter_idempotency_entries", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ); + const RESUMES: (&str, &[&str]) = ( + "adapter_idempotency_resumes", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ); + const ARTIFACTS: (&str, &[&str]) = ( + "adapter_idempotency_async_artifacts", + &["SELECT", "INSERT", "UPDATE"], + ); + const BINDINGS: (&str, &[&str]) = + ("adapter_idempotency_resume_bindings", &["SELECT", "INSERT"]); + assert_eq!(runtime_requirements(false, false, false), [JOURNAL, LEDGER]); + assert_eq!( + runtime_requirements(true, false, false), + [JOURNAL, LEDGER, ENTRIES, RESUMES] + ); + assert_eq!( + runtime_requirements(true, true, false), + [JOURNAL, LEDGER, ENTRIES, RESUMES, ARTIFACTS] + ); + assert_eq!( + runtime_requirements(true, true, true), + [JOURNAL, LEDGER, ENTRIES, RESUMES, ARTIFACTS, BINDINGS] + ); + assert!(runtime_requirements(true, true, true) + .iter() + .all(|(table, _)| *table != "adapter_idempotency_schema_migrations")); + } + + #[test] + fn payment_requirements_follow_what_the_payment_host_checks() { + let collections = Requirements::payments(false); + assert_eq!( + collections.tables, + crate::payments::store::RUNTIME_GRANTS.to_vec() + ); + assert_eq!( + collections.sequences, + ["adapter_payment_events_sequence_seq"] + ); + let both = Requirements::payments(true); + assert_eq!(both.tables.len(), 6); + assert!(both + .tables + .iter() + .any(|(table, privileges)| *table == "adapter_g2p_attempts" + && *privileges == ["SELECT", "INSERT", "UPDATE"])); + assert_eq!( + both.sequences, + [ + "adapter_payment_events_sequence_seq", + "adapter_g2p_events_sequence_seq" + ] + ); + } + + #[test] + fn a_role_name_is_quoted_as_one_identifier() { + assert_eq!(quote_identifier("runtime"), "\"runtime\""); + assert_eq!( + quote_identifier("a\"; DROP ROLE x; --"), + "\"a\"\"; DROP ROLE x; --\"" + ); + } + #[test] fn a_metrics_shutdown_timeout_is_not_fatal_but_other_faults_are() { let timed_out = std::io::Error::new(std::io::ErrorKind::TimedOut, "stalled client"); diff --git a/crates/registry-adapter/src/serve/token_characterisation.rs b/crates/registry-adapter/src/serve/token_characterisation.rs new file mode 100644 index 0000000000..9321899e32 --- /dev/null +++ b/crates/registry-adapter/src/serve/token_characterisation.rs @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Characterises which identity-provider tokens the facade's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds the authenticator the server builds, through +//! `serve::authenticator`, over a static key set holding the corpus signer's +//! public keys, and presents the fixture to `Authenticator::authenticate`. The +//! payment host builds its authenticator through the same function and +//! authenticates a bearer through the same method. The module sits under +//! `serve` so it can also ask the authenticator's own verifier for the check +//! that refused a token and compare it with the check `CallerRefusal` carries. +use super::*; +use registry_platform_config::SecretProvider; +use registry_platform_testing::{ + ClaimValue, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "registry-adapter-test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn runtime_for(case: &FixtureCase) -> AdapterRuntimeConfig { + let client = client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into()); + serde_json::from_value(json!({ + "id": "token-characterisation", + "endpoints": [{"endpoint": "tracker", "baseUrl": "https://tracker.example.invalid"}], + "listener": {"bind": "127.0.0.1:8080"}, + "database": { + "runtimeUrlRef": "secret:file/database-runtime", + "migrationUrlRef": "secret:file/database-migration" + }, + "oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": format!("secret:file/{KEY_FILE}")} + }, + "allowedClients": [client], + "allowedPrivateCidrs": ["10.0.0.0/8"], + "audit": {"retentionDays": 90} + })) + .expect("the runtime configuration parses") +} + +async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { + let verdict = authenticator.verifier.verify(token).await; + let admission = authenticator.authenticate(token).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(refusal), Err(error)) => { + assert_eq!( + refusal.failed_check(), + error.failed_check(), + "the refusal carries the check the verifier named" + ); + Outcome::refused_by(&error) + } + (Err(CallerRefusal::Unauthenticated(_)), Ok(_)) => { + "refused/claims".parse().expect("result value") + } + (Err(CallerRefusal::Unavailable), Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("key directory"); + let root_path = root.path().canonicalize().expect("physical key directory"); + let key_file = root_path.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let resolver = SecretResolver::new([SecretProvider::File], root_path).expect("resolver"); + let resolver = &resolver; + let report = corpus + .run_product_async("adapter", &signer, ISSUER, AUDIENCE, |case| async move { + let runtime = runtime_for(&case); + let authenticator = authenticator(&runtime, resolver) + .await + .expect("the authenticator builds over the static key set"); + observe(&authenticator, case.token.expose()).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-adapter/tests/effective_contract_live.rs b/crates/registry-adapter/tests/effective_contract_live.rs index 73be8e7378..62deebdd01 100644 --- a/crates/registry-adapter/tests/effective_contract_live.rs +++ b/crates/registry-adapter/tests/effective_contract_live.rs @@ -366,7 +366,7 @@ async fn authentication_and_admission_precede_the_pin_which_precedes_body_and_so } #[tokio::test] -async fn a_valid_concrete_collision_is_unserved_before_router_construction() { +async fn a_concrete_collision_with_a_reserved_route_refuses_to_start() { let upstream = UpstreamDouble::start(); let directory = tempfile::tempdir().expect("a copied Adapter project"); copy_example_project(directory.path()); @@ -386,32 +386,25 @@ async fn a_valid_concrete_collision_is_unserved_before_router_construction() { &project_path, project.replace("person", "effective-contract"), ) - .expect("write the valid concrete-collision project"); + .expect("write the concrete-collision project"); - let served = Served::start_with_project(&upstream.url(""), directory.path()).await; - let token = served.token(""); - let readback = served.get(WELL_KNOWN_PATH, Some(&token)); - assert_eq!(readback.0, 200, "{}", readback.2); - let unserved = readback.2["contract"]["unserved"] - .as_array() - .expect("the contract carries unserved operations"); - for binding in ["effective-contract-search", "effective-contract-create"] { - let colliding = unserved - .iter() - .find(|entry| entry["bindingId"] == binding) - .unwrap_or_else(|| panic!("the {binding} collision is explicitly unserved")); - assert_eq!( - colliding["reasonCode"], - "adapter.operation.reserved-facade-path" - ); - assert_eq!( - colliding["reason"], - "the facade path is reserved for the Adapter effective-contract route" - ); - } + // The workspace check refuses both colliding bindings before the facade + // builds a router, so the reserved route is never shadowed. + let stderr = Served::refusal_with_project(&upstream.url(""), directory.path()).await; + assert!( + stderr.contains("the workspace check refused the deployment"), + "{stderr}" + ); + assert_eq!( + stderr + .matches("adapter.project.reserved-facade-path") + .count(), + 2, + "{stderr}" + ); assert_eq!( upstream.request_count(), 0, - "the built-in protected route wins without source I/O" + "a refused deployment performs no source I/O" ); } diff --git a/crates/registry-adapter/tests/facade_refusals.rs b/crates/registry-adapter/tests/facade_refusals.rs new file mode 100644 index 0000000000..018f56b317 --- /dev/null +++ b/crates/registry-adapter/tests/facade_refusals.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every refusal of a facade caller, end to end through the built `adapter` +//! binary over a real journal: the answer is frozen against a checked-in +//! golden file (status, `content-type`, `www-authenticate`, `retry-after`, +//! `cache-control` and the body with its correlation identifier removed), the +//! refusal counter on the operator-private metrics listener rises by one under +//! the check that refused, and the log carries one value-free line naming that +//! check. +//! +//! `ADAPTER_WRITE_GOLDEN=1` rewrites the golden file from the running binary. +//! Without it the answers are compared to the file. Needs +//! `ADAPTER_TEST_DATABASE_URL`; without it every test fails on the spot. +#![cfg(feature = "postgres-test")] + +#[allow(dead_code)] +#[path = "support/served/mod.rs"] +mod served_harness; + +use std::collections::BTreeMap; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::time::Duration; + +use serde_json::{json, Value}; +use served_harness::upstream::{Response, UpstreamDouble}; +use served_harness::{capture, copy_govstack_project, fixture, Served, STDERR_WAIT}; + +const GET_PATH: &str = "/govstack/registries/v1/collections/people/records/EeBJ3Sn9uLg"; +const LIST_PATH: &str = "/govstack/registries/v1/collections/people/records"; +const LOOKUP_PATH: &str = "/govstack/registries/v1/collections/people/lookup"; +const COUNTER: &str = "adapter_request_refusals_total"; +const GOLDEN: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/golden/facade_refusals.json" +); + +/// A second access profile for the copied project: a caller holding +/// `records.write` is admitted to retrieve and to nothing else. +const WRITER_PROFILE: &str = " - id: records-writer\n scopes: [records.write]\n operations: [retrieve]\n recordTypes: [people]\n"; + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .expect("bind a probe port") + .local_addr() + .expect("the probe port") + .port() +} + +fn scrape(port: u16) -> String { + let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect the metrics port"); + stream + .write_all(b"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .expect("write"); + let mut raw = String::new(); + stream.read_to_string(&mut raw).expect("read"); + raw.split_once("\r\n\r\n") + .expect("a header block") + .1 + .to_owned() +} + +/// The refusal counter as `check -> count`. +fn refusals(port: u16) -> BTreeMap { + scrape(port) + .lines() + .filter_map(|line| { + let rest = line.strip_prefix(COUNTER)?.strip_prefix("{check=\"")?; + let (check, count) = rest.split_once("\"} ")?; + Some((check.to_owned(), count.parse().expect("a counter value"))) + }) + .collect() +} + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().skip(1).find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +/// The answer as the golden file holds it. The correlation identifiers differ +/// per request, so they are replaced by a marker. +fn frozen(status: u16, head: &str, body: &Value) -> Value { + let mut body = body.clone(); + if let Some(object) = body.as_object_mut() { + for member in ["traceId", "requestId"] { + if object.contains_key(member) { + object.insert(member.to_owned(), json!("")); + } + } + } + json!({ + "status": status, + "content-type": header(head, "content-type"), + "www-authenticate": header(head, "www-authenticate"), + "retry-after": header(head, "retry-after"), + "cache-control": header(head, "cache-control"), + "body": body, + }) +} + +/// The `request refused` lines the binary wrote, as their `failed_check` +/// values, in order. +fn refused_lines(stderr: &str) -> Vec { + stderr + .lines() + .filter_map(|line| serde_json::from_str::(line.trim()).ok()) + .filter(|event| event["fields"]["message"] == "request refused") + .map(|event| { + assert_eq!(event["fields"]["decision"], "refused"); + event["fields"]["failed_check"] + .as_str() + .expect("a failed check") + .to_owned() + }) + .collect() +} + +fn page(page: u64) -> Response { + let document = fixture("search-page"); + let mut body = document["entries"][0]["upstream"][0]["response"]["body"].clone(); + body["pager"]["page"] = json!(page); + body["pager"]["pageCount"] = json!(9); + Response::json(200, &body.to_string()) +} + +struct Case { + name: &'static str, + status: u16, + head: String, + body: Value, + check: &'static str, +} + +#[tokio::test] +async fn every_refusal_keeps_its_answer_and_is_counted_and_logged_under_its_check() { + let upstream = UpstreamDouble::start(); + upstream.respond_with(vec![page(1)]); + let directory = tempfile::tempdir().expect("a scratch directory"); + copy_govstack_project(directory.path()); + let project = directory.path().join("project.yaml"); + let mut text = std::fs::read_to_string(&project).expect("the project is readable"); + if !text.ends_with('\n') { + text.push('\n'); + } + text.push_str(WRITER_PROFILE); + std::fs::write(&project, text).expect("write the project"); + let metrics_port = free_port(); + let served = + Served::start_with_metrics(&upstream.url(""), directory.path(), metrics_port).await; + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("the test clock follows the epoch") + .as_secs(); + let reader = served.token("records.read"); + let first = served.get(&format!("{LIST_PATH}?pageSize=5"), Some(&reader)); + assert_eq!(first.0, 200, "{}", first.2); + let cursor = first.2["pageInfo"]["nextCursor"] + .as_str() + .expect("a cursor") + .to_owned(); + let tokens: Vec<(&str, String)> = vec![ + ("wrong-audience", served.token_with("subject", "records.read", json!({"aud": "another-service"}))), + ("expired", served.token_with("subject", "records.read", json!({"exp": now.saturating_sub(3_600)}))), + ("unlisted-client", served.token_with("subject", "records.read", json!({"client_id": "stranger"}))), + ( + "exchanged", + served.token_with( + "subject", + "records.read", + json!({registry_platform_oidc::ASSERTION_ISSUER_CLAIM: "https://other.example.invalid"}), + ), + ), + ("subject-too-long", served.token_for(&"s".repeat(257), "records.read")), + ("scope-not-held", served.token("other.scope")), + ("operation-not-named", served.token("records.write")), + ( + "cursor-of-another-client", + served.token_with( + served_harness::SUBJECT, + "records.read", + json!({"client_id": served_harness::SECOND_CLIENT}), + ), + ), + ]; + let token = |name: &str| { + tokens + .iter() + .find(|(candidate, _)| *candidate == name) + .map(|(_, value)| value.as_str()) + .expect("a prepared token") + }; + + let mut cases: Vec = Vec::new(); + let mut run = |name: &'static str, check: &'static str, answer: (u16, String, Value)| { + cases.push(Case { + name, + status: answer.0, + head: answer.1, + body: answer.2, + check, + }); + }; + run( + "no-authorization", + "credential-missing", + served.get(GET_PATH, None), + ); + run( + "basic-scheme", + "credential-missing", + served.request( + "GET", + GET_PATH, + None, + &[("Authorization", "Basic YWJjOmRlZg==")], + b"", + ), + ); + run( + "bearer-without-token", + "credential-malformed", + served.request("GET", GET_PATH, None, &[("Authorization", "Bearer")], b""), + ); + run( + "not-a-compact-token", + "credential-malformed", + served.get(GET_PATH, Some("not-a-token")), + ); + run( + "unknown-signer", + "token-signature", + served.get(GET_PATH, Some(&Served::forged_token())), + ); + run( + "wrong-audience", + "token-audience", + served.get(GET_PATH, Some(token("wrong-audience"))), + ); + run( + "expired", + "token-time", + served.get(GET_PATH, Some(token("expired"))), + ); + run( + "unlisted-client", + "token-client", + served.get(GET_PATH, Some(token("unlisted-client"))), + ); + run( + "exchanged", + "token-assertion-issuer", + served.get(GET_PATH, Some(token("exchanged"))), + ); + run( + "subject-too-long", + "token-claims", + served.get(GET_PATH, Some(token("subject-too-long"))), + ); + run( + "scope-not-held", + "scope", + served.get(GET_PATH, Some(token("scope-not-held"))), + ); + run( + "operation-not-named", + "operation", + served.post(LOOKUP_PATH, Some(token("operation-not-named")), &json!({})), + ); + run( + "cursor-of-another-client", + "ownership", + served.get( + &format!("{LIST_PATH}?cursor={cursor}"), + Some(token("cursor-of-another-client")), + ), + ); + + let frozen_answers: Value = Value::Object( + cases + .iter() + .map(|case| { + ( + case.name.to_owned(), + frozen(case.status, &case.head, &case.body), + ) + }) + .collect(), + ); + if std::env::var_os("ADAPTER_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(std::path::Path::new(GOLDEN).parent().expect("a directory")) + .expect("create the golden directory"); + std::fs::write( + GOLDEN, + serde_json::to_string_pretty(&frozen_answers).expect("serialize the golden") + "\n", + ) + .expect("write the golden file"); + } + let golden: Value = serde_json::from_str( + &std::fs::read_to_string(GOLDEN).expect("the golden file is checked in"), + ) + .expect("the golden file is JSON"); + assert_eq!(frozen_answers, golden, "a refusal answer changed"); + + let mut expected: BTreeMap = BTreeMap::new(); + for case in &cases { + *expected.entry(case.check.to_owned()).or_default() += 1; + } + let counted = refusals(metrics_port); + for (check, count) in &expected { + assert_eq!( + counted.get(check), + Some(count), + "the counter for {check}: {counted:?}" + ); + } + assert_eq!( + counted.values().sum::(), + expected.values().sum::(), + "no other check was counted: {counted:?}" + ); + assert_eq!(counted.len(), 45, "every check is declared at zero"); + + let stderr = served.wait_for_stderr("\"request refused\"", STDERR_WAIT); + std::thread::sleep(Duration::from_millis(300)); + let stderr = served.stderr_text().max(stderr); + let mut logged = refused_lines(&stderr); + logged.sort(); + let mut wanted: Vec = cases.iter().map(|case| case.check.to_owned()).collect(); + wanted.sort(); + assert_eq!(logged, wanted, "one value-free line per refusal"); + for secret in tokens.iter().map(|(_, value)| value.as_str()).chain([ + reader.as_str(), + "stranger", + cursor.as_str(), + ]) { + assert!(!stderr.contains(secret), "a caller value reached the log"); + } + let _ = capture; +} diff --git a/crates/registry-adapter/tests/golden/facade_refusals.json b/crates/registry-adapter/tests/golden/facade_refusals.json new file mode 100644 index 0000000000..ae92e99830 --- /dev/null +++ b/crates/registry-adapter/tests/golden/facade_refusals.json @@ -0,0 +1,171 @@ +{ + "basic-scheme": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "bearer-without-token": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "cursor-of-another-client": { + "body": { + "status": 400, + "title": "the cursor is not valid", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/invalid-cursor" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 400, + "www-authenticate": null + }, + "exchanged": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "expired": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "no-authorization": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "not-a-compact-token": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "operation-not-named": { + "body": { + "status": 403, + "title": "the caller may not make this request", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "www-authenticate": null + }, + "scope-not-held": { + "body": { + "status": 403, + "title": "the caller may not make this request", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "www-authenticate": null + }, + "subject-too-long": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "unknown-signer": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "unlisted-client": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + }, + "wrong-audience": { + "body": { + "status": 401, + "title": "the request carries no valid credential", + "traceId": "", + "type": "https://govstack.global/problems/digital-registries/unauthorized" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "www-authenticate": "Bearer" + } +} diff --git a/crates/registry-adapter/tests/golden/payment_refusals.json b/crates/registry-adapter/tests/golden/payment_refusals.json new file mode 100644 index 0000000000..6782bbbe73 --- /dev/null +++ b/crates/registry-adapter/tests/golden/payment_refusals.json @@ -0,0 +1,182 @@ +{ + "basic-scheme": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "client-not-allowed": { + "body": { + "code": "adapter.payment.forbidden", + "status": 403, + "title": "adapter.payment.forbidden", + "type": "urn:registry:problem:adapter.payment.forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "expired": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "no-authorization": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "not-a-compact-token": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "scope-not-held": { + "body": { + "code": "adapter.payment.forbidden", + "status": 403, + "title": "adapter.payment.forbidden", + "type": "urn:registry:problem:adapter.payment.forbidden" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 403, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "two-authorization-headers": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-attempt": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-connection": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-disbursement-connection": { + "body": { + "code": "adapter.payment.not-found", + "status": 404, + "title": "adapter.payment.not-found", + "type": "urn:registry:problem:adapter.payment.not-found" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 404, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unknown-signer": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + }, + "unlisted-client": { + "body": { + "code": "adapter.payment.authentication-required", + "status": 401, + "title": "adapter.payment.authentication-required", + "type": "urn:registry:problem:adapter.payment.authentication-required" + }, + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "status": 401, + "traceparent-present": true, + "www-authenticate": null, + "x-content-type-options": "nosniff" + } +} diff --git a/crates/registry-adapter/tests/health_routes.rs b/crates/registry-adapter/tests/health_routes.rs new file mode 100644 index 0000000000..3dc3612411 --- /dev/null +++ b/crates/registry-adapter/tests/health_routes.rs @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Live HTTP proof for the unauthenticated `/health` and `/ready` probes of +//! the facade listener. Every test uses the real Adapter binary and a real +//! PostgreSQL journal. Absence of the database URL fails; it never turns +//! this boundary into a skipped test. +#![cfg(feature = "postgres-test")] + +#[allow(dead_code)] +#[path = "support/served/mod.rs"] +mod served_harness; + +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::time::Duration; + +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; +use served_harness::upstream::UpstreamDouble; +use served_harness::{copy_example_project, replace_profile_text, Served}; + +const NOT_READY_BODY: &str = r#"{"status":"not-ready"}"#; + +/// One raw response: status, header lines (the `date` header, which the HTTP +/// server stamps per response, left out) and the body bytes. +#[derive(Debug, PartialEq, Eq)] +struct Raw { + status: u16, + headers: Vec, + body: Vec, +} + +fn raw(served: &Served, method: &str, path: &str, authorization: Option<&str>) -> Raw { + let mut stream = TcpStream::connect(("127.0.0.1", served.port)).expect("connect"); + stream + .set_read_timeout(Some(Duration::from_secs(30))) + .expect("timeout"); + let mut request = + format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); + if let Some(value) = authorization { + request.push_str(&format!("Authorization: {value}\r\n")); + } + if method != "GET" { + request.push_str("Content-Length: 0\r\n"); + } + request.push_str("\r\n"); + stream.write_all(request.as_bytes()).expect("write"); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).expect("read"); + let split = bytes + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("a header block"); + let head = String::from_utf8(bytes[..split].to_vec()).expect("utf8 headers"); + let mut lines = head.lines(); + let status = lines + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse().ok()) + .expect("a status code"); + let mut headers: Vec = lines + .filter(|line| !line.to_ascii_lowercase().starts_with("date:")) + .map(str::to_owned) + .collect(); + headers.sort(); + Raw { + status, + headers, + body: bytes[split + 4..].to_vec(), + } +} + +fn header<'a>(response: &'a Raw, name: &str) -> Option<&'a str> { + response.headers.iter().find_map(|line| { + let (candidate, value) = line.split_once(':')?; + candidate.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +fn assert_probe(response: &Raw, status: u16, body: &str) { + assert_eq!(response.status, status, "{response:?}"); + assert_eq!( + String::from_utf8_lossy(&response.body), + body, + "the body is the constant" + ); + assert_eq!(header(response, "content-type"), Some("application/json")); + assert!( + header(response, "x-registry-request-id").is_none(), + "a probe mints no request id: {response:?}" + ); +} + +#[tokio::test] +async fn probes_answer_identically_under_three_projects_with_and_without_authorization() { + let upstream = UpstreamDouble::start(); + let second = tempfile::tempdir().expect("a copied Adapter project"); + copy_example_project(second.path()); + replace_profile_text( + second.path(), + " path: /v1/records/{type}\n", + " path: /v9/records/{type}\n", + ); + let projects = [ + Served::start(&upstream.url("")).await, + Served::start_with_project(&upstream.url(""), &Served::govstack_project()).await, + Served::start_with_project(&upstream.url(""), second.path()).await, + ]; + + let mut seen: Vec> = Vec::new(); + for served in &projects { + let token = format!("Bearer {}", served.token("")); + let mut answers = Vec::new(); + for path in [HEALTH_PATH, READY_PATH] { + for authorization in [None, Some("Bearer not-a-token"), Some(token.as_str())] { + answers.push(raw(served, "GET", path, authorization)); + } + } + for (position, answer) in answers.iter().enumerate() { + let expected = if position < 3 { + HEALTH_BODY + } else { + READY_BODY + }; + assert_probe(answer, 200, expected); + } + // The same path answers byte-for-byte alike, whatever the header. + assert_eq!(answers[0], answers[1]); + assert_eq!(answers[0], answers[2]); + assert_eq!(answers[3], answers[4]); + assert_eq!(answers[3], answers[5]); + // A method other than GET refuses with no project-specific text. + let refused = raw(served, "POST", HEALTH_PATH, None); + assert_eq!(refused.status, 405, "{refused:?}"); + assert_eq!(header(&refused, "allow"), Some("GET")); + assert!(refused.body.is_empty(), "{refused:?}"); + answers.push(refused); + seen.push(answers); + } + assert_eq!(seen[0], seen[1], "the probes do not vary with the project"); + assert_eq!(seen[0], seen[2], "the probes do not vary with the project"); + assert_eq!( + upstream.request_count(), + 0, + "a probe never reaches a source" + ); +} + +#[tokio::test] +async fn a_journal_that_is_not_ready_answers_the_constant_503_without_database_text() { + let upstream = UpstreamDouble::start(); + let served = Served::start(&upstream.url("")).await; + assert_probe(&raw(&served, "GET", READY_PATH, None), 200, READY_BODY); + + served + .execute_sql( + "DELETE FROM adapter_schema_migrations \ + WHERE version = (SELECT max(version) FROM adapter_schema_migrations)", + ) + .await; + let drift = raw(&served, "GET", READY_PATH, None); + assert_probe(&drift, 503, NOT_READY_BODY); + + served + .execute_sql("DROP TABLE adapter_schema_migrations") + .await; + let missing = raw(&served, "GET", READY_PATH, Some("Bearer anything")); + assert_probe(&missing, 503, NOT_READY_BODY); + assert_eq!(drift, missing, "the refusal does not carry the cause"); + let text = String::from_utf8_lossy(&missing.body).to_lowercase(); + for fragment in ["relation", "adapter_", "postgres", "sql", "error"] { + assert!(!text.contains(fragment), "{fragment} leaked: {text}"); + } + assert_probe(&raw(&served, "GET", HEALTH_PATH, None), 200, HEALTH_BODY); + assert_eq!( + upstream.request_count(), + 0, + "readiness never probes a source" + ); +} + +#[tokio::test] +async fn probes_append_no_journal_row() { + let upstream = UpstreamDouble::start(); + let served = Served::start(&upstream.url("")).await; + let before = served.journal_kinds().await; + for _ in 0..3 { + for path in [HEALTH_PATH, READY_PATH] { + assert_eq!(raw(&served, "GET", path, None).status, 200); + } + } + served + .execute_sql("DROP TABLE adapter_schema_migrations") + .await; + assert_eq!(raw(&served, "GET", READY_PATH, None).status, 503); + assert_eq!( + served.journal_kinds().await, + before, + "neither a ready nor a not-ready probe appends an event" + ); +} + +#[tokio::test] +async fn a_project_declaring_health_or_ready_refuses_to_start() { + for record_type in ["health", "ready"] { + let upstream = UpstreamDouble::start(); + let directory = tempfile::tempdir().expect("a copied Adapter project"); + copy_example_project(directory.path()); + replace_profile_text( + directory.path(), + " path: /v1/records/{type}\n", + " path: /{type}\n", + ); + let project_path = directory.path().join("project.yaml"); + let project = + std::fs::read_to_string(&project_path).expect("the copied project is readable"); + std::fs::write(&project_path, project.replace("person", record_type)) + .expect("write the colliding project"); + + // The workspace check refuses the colliding binding before the facade + // builds a router, so the probe route is never shadowed. + let stderr = Served::refusal_with_project(&upstream.url(""), directory.path()).await; + assert!( + stderr.contains("the workspace check refused the deployment"), + "{record_type}: {stderr}" + ); + assert!( + stderr.contains("adapter.project.reserved-facade-path"), + "{record_type}: {stderr}" + ); + assert_eq!( + upstream.request_count(), + 0, + "a refused deployment performs no source I/O" + ); + } +} diff --git a/crates/registry-adapter/tests/postgres_journal_retention_served.rs b/crates/registry-adapter/tests/postgres_journal_retention_served.rs index a5778e1e92..f3c6a9f165 100644 --- a/crates/registry-adapter/tests/postgres_journal_retention_served.rs +++ b/crates/registry-adapter/tests/postgres_journal_retention_served.rs @@ -2,8 +2,11 @@ //! Journal retention through the real Adapter binary: a served deployment, //! read-only or write, deletes journal events older than -//! `audit.retentionDays` and keeps the ones inside the window, and a -//! runtime role that cannot run those deletes is refused at startup. +//! `audit.retentionDays` and keeps the ones inside the window. The same +//! suite covers the runtime role's grants: a split role starts with none and +//! ends with exactly the privileges its deployment requires, a single role +//! issues no grant, a runtime URL that does not connect stops startup before +//! any grant, and a grant the migration role cannot make stops it with the cause. //! Absence of `ADAPTER_TEST_DATABASE_URL` is a failure, never a skip. #![cfg(feature = "postgres-test")] @@ -178,6 +181,53 @@ impl SplitRoles { profile: Option<&Path>, endpoint: &str, ) -> Self { + Self::spawn_launch( + upstream_url, + migration_url, + runtime_url, + Some((project, profile, endpoint)), + None, + ) + } + + /// Serve `payments` (with the provider packs it pins) over split roles, + /// beside the GovStack project when `facade` is given, alone when not. + fn spawn_payments( + migration_url: &str, + runtime_url: &str, + facade: Option<(&str, &Path)>, + payments: &Path, + packs: &[&Path], + ) -> Self { + Self::spawn_launch( + facade.map_or("", |(upstream_url, _)| upstream_url), + migration_url, + runtime_url, + facade.map(|(_, project)| (project, None, "tracker")), + Some((payments, packs)), + ) + } + + fn spawn_launch( + upstream_url: &str, + migration_url: &str, + runtime_url: &str, + facade: Option<(&Path, Option<&Path>, &str)>, + payments: Option<(&Path, &[&Path])>, + ) -> Self { + let endpoints = match facade { + Some((_, _, endpoint)) => format!( + r#"endpoints: + - endpoint: {endpoint} + baseUrl: {upstream_url} + credential: + type: basic + usernameRef: secret:env/TEST_UPSTREAM_USERNAME + passwordRef: secret:env/TEST_UPSTREAM_PASSWORD +"# + ), + None => "endpoints: []\n".to_owned(), + }; let key = access_token_test_key(jsonwebtoken::Algorithm::ES256); let jwks = jwks_from_private_jwk(&key).to_string(); let port = TcpListener::bind("127.0.0.1:0") @@ -193,14 +243,7 @@ impl SplitRoles { r#"apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 kind: AdapterRuntimeConfig id: govstack-split-roles -endpoints: - - endpoint: {endpoint} - baseUrl: {upstream_url} - credential: - type: basic - usernameRef: secret:env/TEST_UPSTREAM_USERNAME - passwordRef: secret:env/TEST_UPSTREAM_PASSWORD -listener: +{endpoints}listener: bind: 127.0.0.1:{port} database: runtimeUrlRef: secret:env/TEST_DB_RUNTIME_URL @@ -227,16 +270,21 @@ cursorKeyRef: secret:env/TEST_CURSOR_KEY ) .expect("write the runtime config"); let mut command = Command::new(env!("CARGO_BIN_EXE_adapter")); - command - .args(["serve", "--runtime-config"]) - .arg(&runtime) - .arg("--project") - .arg(project); - if !project.join("pack.yaml").exists() { - command.arg("--pack").arg(Served::example_pack()); + command.args(["serve", "--runtime-config"]).arg(&runtime); + if let Some((project, profile, _)) = facade { + command.arg("--project").arg(project); + if !project.join("pack.yaml").exists() { + command.arg("--pack").arg(Served::example_pack()); + } + if let Some(profile) = profile.filter(|_| !project.join("profile.yaml").exists()) { + command.arg("--profile").arg(profile); + } } - if let Some(profile) = profile.filter(|_| !project.join("profile.yaml").exists()) { - command.arg("--profile").arg(profile); + if let Some((payments, packs)) = payments { + command.arg("--payments-config").arg(payments); + for pack in packs { + command.arg("--payment-provider-pack").arg(pack); + } } let child = command .env("TEST_UPSTREAM_USERNAME", USERNAME) @@ -245,6 +293,7 @@ cursorKeyRef: secret:env/TEST_CURSOR_KEY .env("TEST_DB_RUNTIME_URL", runtime_url) .env("TEST_JWKS", &jwks) .env("TEST_CURSOR_KEY", CURSOR_KEY) + .env("TEST_PAYMENT_TOKEN", "synthetic-payment-token") .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() @@ -308,169 +357,1203 @@ fn as_role(database: &str, role: &str) -> String { format!("{scheme}://{role}:{RUNTIME_PASSWORD}@{host}") } +/// A login role the test creates in the shared database, dropped with its +/// owned objects when the test ends. +async fn create_login_role(database: &str, role: &str) { + execute( + database, + &format!("CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}';"), + ) + .await; +} + +async fn drop_role(database: &str, role: &str) { + execute( + database, + &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + ) + .await; +} + +async fn current_schema(database: &str) -> String { + connect(database) + .await + .query_one("SELECT current_schema()", &[]) + .await + .expect("read the migrated schema") + .get(0) +} + #[tokio::test] -async fn a_runtime_role_without_delete_is_refused_and_insert_select_delete_serves() { +async fn a_split_runtime_role_with_no_grants_is_granted_what_it_needs_and_runs_retention() { let upstream = UpstreamDouble::start(); let database = migrated_schema(&upstream, &Served::govstack_project(), "govstack-grants").await; - let schema: String = connect(&database) + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + seed(&database).await; + let runtime_url = as_role(&database, &role); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + serving.wait_until_listening(); + await_retention(&database).await; + drop(serving); + drop_role(&database, &role).await; +} + +/// The privileges `role` holds on every table of `schema`, by table, for the +/// seven table privileges PostgreSQL defines. Tables with none are omitted. +async fn table_privileges( + database: &str, + schema: &str, + role: &str, +) -> std::collections::BTreeMap> { + let rows = connect(database) .await - .query_one("SELECT current_schema()", &[]) + .query( + "SELECT c.relname, p.privilege \ + FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + CROSS JOIN unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', \ + 'REFERENCES', 'TRIGGER']) AS p(privilege) \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') \ + AND has_table_privilege($2, c.oid, p.privilege) \ + ORDER BY c.relname, p.privilege", + &[&schema, &role], + ) .await - .expect("read the migrated schema") - .get(0); + .expect("read the role's table privileges"); + let mut held = std::collections::BTreeMap::>::new(); + for row in rows { + held.entry(row.get(0)).or_default().push(row.get(1)); + } + held +} + +/// Every role that holds a privilege on a table or sequence of `schema` or on +/// the schema itself without owning it, by name, with `PUBLIC` for the +/// pseudo-role. A grantee that may pass the privilege on reads +/// ` WITH GRANT OPTION`. Unlike `has_table_privilege`, this reads the +/// ACLs, so a grant to `PUBLIC` is not mistaken for a grant to one role. +async fn acl_grantees(database: &str, schema: &str) -> std::collections::BTreeSet { + connect(database) + .await + .query( + "SELECT (CASE a.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END) \ + || (CASE WHEN a.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END) \ + FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + CROSS JOIN LATERAL aclexplode(c.relacl) a \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'S') AND a.grantee <> c.relowner \ + UNION \ + SELECT (CASE a.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END) \ + || (CASE WHEN a.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END) \ + FROM pg_namespace n \ + CROSS JOIN LATERAL aclexplode(n.nspacl) a \ + WHERE n.nspname = $1 AND a.grantee <> n.nspowner", + &[&schema], + ) + .await + .expect("read the ACL grantees") + .iter() + .map(|row| row.get::<_, String>(0)) + .collect() +} + +fn expected(grants: &[(&str, &[&str])]) -> std::collections::BTreeMap> { + grants + .iter() + .map(|(table, privileges)| { + let mut privileges: Vec = privileges.iter().map(|p| (*p).to_owned()).collect(); + privileges.sort(); + ((*table).to_owned(), privileges) + }) + .collect() +} + +/// Serve `project` with a split runtime role that starts with no grants, and +/// assert the role ends with exactly `grants` and `USAGE` (not `CREATE`) on +/// the schema. +async fn assert_serve_grants_exactly( + project: &Path, + profile: Option<&Path>, + endpoint: &str, + deployment: &str, + grants: &[(&str, &[&str])], +) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; let role = format!("{schema}_runtime"); - execute( + create_login_role(&database, &role).await; + assert!( + table_privileges(&database, &schema, &role).await.is_empty(), + "the role starts with no table privilege" + ); + let runtime_url = as_role(&database, &role); + let mut serving = SplitRoles::spawn_project( + &upstream.url(""), &database, - &format!( - "CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ - GRANT USAGE ON SCHEMA {schema} TO {role}; \ - GRANT SELECT ON adapter_schema_migrations TO {role}; \ - GRANT INSERT, SELECT ON adapter_journal_events TO {role};" - ), + &runtime_url, + project, + profile, + endpoint, + ); + serving.wait_until_listening(); + assert_eq!( + table_privileges(&database, &schema, &role).await, + expected(grants), + "the runtime role holds exactly the privileges the deployment requires" + ); + let schema_privileges = connect(&database) + .await + .query_one( + "SELECT has_schema_privilege($1, $2, 'USAGE'), has_schema_privilege($1, $2, 'CREATE')", + &[&role, &schema], + ) + .await + .expect("read the schema privileges"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role is the only grantee, and PUBLIC gained nothing" + ); + assert!(schema_privileges.get::<_, bool>(0), "USAGE on the schema"); + assert!( + !schema_privileges.get::<_, bool>(1), + "no CREATE on the schema" + ); + drop(serving); + drop_role(&database, &role).await; +} + +const EVERY_DEPLOYMENT: [(&str, &[&str]); 2] = [ + ("adapter_journal_events", &["INSERT", "SELECT", "DELETE"]), + ("adapter_schema_migrations", &["SELECT"]), +]; +const WRITE: [(&str, &[&str]); 2] = [ + ( + "adapter_idempotency_entries", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ), + ( + "adapter_idempotency_resumes", + &["SELECT", "INSERT", "UPDATE", "DELETE"], + ), +]; +const RECOVERY: [(&str, &[&str]); 2] = [ + ( + "adapter_idempotency_async_artifacts", + &["SELECT", "INSERT", "UPDATE"], + ), + ("adapter_idempotency_resume_bindings", &["SELECT", "INSERT"]), +]; + +#[tokio::test] +async fn serve_grants_exactly_the_required_privileges() { + // A read-only deployment: the journal and the migration ledger only. + assert_serve_grants_exactly( + &Served::govstack_project(), + None, + "tracker", + "grants-read", + &EVERY_DEPLOYMENT, + ) + .await; + + // A synchronous write adds idempotent claims and response custody, and + // no artifact fence. + let write: Vec<_> = EVERY_DEPLOYMENT.iter().chain(&WRITE).copied().collect(); + assert_serve_grants_exactly( + &Served::example_project(), + Some(&Served::example_profile()), + "tracker", + "grants-write", + &write, ) .await; - seed(&database).await; - let runtime_url = as_role(&database, &role); + + // A resumable write adds the artifact fence and the resume bindings. + let resumable: Vec<_> = EVERY_DEPLOYMENT + .iter() + .chain(&WRITE) + .chain(&RECOVERY) + .copied() + .collect(); + let recovery_project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/facade-recovery"); + assert_serve_grants_exactly( + &recovery_project, + Some(&Served::example_profile()), + "reference", + "grants-resume", + &resumable, + ) + .await; +} + +#[tokio::test] +async fn a_runtime_url_that_cannot_connect_fails_startup_before_any_grant() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-ghost").await; + let schema = current_schema(&database).await; + // The runtime URL names a role that does not exist. + let runtime_url = as_role(&database, &format!("{schema}_absent")); let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); - assert!( - stderr.contains("the runtime role lacks DELETE on adapter_journal_events"), - "{stderr}" + assert!(stderr.contains("database runtime"), "{stderr}"); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no grant is made before the runtime credential works: {stderr}" ); +} + +#[tokio::test] +async fn a_runtime_url_naming_public_is_refused_and_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-public").await; + let schema = current_schema(&database).await; + let runtime_url = as_role(&database, "public"); + + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); assert_eq!( - seeded_exchange_ids(&database).await.len(), - usize::try_from(MAX_RETENTION_BATCH).expect("the batch fits usize") + 2, - "a refused deployment deletes nothing" + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no grant reached PUBLIC or any other role: {stderr}" ); +} + +#[tokio::test] +async fn a_runtime_role_with_members_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-members").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let member = format!("{schema}_member"); + create_login_role(&database, &role).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let runtime_url = as_role(&database, &role); + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an automatic grant is never made to a role others inherit from: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; +} + +/// The role that created the runtime role administers it, as in a database +/// built by the shared provisioning plan, so its membership does not stop the grant. +#[tokio::test] +async fn a_runtime_role_whose_only_member_administers_it_is_granted_its_privileges() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-admin").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + create_login_role(&database, &role).await; + create_login_role(&database, &administrator).await; execute( &database, - &format!("GRANT DELETE ON adapter_journal_events TO {role};"), + &format!("GRANT {role} TO {administrator} WITH ADMIN OPTION;"), ) .await; + let runtime_url = as_role(&database, &role); + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); serving.wait_until_listening(); - await_retention(&database).await; + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role received the grants" + ); drop(serving); + drop_role(&database, &administrator).await; + drop_role(&database, &role).await; +} + +/// Create the runtime role the way the shared provisioning plan does: a +/// `LOGIN CREATEROLE` administrator creates it with `createrole_self_grant` +/// set to `set,inherit`. PostgreSQL then records two membership rows for the +/// administrator in the runtime role, one that carries ADMIN OPTION and one +/// that carries SET and INHERIT. +async fn create_provisioned_runtime_role(database: &str, runtime: &str, administrator: &str) { execute( - &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + database, + &format!("CREATE ROLE {administrator} LOGIN CREATEROLE PASSWORD '{RUNTIME_PASSWORD}';"), ) .await; -} - -/// A fresh migrated schema and a runtime role holding only the journal -/// grants every deployment needs. -async fn journal_only_runtime_role( - upstream: &UpstreamDouble, - deployment: &str, -) -> (String, String) { - let database = migrated_schema(upstream, &Served::govstack_project(), deployment).await; - let schema: String = connect(&database) + execute( + &as_role(database, administrator), + &format!( + "SET createrole_self_grant = 'set,inherit'; \ + CREATE ROLE {runtime} LOGIN PASSWORD '{RUNTIME_PASSWORD}';" + ), + ) + .await; + let rows = connect(database) .await - .query_one("SELECT current_schema()", &[]) + .query( + "SELECT m.admin_option FROM pg_auth_members m \ + JOIN pg_roles r ON r.oid = m.roleid \ + JOIN pg_roles a ON a.oid = m.member \ + WHERE r.rolname = $1 AND a.rolname = $2 ORDER BY m.admin_option", + &[&runtime, &administrator], + ) .await - .expect("read the migrated schema") - .get(0); + .expect("read the administrator's memberships"); + assert_eq!( + rows.iter() + .map(|row| row.get::<_, bool>(0)) + .collect::>(), + [false, true], + "the administrator holds one ADMIN row and one plain row in the runtime role" + ); +} + +/// The layout the shared provisioning plan builds, with the CREATEROLE administrator +/// as the runtime role's only member, still receives its grants. Pinned on +/// the two-row layout: a per-row test of ADMIN OPTION would count the +/// administrator's plain row and refuse every provisioned database. +#[tokio::test] +async fn a_provisioned_runtime_role_is_granted_its_privileges() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-provisioned").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + create_provisioned_runtime_role(&database, &role, &administrator).await; + let runtime_url = as_role(&database, &role); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + serving.wait_until_listening(); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role received the grants" + ); + drop(serving); + drop_role(&database, &role).await; + drop_role(&database, &administrator).await; +} + +/// The provisioned layout plus one member that does not administer the role: +/// that member would inherit the grants, so none is made. +#[tokio::test] +async fn a_provisioned_runtime_role_with_a_plain_member_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-mixed").await; + let schema = current_schema(&database).await; let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + let member = format!("{schema}_member"); + create_provisioned_runtime_role(&database, &role, &administrator).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let runtime_url = as_role(&database, &role); + + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "a plain member blocks the grant even beside an administrator: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; + drop_role(&database, &administrator).await; +} + +/// A member that holds ADMIN OPTION but has members of its own reaches the +/// runtime role through them, so it does not make the grant safe. +#[tokio::test] +async fn an_administrator_with_members_of_its_own_blocks_the_grant() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-admin-chain").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let administrator = format!("{schema}_admin"); + let behind = format!("{schema}_behind"); + create_login_role(&database, &role).await; + create_login_role(&database, &administrator).await; + create_login_role(&database, &behind).await; execute( &database, &format!( - "CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ - GRANT USAGE ON SCHEMA {schema} TO {role}; \ - GRANT SELECT ON adapter_schema_migrations TO {role}; \ - GRANT INSERT, SELECT, DELETE ON adapter_journal_events TO {role};" + "GRANT {role} TO {administrator} WITH ADMIN OPTION; \ + GRANT {administrator} TO {behind};" ), ) .await; - (database, role) -} + let runtime_url = as_role(&database, &role); -const WRITE_GRANTS: &str = "GRANT SELECT, INSERT, UPDATE, DELETE \ - ON adapter_idempotency_entries, adapter_idempotency_resumes TO {role};"; -const RECOVERY_GRANTS: &str = - "GRANT SELECT, INSERT, UPDATE ON adapter_idempotency_async_artifacts TO {role}; \ - GRANT SELECT, INSERT ON adapter_idempotency_resume_bindings TO {role};"; + let stderr = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url).refusal(); + assert!(stderr.contains("the runtime role lacks"), "{stderr}"); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an administrator that others inherit from blocks the grant: {stderr}" + ); + drop_role(&database, &behind).await; + drop_role(&database, &administrator).await; + drop_role(&database, &role).await; +} #[tokio::test] -async fn a_write_runtime_role_without_idempotency_grants_is_refused_by_name() { +async fn a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing() { let upstream = UpstreamDouble::start(); - let (database, role) = journal_only_runtime_role(&upstream, "tracker-grants").await; + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-nonowner").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + // The migrator can use and read the schema but owns nothing and holds no + // grant option, so PostgreSQL turns each of its GRANTs into a warning. + execute( + &database, + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator};" + ), + ) + .await; + let migration_url = as_role(&database, &migrator); let runtime_url = as_role(&database, &role); - let spawn = || { - SplitRoles::spawn_project( - &upstream.url(""), - &database, - &runtime_url, - &Served::example_project(), - Some(&Served::example_profile()), - "tracker", - ) - }; - let stderr = spawn().refusal(); + let stderr = SplitRoles::spawn(&upstream.url(""), &migration_url, &runtime_url).refusal(); assert!( - stderr.contains( - "the runtime role lacks SELECT, INSERT, UPDATE, DELETE on adapter_idempotency_entries" - ), + stderr.contains("INSERT, SELECT, DELETE on adapter_journal_events"), "{stderr}" ); assert!( - stderr.contains("SELECT, INSERT, UPDATE, DELETE on adapter_idempotency_resumes"), + stderr.contains("the migration role does not own"), "{stderr}" ); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); assert!( - !stderr.contains("adapter_idempotency_async_artifacts"), - "a synchronous write needs no artifact-fence grant: {stderr}" + !acl_grantees(&database, &schema).await.contains(&role), + "a failed grant leaves nothing behind: {stderr}" ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; +} - execute(&database, &WRITE_GRANTS.replace("{role}", &role)).await; - let mut serving = spawn(); - serving.wait_until_listening(); - drop(serving); +/// The migration role owns the journal tables but not the idempotency ones, so +/// the grants on the first succeed and the check on the second fails: nothing +/// stays granted. +#[tokio::test] +async fn a_migration_role_that_owns_only_some_tables_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-partial").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; execute( &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + ALTER TABLE {schema}.adapter_journal_events OWNER TO {migrator}; \ + ALTER TABLE {schema}.adapter_schema_migrations OWNER TO {migrator};" + ), ) .await; + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + + let stderr = SplitRoles::spawn_project( + &upstream.url(""), + &migration_url, + &runtime_url, + &Served::example_project(), + Some(&Served::example_profile()), + "tracker", + ) + .refusal(); + assert!( + stderr.contains("on adapter_idempotency_entries"), + "{stderr}" + ); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "the grants on the tables the migration role owns were rolled back: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; } +/// A start that finds every privilege in place writes no catalog row. #[tokio::test] -async fn a_resumable_write_runtime_role_needs_the_recovery_grants_and_serves_on_first_run() { +async fn a_restart_with_every_grant_in_place_writes_no_grant() { let upstream = UpstreamDouble::start(); - let (database, role) = journal_only_runtime_role(&upstream, "resume-grants").await; - execute(&database, &WRITE_GRANTS.replace("{role}", &role)).await; + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-restart").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; let runtime_url = as_role(&database, &role); - let project = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../products/adapter/examples/facade-recovery"); - let spawn = || { - SplitRoles::spawn_project( - &upstream.url(""), - &database, - &runtime_url, - &project, - Some(&Served::example_profile()), - "reference", + let catalog_versions = || async { + connect(&database) + .await + .query( + "SELECT c.relname::text, c.xmin::text FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') \ + UNION ALL SELECT n.nspname::text, n.xmin::text FROM pg_namespace n \ + WHERE n.nspname = $1 \ + ORDER BY 1", + &[&schema], + ) + .await + .expect("read the catalog row versions") + .iter() + .map(|row| (row.get::<_, String>(0), row.get::<_, String>(1))) + .collect::>() + }; + + let mut first = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + first.wait_until_listening(); + drop(first); + let granted = catalog_versions().await; + let mut second = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + second.wait_until_listening(); + drop(second); + assert_eq!( + catalog_versions().await, + granted, + "a restart rewrote a table or schema ACL" + ); + drop_role(&database, &role).await; +} + +/// The advisory-lock key the grant step takes, so two replicas starting +/// together do not rewrite the same catalog rows at once. +const GRANT_LOCK_KEY: i64 = 0x6164_6170_5f67_6e74; + +#[tokio::test] +async fn the_grant_step_waits_for_the_grant_lock() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), "grants-lock").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let runtime_url = as_role(&database, &role); + let holder = connect(&database).await; + holder + .query_one("SELECT pg_advisory_lock($1)", &[&GRANT_LOCK_KEY]) + .await + .expect("take the grant lock"); + + let mut serving = SplitRoles::spawn(&upstream.url(""), &database, &runtime_url); + tokio::time::sleep(Duration::from_secs(3)).await; + assert!( + serving + .child + .try_wait() + .expect("poll the adapter") + .is_none(), + "the adapter exited while the grant lock was held" + ); + assert!( + TcpStream::connect(("127.0.0.1", serving.port)).is_err(), + "the adapter served while the grant lock was held" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "the adapter granted before it held the grant lock" + ); + holder + .query_one("SELECT pg_advisory_unlock($1)", &[&GRANT_LOCK_KEY]) + .await + .expect("release the grant lock"); + serving.wait_until_listening(); + drop(serving); + drop_role(&database, &role).await; +} + +#[tokio::test] +async fn single_role_serve_issues_no_grant() { + let upstream = UpstreamDouble::start(); + let base = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("ADAPTER_TEST_DATABASE_URL names a disposable PostgreSQL test server"); + let suffix = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("the test clock is after the Unix epoch") + .as_nanos(); + let schema = format!("adapter_single_{suffix}"); + let role = format!("{schema}_solo"); + let log = format!("{schema}_log"); + // An event trigger records the session role of every GRANT in the + // database, so the test can observe a grant a single role issues to itself. + // Other tests run GRANTs while it exists, and its own cleanup can drop the + // log table under one of them, so the function ignores that one case. + execute( + &base, + &format!( + "CREATE SCHEMA {schema}; CREATE SCHEMA {log}; \ + CREATE TABLE {log}.grants (session_role text NOT NULL); \ + CREATE FUNCTION {log}.record() RETURNS event_trigger \ + LANGUAGE plpgsql SECURITY DEFINER AS $$ \ + BEGIN INSERT INTO {log}.grants VALUES (session_user); \ + EXCEPTION WHEN undefined_table THEN NULL; END $$; \ + CREATE EVENT TRIGGER {log}_trigger ON ddl_command_end \ + WHEN TAG IN ('GRANT') EXECUTE FUNCTION {log}.record(); \ + CREATE ROLE {role} LOGIN PASSWORD '{RUNTIME_PASSWORD}'; \ + GRANT USAGE, CREATE ON SCHEMA {schema} TO {role};" + ), + ) + .await; + let separator = if base.contains('?') { '&' } else { '?' }; + let scoped = format!("{base}{separator}options=-csearch_path%3D{schema}"); + let single_url = as_role(&scoped, &role); + let grants_by_role = || async { + connect(&base) + .await + .query( + &format!("SELECT count(*) FROM {log}.grants WHERE session_role = $1"), + &[&role], + ) + .await + .expect("read the grant log")[0] + .get::<_, i64>(0) + }; + + let mut serving = SplitRoles::spawn(&upstream.url(""), &single_url, &single_url); + serving.wait_until_listening(); + assert_eq!(grants_by_role().await, 0, "a single role issues no grant"); + // Positive control: the trigger does see a grant the same role issues. + execute( + &single_url, + "GRANT SELECT ON adapter_schema_migrations TO PUBLIC;", + ) + .await; + assert_eq!(grants_by_role().await, 1, "the grant log records a grant"); + drop(serving); + execute( + &base, + &format!( + "DROP EVENT TRIGGER {log}_trigger; DROP OWNED BY {role}; DROP ROLE {role}; \ + DROP SCHEMA {schema} CASCADE; DROP SCHEMA {log} CASCADE;" + ), + ) + .await; +} + +// Payment tables. The payment host's startup check requires the privileges +// below on the collection tables and, when `payments.yaml` declares a +// disbursement connection, on the G2P tables. These lists are retyped here on +// purpose: a change to the check must change them too. +const COLLECTIONS: [(&str, &[&str]); 3] = [ + ("adapter_payment_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_payment_commands", &["SELECT", "INSERT"]), + ("adapter_payment_events", &["SELECT", "INSERT"]), +]; +const DISBURSEMENTS: [(&str, &[&str]); 3] = [ + ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"]), + ("adapter_g2p_commands", &["SELECT", "INSERT"]), + ("adapter_g2p_events", &["SELECT", "INSERT"]), +]; +const COLLECTIONS_SEQUENCE: &str = "adapter_payment_events_sequence_seq"; +const DISBURSEMENTS_SEQUENCE: &str = "adapter_g2p_events_sequence_seq"; + +const G2P_SCRIPT: &str = r#" +fn submit_request(intent, settings, acceptance) { + #{pathParameters: #{}, query: #{}, headers: #{}, body: #{correlation: intent.correlationId}} +} +fn submit_response(intent, settings, acceptance, response) { + #{correlationId: intent.correlationId, references: #{transfer: response.body.id}} +} +fn status_request(intent, settings, acceptance) { + #{pathParameters: #{}, query: #{id: acceptance.references.transfer}, headers: #{}, body: ()} +} +fn status_response(intent, settings, acceptance, response) { + #{ + correlationId: response.body.correlation, + providerReference: response.body.id, + state: "provider-confirmed", + money: #{minorUnits: response.body.minorUnits, currency: response.body.currency, scale: 2}, + parties: [ + #{role: "funding", key: "ACCOUNT_ID", value: response.body.debit}, + #{role: "recipient", key: "MSISDN", value: response.body.credit} + ] + } +} +"#; + +/// A `payments.yaml` with one simulator collection connection, and one bearer +/// disbursement connection when `disbursements`, with the provider pack the +/// second pins. Returns the configuration path and the packs to pass. +fn payments_fixture( + directory: &Path, + disbursements: bool, +) -> (std::path::PathBuf, Vec) { + std::fs::create_dir_all(directory.join("scripts")).expect("create the pack scripts directory"); + std::fs::write(directory.join("scripts/g2p.rhai"), G2P_SCRIPT).expect("write the script"); + let pack = format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: g2p-pay +version: '1' +connector: adapter-payment-http/v1 +capabilities: [disbursement] +mapping: + disbursement: + auth: bearer + submit: + path: /disbursements + request: {{file: scripts/g2p.rhai, entrypoint: submit_request}} + response: {{file: scripts/g2p.rhai, entrypoint: submit_response}} + status: + path: /disbursements/status + request: {{file: scripts/g2p.rhai, entrypoint: status_request}} + response: {{file: scripts/g2p.rhai, entrypoint: status_response}} + scripts: + - path: scripts/g2p.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(G2P_SCRIPT.as_bytes()) + ); + let pack_path = directory.join("pack.yaml"); + std::fs::write(&pack_path, &pack).expect("write the provider pack"); + let mut yaml = r#"apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 +kind: AdapterPayments +connections: + - id: licence-fees + institutionId: institution-a + serviceId: licence-issuance + allowedClients: [synthetic-client] + requiredScope: payments:collect + binding: + simulation: true + currency: USD + currencyScale: 2 + providerCredentialRef: secret:env/TEST_PAYMENT_TOKEN + providerCredentialIdentity: registry + replayWindowSeconds: 3600 + provider: + type: simulator + connection: + baseUrl: http://127.0.0.1:8099/ + tenant: pilot + biller: ministry + billerName: Ministry + callbackUrl: https://programme.example.test/callback + payerFiBic: SIMBANK + registry: + baseUrl: http://127.0.0.1:8080/ + recordType: service-fee-bill + recordRoute: service-fee-bills + readProfile: payment-adapter-reporter + bindProfile: payment-adapter-binder + receiptProfile: payment-adapter-reporter + bindAction: bind-payment-attempt + receiptAction: record-payment-receipt + credentialRef: secret:env/TEST_PAYMENT_TOKEN + credentialIdentity: payment-adapter +"# + .to_owned(); + if disbursements { + yaml.push_str(&format!( + r#"disbursements: + - id: cash-transfers + allowedClients: [synthetic-client] + requiredScope: payments:disburse + binding: + institutionId: ministry-social-protection + serviceId: cash-transfer + programmeId: cash-programme + fundingAccountId: programme-account + currency: KES + currencyScale: 2 + providerPack: + id: g2p-pay + version: '1' + digest: {} + fundingPartyKey: ACCOUNT_ID + recipientPartyKey: MSISDN + provider: + type: http + revision: bearer-v1 + submitBaseUrl: https://disbursements.example.test/ + statusBaseUrl: https://disbursements.example.test/ + auth: + type: bearer + credentialIdentity: provider + credentialRef: secret:env/TEST_PAYMENT_TOKEN + settings: {{}} + registry: + baseUrl: https://breg.example.test/ + credentialIdentity: g2p-payment-adapter + credentialRef: secret:env/TEST_PAYMENT_TOKEN + recordRoute: disbursement-instructions + recordType: disbursement-instruction + readProfile: g2p-adapter-read + bindAction: bind-payout-attempt + bindProfile: g2p-adapter-bind + reportAction: record-provider-confirmation + reportProfile: g2p-adapter-report +"#, + registry_platform_config::sha256_uri(pack.as_bytes()) + )); + } + let payments_path = directory.join("payments.yaml"); + std::fs::write(&payments_path, yaml).expect("write the payments configuration"); + ( + payments_path, + if disbursements { + vec![pack_path] + } else { + Vec::new() + }, + ) +} + +/// Whether `role` holds USAGE on the sequence `name` of `schema`. +async fn sequence_usage(database: &str, schema: &str, name: &str, role: &str) -> bool { + connect(database) + .await + .query_one( + "SELECT has_sequence_privilege($1, to_regclass($2), 'USAGE')", + &[&role, &format!("{schema}.{name}")], ) + .await + .expect("read the sequence privilege") + .get(0) +} + +/// The tables `role` holds a privilege on, restricted to the payment host's +/// (`adapter_payment_*` and `adapter_g2p_*`). +async fn payment_table_privileges( + database: &str, + schema: &str, + role: &str, +) -> std::collections::BTreeMap> { + table_privileges(database, schema, role) + .await + .into_iter() + .filter(|(table, _)| { + table.starts_with("adapter_payment_") || table.starts_with("adapter_g2p_") + }) + .collect() +} + +/// How a payment grant test serves: beside a GovStack project, or alone. +#[derive(Clone, Copy)] +enum PaymentHost { + BesideFacade, + Alone, +} + +/// Serve payments over a split runtime role that starts with no grants, and +/// assert it ends holding exactly the privileges the payment host requires: +/// the collection tables, and the G2P tables when `disbursements`, plus USAGE +/// on the schema and the events sequences, and nothing else anywhere. +async fn assert_payments_grants_exactly(host: PaymentHost, disbursements: bool, deployment: &str) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), disbursements); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + let facade = match host { + PaymentHost::BesideFacade => Some((upstream_url.as_str(), govstack.as_path())), + PaymentHost::Alone => None, }; + let mut serving = + SplitRoles::spawn_payments(&database, &runtime_url, facade, &payments, &packs); + serving.wait_until_listening(); - let stderr = spawn().refusal(); + let mut required: Vec<(&str, &[&str])> = COLLECTIONS.to_vec(); + if disbursements { + required.extend(DISBURSEMENTS); + } + // Beside a project the facade's own tables are granted too. The facade + // grant tests cover those, so this reads the payment tables only. + assert_eq!( + payment_table_privileges(&database, &schema, &role).await, + expected(&required), + "the runtime role holds exactly the payment privileges the host requires" + ); + assert!(sequence_usage(&database, &schema, COLLECTIONS_SEQUENCE, &role).await); + assert_eq!( + sequence_usage(&database, &schema, DISBURSEMENTS_SEQUENCE, &role).await, + disbursements, + "the G2P sequence is granted when a disbursement connection is declared, not before" + ); + let schema_privileges = connect(&database) + .await + .query_one( + "SELECT has_schema_privilege($1, $2, 'USAGE'), has_schema_privilege($1, $2, 'CREATE')", + &[&role, &schema], + ) + .await + .expect("read the schema privileges"); + assert!(schema_privileges.get::<_, bool>(0), "USAGE on the schema"); assert!( - stderr.contains("SELECT, INSERT, UPDATE on adapter_idempotency_async_artifacts"), + !schema_privileges.get::<_, bool>(1), + "no CREATE on the schema" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::from([role.clone()]), + "the runtime role is the only grantee, and PUBLIC gained nothing" + ); + drop(serving); + drop_role(&database, &role).await; +} + +#[tokio::test] +async fn serve_grants_the_collection_tables_beside_a_project() { + assert_payments_grants_exactly(PaymentHost::BesideFacade, false, "grants-pay-facade").await; +} + +#[tokio::test] +async fn serve_grants_the_g2p_tables_when_disbursements_are_declared_beside_a_project() { + assert_payments_grants_exactly(PaymentHost::BesideFacade, true, "grants-g2p-facade").await; +} + +#[tokio::test] +async fn the_payments_only_host_grants_the_collection_tables_and_schema_usage() { + assert_payments_grants_exactly(PaymentHost::Alone, false, "grants-pay-alone").await; +} + +#[tokio::test] +async fn the_payments_only_host_grants_the_g2p_tables_when_disbursements_are_declared() { + assert_payments_grants_exactly(PaymentHost::Alone, true, "grants-g2p-alone").await; +} + +/// One role on both sessions owns the payment tables and issues no grant. +#[tokio::test] +async fn a_single_role_payments_host_issues_no_grant() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-single").await; + let schema = current_schema(&database).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let mut serving = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + serving.wait_until_listening(); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "no role other than the owner holds anything" + ); + drop(serving); +} + +/// A runtime role with a plain member inherits what it is granted, so the +/// payment tables are granted nothing and startup refuses as it does without +/// the grant step. +#[tokio::test] +async fn a_payments_runtime_role_with_members_is_granted_nothing_and_refused() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-members").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let member = format!("{schema}_member"); + create_login_role(&database, &role).await; + create_login_role(&database, &member).await; + execute(&database, &format!("GRANT {role} TO {member};")).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + + let stderr = + SplitRoles::spawn_payments(&database, &runtime_url, None, &payments, &packs).refusal(); + assert!( + stderr.contains("payment runtime role lacks required table or sequence privileges"), "{stderr}" ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "an automatic grant is never made to a role others inherit from: {stderr}" + ); + drop_role(&database, &member).await; + drop_role(&database, &role).await; +} + +/// A migration role that owns the facade tables but not a payment table +/// cannot make that grant: the whole transaction rolls back and the refusal +/// names the privilege and the table. +#[tokio::test] +async fn a_migration_role_that_does_not_own_a_payment_table_fails_startup_and_grants_nothing() { + let upstream = UpstreamDouble::start(); + let database = migrated_schema( + &upstream, + &Served::govstack_project(), + "grants-pay-nonowner", + ) + .await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), false); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + // Create the payment tables as the test database's own role first, so the + // migrator owns none of them. The payments-only host then migrates as the + // migrator, which finds them in place. + let mut alone = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + alone.wait_until_listening(); + drop(alone); + execute( + &database, + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL SEQUENCES IN SCHEMA {schema} TO {migrator};" + ), + ) + .await; + + let stderr = + SplitRoles::spawn_payments(&migration_url, &runtime_url, None, &payments, &packs).refusal(); assert!( - stderr.contains("SELECT, INSERT on adapter_idempotency_resume_bindings"), + stderr.contains("SELECT, INSERT, UPDATE on adapter_payment_attempts"), "{stderr}" ); + assert!( + stderr.contains("the migration role does not own"), + "{stderr}" + ); + assert!(!stderr.contains(RUNTIME_PASSWORD), "{stderr}"); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "a failed grant leaves nothing behind: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; +} - execute(&database, &RECOVERY_GRANTS.replace("{role}", &role)).await; - let mut serving = spawn(); - serving.wait_until_listening(); - drop(serving); +/// A payments configuration the host refuses (a credential reference that +/// resolves to nothing) settles before any database work, so nothing is +/// granted, beside a project or alone. +async fn assert_refused_payments_grant_nothing(host: PaymentHost, deployment: &str) { + let upstream = UpstreamDouble::start(); + let database = migrated_schema(&upstream, &Served::govstack_project(), deployment).await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + create_login_role(&database, &role).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), true); + let refused = std::fs::read_to_string(&payments) + .expect("read the payments configuration") + .replace( + "secret:env/TEST_PAYMENT_TOKEN", + "secret:env/TEST_PAYMENT_ABSENT", + ); + std::fs::write(&payments, refused).expect("write the refused configuration"); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + let facade = match host { + PaymentHost::BesideFacade => Some((upstream_url.as_str(), govstack.as_path())), + PaymentHost::Alone => None, + }; + + let stderr = + SplitRoles::spawn_payments(&database, &runtime_url, facade, &payments, &packs).refusal(); + assert!( + stderr.contains("a payment credential could not be resolved"), + "{stderr}" + ); + assert_eq!( + acl_grantees(&database, &schema).await, + std::collections::BTreeSet::new(), + "a refused payments configuration grants nothing: {stderr}" + ); + drop_role(&database, &role).await; +} + +#[tokio::test] +async fn a_refused_payments_configuration_grants_nothing_beside_a_project() { + assert_refused_payments_grant_nothing(PaymentHost::BesideFacade, "grants-refused-facade").await; +} + +#[tokio::test] +async fn a_refused_payments_configuration_grants_nothing_when_served_alone() { + assert_refused_payments_grant_nothing(PaymentHost::Alone, "grants-refused-alone").await; +} + +/// The payment grants share the facade tables' transaction: the migration role +/// owns the facade tables but not the payment tables, so the facade grants, +/// which would succeed alone, roll back with the payment ones. +#[tokio::test] +async fn payment_grants_commit_with_the_facade_grants_or_not_at_all() { + let upstream = UpstreamDouble::start(); + let database = + migrated_schema(&upstream, &Served::govstack_project(), "grants-pay-atomic").await; + let schema = current_schema(&database).await; + let role = format!("{schema}_runtime"); + let migrator = format!("{schema}_migrator"); + create_login_role(&database, &role).await; + create_login_role(&database, &migrator).await; + let directory = tempfile::tempdir().expect("a scratch directory"); + let (payments, packs) = payments_fixture(directory.path(), false); + let packs: Vec<&Path> = packs.iter().map(std::path::PathBuf::as_path).collect(); + // Create the payment tables as the test database's own role, then hand + // every other table to the migrator. + let mut creator = SplitRoles::spawn_payments(&database, &database, None, &payments, &packs); + creator.wait_until_listening(); + drop(creator); execute( &database, - &format!("DROP OWNED BY {role}; DROP ROLE {role};"), + &format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL TABLES IN SCHEMA {schema} TO {migrator}; \ + GRANT ALL ON ALL SEQUENCES IN SCHEMA {schema} TO {migrator}; \ + DO $$ DECLARE t text; BEGIN \ + FOR t IN SELECT tablename FROM pg_tables WHERE schemaname = '{schema}' \ + AND tablename NOT LIKE 'adapter\\_payment\\_%' AND tablename NOT LIKE 'adapter\\_g2p\\_%' \ + LOOP EXECUTE format('ALTER TABLE {schema}.%I OWNER TO {migrator}', t); END LOOP; \ + END $$;" + ), ) .await; + let migration_url = as_role(&database, &migrator); + let runtime_url = as_role(&database, &role); + let upstream_url = upstream.url(""); + let govstack = Served::govstack_project(); + + let stderr = SplitRoles::spawn_payments( + &migration_url, + &runtime_url, + Some((upstream_url.as_str(), govstack.as_path())), + &payments, + &packs, + ) + .refusal(); + assert!(stderr.contains("on adapter_payment_attempts"), "{stderr}"); + assert!( + !acl_grantees(&database, &schema).await.contains(&role), + "the facade grants rolled back with the payment ones: {stderr}" + ); + drop_role(&database, &migrator).await; + drop_role(&database, &role).await; } diff --git a/crates/registry-adapter/tests/records_get_served.rs b/crates/registry-adapter/tests/records_get_served.rs index 849747aa49..b3f2ac1757 100644 --- a/crates/registry-adapter/tests/records_get_served.rs +++ b/crates/registry-adapter/tests/records_get_served.rs @@ -420,10 +420,14 @@ async fn every_401_path_leaves_a_value_free_log_line() { assert_eq!(status, 401); let stderr = served.stop_and_read_stderr(); - for stage in ["header", "client", "profile"] { + for check in [ + "credential-missing", + "token-assertion-issuer", + "token-claims", + ] { assert!( - stderr.contains(&format!("\"stage\":\"{stage}\"")), - "no {stage}-stage refusal was logged: {stderr}" + stderr.contains(&format!("\"failed_check\":\"{check}\"")), + "no {check} refusal was logged: {stderr}" ); } assert!( diff --git a/crates/registry-adapterctl/Cargo.toml b/crates/registry-adapterctl/Cargo.toml index ea6fa6f302..0432882102 100644 --- a/crates/registry-adapterctl/Cargo.toml +++ b/crates/registry-adapterctl/Cargo.toml @@ -19,6 +19,10 @@ workspace = true # Enables only the platform's pinned-loopback HTTPS profile for the real TLS # verify tests. Default and release builds retain production address policy. tls-test = ["registry-platform-httputil/test-support"] +# Gates the suite that needs a disposable PostgreSQL server offering verified +# TLS (tests/provision_postgres.rs), so a plain cargo test run never fails +# for want of one and never silently skips it either. +postgres-test = [] [dependencies] base64.workspace = true @@ -37,6 +41,7 @@ registry-payment-mifos-connector.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config = { workspace = true, features = ["schema"] } registry-platform-httputil.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-script.workspace = true registry-platform-yaml.workspace = true schemars.workspace = true @@ -48,6 +53,13 @@ zeroize.workspace = true [dev-dependencies] jsonschema.workspace = true rcgen.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } registry-record.workspace = true tempfile.workspace = true +tokio-postgres.workspace = true tokio-rustls.workspace = true +uuid.workspace = true + +[[test]] +name = "provision_postgres" +required-features = ["postgres-test"] diff --git a/crates/registry-adapterctl/src/check.rs b/crates/registry-adapterctl/src/check.rs index 525b06e4d5..73ae644487 100644 --- a/crates/registry-adapterctl/src/check.rs +++ b/crates/registry-adapterctl/src/check.rs @@ -850,7 +850,7 @@ pub(crate) fn read_runtime( path: shown.clone(), source, })?; - let loader = RuntimeConfigLoader::new(RuntimeEnvelope { + let loader = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: ADAPTER_RUNTIME_API_VERSION, kind: ADAPTER_RUNTIME_KIND, }) diff --git a/crates/registry-adapterctl/src/compile/document.rs b/crates/registry-adapterctl/src/compile/document.rs index 63e4bcd382..e2729292ff 100644 --- a/crates/registry-adapterctl/src/compile/document.rs +++ b/crates/registry-adapterctl/src/compile/document.rs @@ -254,6 +254,17 @@ pub(crate) fn assemble( } })); } + for (reserved, route) in [ + (registry_platform_httputil::probe::HEALTH_PATH, "health"), + (registry_platform_httputil::probe::READY_PATH, "ready"), + ] { + if paths.contains_key(reserved) { + findings.push(assembly_refusal( + "adapterctl.compile.reserved-path", + &format!("an authored operation collides with the Adapter {route} route"), + )); + } + } if paths.contains_key(well_known_path) { findings.push(assembly_refusal( "adapterctl.compile.reserved-path", @@ -493,23 +504,15 @@ fn openapi_method(method: HttpMethod) -> String { } /// The concrete path of one bound operation: the record type substituted -/// into the record-type parameter's whole segment, every other segment -/// kept as declared. +/// into the record-type parameter's placeholder by the rule the listener and +/// the checks share, every other part kept as declared. fn concrete_path(path: &str, parameter: Option<&str>, record_type: &str) -> String { - let Some(parameter) = parameter else { - return path.to_owned(); - }; - let template = format!("{{{parameter}}}"); - path.split('/') - .map(|segment| { - if segment == template { - record_type.to_owned() - } else { - segment.to_owned() - } - }) - .collect::>() - .join("/") + match parameter { + Some(parameter) => { + registry_adapter_core::concrete_facade_path(path, parameter, record_type) + } + None => path.to_owned(), + } } /// The operation's OpenAPI parameters: the remaining declared path @@ -768,13 +771,18 @@ mod tests { /// One project over that profile, with the given bindings. fn project(bindings: Value) -> AdapterProject { + project_of_record_type("case", bindings) + } + + /// [`project`] with its one record type named `record_type`. + fn project_of_record_type(record_type: &str, bindings: Value) -> AdapterProject { serde_json::from_value(json!({ "project": {"id": "case-deployment", "version": "1"}, "profile": {"id": "case-api", "version": "1", "digest": PINNED_DIGEST}, "pack": {"id": "case-api-pack", "version": "1", "digest": PINNED_DIGEST}, "recordTypes": [ { - "name": "case", + "name": record_type, "fields": [ {"name": "case_type", "type": "string", "required": true}, {"name": "severity", "type": "integer"}, @@ -1305,6 +1313,21 @@ mod tests { ); } + /// The compiled path is the one the listener serves, whether the + /// record-type placeholder fills a segment or sits inside one. + #[test] + fn the_concrete_path_follows_the_shared_substitution_rule() { + assert_eq!( + concrete_path("/v1/{type}/{id}", Some("type"), "case"), + "/v1/case/{id}" + ); + assert_eq!( + concrete_path("/v1/{type}.json", Some("type"), "case"), + "/v1/case.json" + ); + assert_eq!(concrete_path("/v1/{type}", None, "case"), "/v1/{type}"); + } + /// Two bindings whose concrete paths collide refuse the assembly with /// the collision finding. #[test] @@ -1333,6 +1356,49 @@ mod tests { assert_eq!(findings[0].code, "adapterctl.compile.path-collision"); } + /// A binding whose concrete path is the health or ready route refuses the + /// assembly, because the listener answers those routes itself. + #[test] + fn a_concrete_path_equal_to_the_health_or_ready_route_refuses() { + let mut declared = profile_value(); + declared["operations"][1]["path"] = json!("/{type}"); + let profile: AdapterProfile = + serde_json::from_value(declared).expect("the profile decodes"); + for (record_type, route) in [("health", "health"), ("ready", "ready")] { + let findings = assemble( + &profile, + &project_of_record_type( + record_type, + json!([{ + "id": "case-find", + "operation": "cases-find", + "recordType": record_type, + "route": "case-find", + "maximumUpstreamCalls": 11, + }]), + ), + ) + .expect_err("the reserved path refuses"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!(findings[0].code, "adapterctl.compile.reserved-path"); + assert!(findings[0].message.contains(route), "{findings:?}"); + } + assemble( + &profile, + &project_of_record_type( + "cases", + json!([{ + "id": "case-find", + "operation": "cases-find", + "recordType": "cases", + "route": "case-find", + "maximumUpstreamCalls": 11, + }]), + ), + ) + .expect("an ordinary record type compiles"); + } + /// The same authored bytes compile to the same rendered bytes. #[test] fn the_document_is_deterministic() { diff --git a/crates/registry-adapterctl/src/lib.rs b/crates/registry-adapterctl/src/lib.rs index 97bf7ce62c..eefaa46d3b 100644 --- a/crates/registry-adapterctl/src/lib.rs +++ b/crates/registry-adapterctl/src/lib.rs @@ -5,7 +5,7 @@ //! This crate owns the `adapterctl` binary. Its commands: `check`, the //! offline check over authored artifacts (project, profile, pack, fixtures, //! and with `--runtime` the runtime config); `job check`, the offline -//! compile of one ingestion job; `job lock`, the job's pin rewriter; `mapping check`, `mapping generate`, and +//! compile of one ingestion job; `provision`, the creation of the roles and the database the runtime file names; `job lock`, the job's pin rewriter; `mapping check`, `mapping generate`, and //! `mapping preview`, the checks, script generator, and offline preview of //! an `AdapterMapping` model; `project lock`, the pin rewriter; `schemas`, the generator and drift gate of the Adapter format //! JSON Schemas; `compile`, the per-deployment contract compiler; @@ -25,6 +25,7 @@ mod mapping; mod payment_fixtures; mod payments; mod project; +mod provision; mod report; mod schemas; mod verify; @@ -70,6 +71,8 @@ enum Command { Project(project::ProjectArgs), /// Check typed payment connections or export their fixed operation contract. Payments(payments::PaymentsArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Write the generated JSON Schemas of every Adapter format, or /// check the committed ones for drift. Schemas(schemas::SchemasArgs), @@ -144,6 +147,9 @@ where } }; let Cli { format, command } = cli; + if let Command::Provision(args) = &command { + return provision(args, format); + } let command_name = match &command { Command::Check(_) => "check", Command::Job(job) => match job.command { @@ -154,6 +160,7 @@ where Command::Project(project) => match project.command { project::ProjectCommand::Lock(_) => "project lock", }, + Command::Provision(_) => "provision", Command::Schemas(_) => "schemas", Command::Payments(args) => payments::command_name(&args.command), Command::Compile(_) => "compile", @@ -172,6 +179,7 @@ where }, Command::Mapping(args) => mapping_command(args, format, command_name, stdout, stderr), Command::Project(args) => project_command(args, format, command_name, stdout, stderr), + Command::Provision(_) => unreachable!("provision writes its own report above"), Command::Schemas(args) => schemas_command(args, format, command_name, stdout, stderr), Command::Payments(args) => payments_command(args, format, command_name, stdout, stderr), Command::Compile(args) => compile_command(args, format, command_name, stdout, stderr), @@ -184,6 +192,23 @@ where } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "adapterctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn usage_failure(message: String) -> Value { failure( "usage", diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index f887d2d466..95faf7f666 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -254,7 +254,7 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { }; } }; - let check = RuntimeConfigLoader::new(RuntimeEnvelope { + let check = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs new file mode 100644 index 0000000000..a53ee854da --- /dev/null +++ b/crates/registry-adapterctl/src/provision.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision`: the shared command over the Adapter's runtime +//! file. The file's two database URLs name the roles, the database and both +//! passwords, so nothing is written twice. + +use std::path::Path; + +use registry_adapter_core::{ + AdapterRuntimeConfig, ADAPTER_REMOVED_KEYS, ADAPTER_RUNTIME_API_VERSION, ADAPTER_RUNTIME_KIND, +}; +use registry_platform_config::{ + describe_secret_failure, RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, +}; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// The Adapter keeps its tables in the schema on the migration role's search +/// path, handed to the migration role, and needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "adapter", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(ADAPTER_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `adapter serve` does and resolves the +/// two database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::fs::canonicalize(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be read".to_owned(), + "Pass --runtime-config as a path to the runtime file.", + ) + })?; + let config = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { + api_version: ADAPTER_RUNTIME_API_VERSION, + kind: ADAPTER_RUNTIME_KIND, + }) + .removed_keys(ADAPTER_REMOVED_KEYS) + .load::(&absolute) + .map_err(|error| Box::new(error.deciding_diagnostic().clone()))? + .config; + let secrets = match config.secret_providers.as_ref() { + Some(providers) => providers.resolver(), + None => SecretResolver::new([SecretProvider::Environment], ""), + } + .map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-adapterctl/src/verify/mod.rs b/crates/registry-adapterctl/src/verify/mod.rs index 26349c968f..e38b5eae2f 100644 --- a/crates/registry-adapterctl/src/verify/mod.rs +++ b/crates/registry-adapterctl/src/verify/mod.rs @@ -45,7 +45,7 @@ use registry_adapter_core::{ }; use registry_platform_config::{SecretProvider, SecretResolver}; use registry_platform_httputil::destination::{ - DataDestinationPolicy, DestinationProfile, DestinationTlsMaterial, + DataDestinationPolicy, DestinationPolicyError, DestinationProfile, DestinationTlsMaterial, MAX_DESTINATION_CA_BUNDLE_BYTES, }; use registry_platform_yaml::{Diagnostic, Report, SecretReference, Url}; @@ -833,9 +833,7 @@ fn destination_policy( profile, &networks, ) - .map_err(|_| { - EgressFault::Refused("the destination is not admitted by the frozen policy".to_owned()) - })?; + .map_err(|error| EgressFault::Refused(destination_refusal(&error)))?; if let Some(profile) = &binding.tls_trust_profile { let bundle = resolve_ca_bundle(runtime, profile.as_str()).map_err(|_| { EgressFault::Refused( @@ -856,6 +854,16 @@ fn destination_policy( Ok(policy) } +/// The report text for a refused destination. An empty private range list +/// keeps the platform's own text, which says how to fix it. Any other refusal +/// is a fixed sentence, so the report never repeats an origin. +fn destination_refusal(error: &DestinationPolicyError) -> String { + match error { + DestinationPolicyError::PrivateServiceRequiresPrivateCidr => error.to_string(), + _ => "the destination is not admitted by the frozen policy".to_owned(), + } +} + fn destination_profile(base: &Url) -> DestinationProfile { let parsed = base.to_url(); #[cfg(feature = "tls-test")] @@ -864,19 +872,16 @@ fn destination_profile(base: &Url) -> DestinationProfile { } match parsed.scheme() { "https" => DestinationProfile::ProductionHttps, - _ if denotes_loopback(base) => DestinationProfile::LoopbackDevelopmentHttp, + _ if denotes_loopback(base) => DestinationProfile::LoopbackHttp, _ => DestinationProfile::PrivateServiceHttp, } } fn denotes_loopback(origin: &Url) -> bool { - let parsed = origin.to_url(); - parsed.host_str().is_some_and(|host| { - host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|address| address.is_loopback()) - }) + origin + .to_url() + .host_str() + .is_some_and(|host| registry_platform_httputil::loopback::loopback_host(host).is_some()) } /// Read one declared CA bundle under the platform ceiling. Every failure is @@ -1173,6 +1178,17 @@ mod tests { ); } + #[test] + fn an_empty_private_range_list_keeps_the_platform_remedy() { + let message = + destination_refusal(&DestinationPolicyError::PrivateServiceRequiresPrivateCidr); + assert!(message.contains("name the range"), "{message}"); + assert_eq!( + destination_refusal(&DestinationPolicyError::OriginMissingPort), + "the destination is not admitted by the frozen policy" + ); + } + #[test] fn live_facade_probe_does_not_drive_evidence_extract_sends() { let pack: AdapterPack = serde_json::from_value( diff --git a/crates/registry-adapterctl/tests/compile.rs b/crates/registry-adapterctl/tests/compile.rs index d09f22ff2e..6a972dff36 100644 --- a/crates/registry-adapterctl/tests/compile.rs +++ b/crates/registry-adapterctl/tests/compile.rs @@ -609,8 +609,9 @@ fn the_document_keeps_the_breg_generated_shape() { assert_eq!(document["openapi"], breg["openapi"]); assert_eq!( - document["components"]["securitySchemes"], breg["components"]["securitySchemes"], - "the same bearer scheme BReg serves" + document["components"]["securitySchemes"], + json!({"bearerAuth": breg["components"]["securitySchemes"]["bearerAuth"]}), + "the facade publishes the bearer scheme BReg serves on record routes" ); // BReg enumerates concrete record paths (`/v1/records/contacts`); the // adapter's paths are concrete the same way, with no `{type}` diff --git a/crates/registry-adapterctl/tests/provision_cli.rs b/crates/registry-adapterctl/tests/provision_cli.rs new file mode 100644 index 0000000000..58d817126c --- /dev/null +++ b/crates/registry-adapterctl/tests/provision_cli.rs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; +const CURSOR_KEY: &str = "synthetic-cursor-key-0123456789!"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!("postgresql://adapter_migration:{MIGRATION_PASSWORD}@db.invalid:5432/adapter"), + ), + ( + "runtime-database-url", + format!("postgresql://adapter_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/adapter"), + ), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ("cursor-key", CURSOR_KEY.to_owned()), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 +kind: AdapterRuntimeConfig +id: adapter-provision-cli-test +endpoints: + - endpoint: tracker + baseUrl: https://192.168.1.10 + credential: + type: basic + usernameRef: secret:file/jwks.json + passwordRef: secret:file/jwks.json +secretProviders: + file: + root: {secrets} +listener: + bind: 127.0.0.1:0 +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +oidc: + issuer: https://identity.example.test + audience: urn:example:adapter + jwksSource: + type: static + documentRef: secret:file/jwks.json +allowedClients: + - provision-test-client +allowedPrivateCidrs: + - 192.168.0.0/16 +audit: + retentionDays: 90 +idempotency: + responseRetentionSeconds: 86400 +cursorKeyRef: secret:file/cursor-key +", + secrets = secrets.display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_adapterctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["adapter_migration", "adapter_runtime", "adapter"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "adapter"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "adapter"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } +} + +#[test] +fn a_runtime_file_the_loader_refuses_is_reported_without_connecting() { + let directory = scratch(); + let runtime = directory.path().join("runtime.yaml"); + std::fs::write(&runtime, "kind: AdapterRuntimeConfig\n").unwrap(); + std::fs::set_permissions(&runtime, std::fs::Permissions::from_mode(0o600)).unwrap(); + let output = ctl(&[ + "provision", + "--runtime-config", + runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_ne!(output.status.code(), Some(0)); + assert!(output.stdout.is_empty()); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "ADAPTER_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "ADAPTER_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} diff --git a/crates/registry-adapterctl/tests/provision_postgres.rs b/crates/registry-adapterctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..031e68ae79 --- /dev/null +++ b/crates/registry-adapterctl/tests/provision_postgres.rs @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `adapterctl provision` against a real server, then `adapter serve` on what +//! it created: the facade migrates as the migration role, grants the runtime +//! role what its deployment uses, and listens with split roles and no hand +//! SQL. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +const CURSOR_KEY: &str = "synthetic-cursor-key-0123456789!"; + +fn repository(relative: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(relative) +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_adapterctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it, from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `adapter serve` then +/// migrates over the migration credential, grants the runtime role its +/// privileges, and answers a request over the runtime credential. +#[tokio::test] +async fn provision_then_serve_with_split_roles() { + let (base_url, ca) = provision_test_env(); + let admin = connect_verified(&base_url, &ca, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let secret = |name: &str, value: &str| { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + }; + secret("cursor-key", CURSOR_KEY); + secret("upstream-user", "upstream-user"); + secret("upstream-password", "upstream-password"); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + let runtime_file = directory.path().join("runtime.yaml"); + std::fs::write( + &runtime_file, + format!( + "\ +apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 +kind: AdapterRuntimeConfig +id: adapter-provision-test +endpoints: + - endpoint: tracker + baseUrl: https://192.168.1.10 + credential: + type: basic + usernameRef: secret:file/upstream-user + passwordRef: secret:file/upstream-password +secretProviders: + file: + root: {secrets} +listener: + bind: {bind} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +oidc: + issuer: https://identity.example.test + audience: urn:example:adapter + jwksSource: + type: static + documentRef: secret:file/jwks.json +allowedClients: + - provision-test-client +allowedPrivateCidrs: + - 192.168.0.0/16 +audit: + retentionDays: 90 +idempotency: + responseRetentionSeconds: 86400 +cursorKeyRef: secret:file/cursor-key +", + secrets = secrets.display(), + ), + ) + .unwrap(); + let runtime = runtime_file.display().to_string(); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("adapter_owner_{suffix}"), + format!("adapter_mig_{suffix}"), + format!("adapter_rt_{suffix}"), + format!("adapter_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, db_port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{db_port}/{database}") + }; + secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = directory.path().join("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + + let server = tokio::spawn({ + let project = repository("products/adapter/examples/dhis2-tracker"); + let profile = repository("products/adapter/profiles/breg-records/profile.yaml"); + let pack = repository("products/adapter/packs/dhis2-tracker/pack.yaml"); + let runtime = runtime_file.clone(); + async move { + registry_adapter::serve::run(&project, Some(&profile), Some(&pack), &runtime).await + } + }); + // An unauthenticated request reaches the facade and is refused by its + // authenticator, so a 401 shows the runtime role serving. + let route = "/.well-known/registry-adapter/effective-contract"; + let mut status = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + status = http_status(&bind, route).await; + if status.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the facade stopped instead of serving: {outcome:?}"); + } + assert_eq!(status, Some(401), "the facade never answered"); + server.abort(); + + // The runtime role holds what the deployment uses and nothing on the + // migration ledger of the idempotency store. + let runtime_session = + connect_verified(&url(&runtime_role, &runtime_password, &database), &ca, None).await; + let granted = runtime_session + .query_one( + "SELECT has_table_privilege(current_user, 'adapter_journal_events', 'INSERT'), \ + has_table_privilege(current_user, 'adapter_idempotency_schema_migrations', 'SELECT')", + &[], + ) + .await + .unwrap(); + assert!(granted.get::<_, bool>(0), "the journal is writable"); + assert!( + !granted.get::<_, bool>(1), + "the idempotency migration ledger is not readable" + ); + drop(runtime_session); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-breg-client-node/README.md b/crates/registry-breg-client-node/README.md index 430260b0d0..7959bb82a4 100644 --- a/crates/registry-breg-client-node/README.md +++ b/crates/registry-breg-client-node/README.md @@ -39,27 +39,21 @@ not expose token, private-key, record, or Proposal payload values. ## Hook verification -`verifyHookDelivery({ method, path, headers, body, key })` authenticates one -exact Base Registry Engine Version 1 delivery with the shared Rust verifier. -Header lookup is case-insensitive. The result carries the CloudEvents -attributes, generation, attempt, delivery time, idempotency key, and exact body. -Generation and attempt remain decimal strings so the Node number boundary -cannot round a signed value. - -Body and key buffers must not use a shared backing store. Accepted buffers are -copied before native verification so another worker cannot change the bytes -being authenticated. - -The helper does not apply clock-skew or deduplication policy. Bound the returned -`deliveryTime` against the receiver clock. `idempotencyKey` collapses automatic -retries within one delivery generation; an effect that must remain once-only -across operator replay uses a durable apply-once operation keyed by authenticated -`source` plus `id`, or by an application business key, before acting on `body`. - -Refusal throws `BaseRegistryClientError` with kind `hook-verification` and a -code from `missing-header`, `invalid-delivery-time`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version`. -The message names the input to check and never includes a header value, body, -or key. +`verifyHookDelivery({ headers, body, key, previousKey })` authenticates one +Base Registry Engine Standard Webhooks delivery with the shared Rust verifier. +Header names are case-insensitive. Supply the body and keys as Buffers. The wrapper refuses shared backing stores and copies the buffers before verification. +The optional previous key supports rotation. A key contains 32 to 64 exact bytes. + +The result contains the authenticated `id`, `timestamp` (a decimal string of signed Unix seconds), +`source`, `type`, `time`, `dataschema`, and exact `body`. Deduplicate on `source` and +`id` before acting. Retries and operator replays preserve the id. + +The default window is 300 seconds in either direction. Choose `maxSkewSeconds` +(1 to 3600 seconds) for a custom window or `callerEnforcedFreshness: true` to enforce freshness yourself. + +A refusal raises `BaseRegistryClientError` with kind `hook-verification` and one of +`missing-header`, `duplicate-header`, `invalid-content-type`, `invalid-id`, `invalid-timestamp`, `stale-delivery`, `malformed-signature`, `unsupported-version`, `signature-mismatch`, `body-too-large`, `invalid-key`, `invalid-envelope`, or `id-mismatch`. +The message names what to check without exposing header values, body, or keys. ## Exact values and application metadata diff --git a/crates/registry-breg-client-node/__test__/facade.test-d.ts b/crates/registry-breg-client-node/__test__/facade.test-d.ts index 05346b4a2a..9dd5dd97a5 100644 --- a/crates/registry-breg-client-node/__test__/facade.test-d.ts +++ b/crates/registry-breg-client-node/__test__/facade.test-d.ts @@ -120,28 +120,30 @@ if (metadata.statisticalDatasets !== null) { } const verifiedHook: VerifiedHookDelivery = verifyHookDelivery({ - method: 'POST', - path: '/hooks/registry', - headers: { 'X-Registry-Signature': 'v1=opaque' }, + headers: { 'webhook-signature': 'v1,opaque' }, body: Buffer.from('{}'), key: Buffer.alloc(32), + previousKey: Buffer.alloc(32, 1), }) verifiedHook.id.toUpperCase() verifiedHook.source.toUpperCase() verifiedHook.type.toUpperCase() verifiedHook.time.toUpperCase() verifiedHook.dataschema.toUpperCase() -verifiedHook.generation.toUpperCase() -verifiedHook.attempt.toUpperCase() -verifiedHook.deliveryTime.toUpperCase() -verifiedHook.idempotencyKey.toUpperCase() +verifiedHook.timestamp.toUpperCase() verifiedHook.body.byteLength.toFixed() const webhookRefusal: HookVerificationRefusalCode = 'signature-mismatch' webhookRefusal.toUpperCase() +const staleRefusal: HookVerificationRefusalCode = 'stale-delivery' +staleRefusal.toUpperCase() +verifyHookDelivery({ headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), maxSkewSeconds: 60 }) +verifyHookDelivery({ headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), callerEnforcedFreshness: true }) +// @ts-expect-error The window is a number of seconds. +verifyHookDelivery({ headers: {}, body: Buffer.from('{}'), key: Buffer.alloc(32), maxSkewSeconds: '60' }) // @ts-expect-error Hook bodies must remain exact bytes. -verifyHookDelivery({ method: 'POST', path: '/', headers: {}, body: '{}', key: Buffer.alloc(32) }) +verifyHookDelivery({ headers: {}, body: '{}', key: Buffer.alloc(32) }) // @ts-expect-error Header values must be exact strings. -verifyHookDelivery({ method: 'POST', path: '/', headers: { 'ce-id': 1 }, body: Buffer.from('{}'), key: Buffer.alloc(32) }) +verifyHookDelivery({ headers: { 'webhook-id': 1 }, body: Buffer.from('{}'), key: Buffer.alloc(32) }) const options: ListOptions = { top: 25, filter: 'status eq active', count: true, bbox: ['100.1', '13.1', '100.2', '13.2'] } client.listRecords('people', options) diff --git a/crates/registry-breg-client-node/__test__/webhook-verification.test.js b/crates/registry-breg-client-node/__test__/webhook-verification.test.js index 35fbaf10a8..783e43e6ac 100644 --- a/crates/registry-breg-client-node/__test__/webhook-verification.test.js +++ b/crates/registry-breg-client-node/__test__/webhook-verification.test.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('node:assert/strict'); +const { createHmac } = require('node:crypto'); const { test } = require('node:test'); const { @@ -9,168 +10,150 @@ const { } = process.env.BREG_CLIENT_PACKAGE ? require(process.env.BREG_CLIENT_PACKAGE).breg : require('..'); -const key = Buffer.from('webhook-delivery-signing-key-0123456789abcdef'); -const body = Buffer.from('{"entity":"case","values":{"label":"value"}}'); -const signature = 'v1=OzL5k0ghZJb9nPbb-JOVsroWeanipBlZXbeKDd52RcM'; +const key = Buffer.from('0123456789abcdef0123456789abcdef'); +const previousKey = Buffer.from('abcdef0123456789abcdef0123456789'); +const body = Buffer.from('{"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{},"dataschema":"https://example.test/schema","id":"00000000-0000-4000-8000-000000000001","source":"/products/breg/deployments/example","subject":{"recordReference":"breg/case/42","recordRevision":7},"time":"2026-08-30T00:00:00.123Z","type":"case-created-v1"}'); +const signature = 'v1,NELq97rzqnAqQUxh1eiskBB3oOl+4FsqaI1ZV/lAqQY='; +const { id, source, type, time, dataschema } = JSON.parse(body); +const timestamp = '1788048001'; -function headers() { +function signedHeaders(stamp = timestamp, signingKey = key, eventId = id, payload = body) { + const digest = createHmac('sha256', signingKey).update(`${eventId}.${stamp}.`) + .update(payload).digest('base64'); return { - 'Ce-Specversion': '1.0', - 'CE-ID': '00000000-0000-4000-8000-000000000001', - 'ce-source': 'urn:registrystack:registry:example:instance:primary', - 'ce-type': 'case-created-v1', - 'ce-time': '2026-08-30T00:00:00Z', - 'ce-dataschema': 'urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa', - 'x-registry-event-generation': '1', - 'x-registry-delivery-attempt': '1', - 'x-registry-delivery-time': '2026-08-30T00:00:01Z', - 'idempotency-key': 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - 'content-type': 'application/json', - 'x-registry-signature': signature, + 'Content-Type': 'application/json', + 'Webhook-ID': eventId, + 'webhook-timestamp': String(stamp), + 'webhook-signature': `v1,${digest}`, }; } function input(overrides = {}) { - return { - method: 'POST', - path: '/hooks/registry', - headers: headers(), - body, - key, - ...overrides, - }; + return { headers: signedHeaders(), body, key, callerEnforcedFreshness: true, ...overrides }; } -test('shared language vectors authenticate exact RFC3339 fractions', () => { - const vectors = require('../../registry-platform-crypto/tests/fixtures/delivery-signatures.json'); - for (const vector of vectors) { - const exact = { ...headers(), 'x-registry-delivery-time': vector.deliveryTime, 'x-registry-signature': vector.signature }; - if (vector.valid) { - assert.equal(verifyHookDelivery(input({ headers: exact })).deliveryTime, vector.deliveryTime); - assert.throws(() => verifyHookDelivery(input({ headers: { ...exact, 'x-registry-delivery-time': '2026-08-30T00:00:01.0000Z' } })), assertRefusal('signature-mismatch')); - } else { - assert.throws(() => verifyHookDelivery(input({ headers: exact })), assertRefusal('invalid-delivery-time')); - } - } -}); +function fresh(offset, overrides = {}) { + return input({ + headers: signedHeaders(Math.floor(Date.now() / 1000) + offset), + callerEnforcedFreshness: undefined, + ...overrides, + }); +} function assertRefusal(code) { return (error) => error instanceof BaseRegistryClientError - && error.kind === 'hook-verification' - && error.code === code - && !error.message.includes(signature) - && !error.message.includes(key.toString()); -} - -function assertExactRefusal(code, message) { - return (error) => assertRefusal(code)(error) && error.message === message; + && error.kind === 'hook-verification' && error.code === code + && !error.message.includes(signature) && !error.message.includes(key.toString()); } -test('accepts the fixed BReg signing vector and returns exact delivery values', () => { - const verified = verifyHookDelivery(input()); - - assert.deepEqual(verified, { - id: '00000000-0000-4000-8000-000000000001', - source: 'urn:registrystack:registry:example:instance:primary', - type: 'case-created-v1', - time: '2026-08-30T00:00:00Z', - dataschema: 'urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa', - generation: '1', - attempt: '1', - deliveryTime: '2026-08-30T00:00:01Z', - idempotencyKey: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - body, - }); - assert.ok(Buffer.isBuffer(verified.body)); +test('accepts the fixed standard webhook envelope vector', () => { + assert.equal(signedHeaders()['webhook-signature'], signature); + assert.deepEqual(verifyHookDelivery(input()), { id, timestamp, source, type, time, dataschema, body }); }); -test('refuses a tampered signed header', () => { - assert.throws(() => verifyHookDelivery(input({ - headers: { ...headers(), 'ce-type': 'case-patched-v1' }, - })), assertRefusal('signature-mismatch')); +test('checks the shared signature vectors without a wall clock', () => { + const vectors = require('../../registry-platform-crypto/tests/fixtures/standard-webhooks.json'); + for (const vector of vectors) { + const { id, timestamp, signature, body, keyHex, previousKeyHex, expected, keyPolicy } = vector; + // Freshness is exercised separately with the live clock. + const code = keyPolicy === 'below-minimum' ? 'invalid-key' + : ['accepted', 'stale-delivery'].includes(expected) ? 'invalid-envelope' : expected; + assert.throws(() => verifyHookDelivery(input({ + headers: { 'content-type': 'application/json', 'webhook-id': id, + 'webhook-timestamp': timestamp, 'webhook-signature': signature }, + body: Buffer.from(body), key: Buffer.from(keyHex, 'hex'), + previousKey: previousKeyHex ? Buffer.from(previousKeyHex, 'hex') : undefined, + })), assertRefusal(code), vector.name); + } }); -test('refuses a tampered body', () => { - assert.throws( - () => verifyHookDelivery(input({ body: Buffer.from('{"tampered":true}') })), - assertRefusal('signature-mismatch'), - ); +test('accepts a signature made with the previous key', () => { + const headers = signedHeaders(timestamp, previousKey); + assert.throws(() => verifyHookDelivery(input({ headers })), assertRefusal('signature-mismatch')); + assert.equal(verifyHookDelivery(input({ headers, previousKey })).id, id); }); -test('refuses the wrong key', () => { - assert.throws( - () => verifyHookDelivery(input({ key: Buffer.alloc(32, 0x6b) })), - assertRefusal('signature-mismatch'), - ); +test('refuses mismatched identity and invalid headers or bytes', () => { + for (const [code, overrides] of [ + ['id-mismatch', { headers: signedHeaders(timestamp, key, '00000000-0000-4000-8000-000000000002') }], + ['duplicate-header', { headers: { ...signedHeaders(), 'webhook-id': id } }], + ['missing-header', { headers: {} }], + ['invalid-content-type', { headers: { ...signedHeaders(), 'Content-Type': 'text/plain' } }], + ['signature-mismatch', { body: Buffer.from('{}') }], + ['body-too-large', { body: Buffer.alloc(1_048_577) }], + ]) { + assert.throws(() => verifyHookDelivery(input(overrides)), assertRefusal(code)); + } }); -test('refuses a truncated signature', () => { - assert.throws(() => verifyHookDelivery(input({ - headers: { ...headers(), 'x-registry-signature': 'v1=truncated' }, - })), assertRefusal('malformed-signature')); +test('names invalid key lengths and kinds without revealing their bytes', () => { + for (const [overrides, message] of [ + [{ key: Buffer.alloc(31, 120) }, 'The current hook key is 31 bytes and must contain 32 to 64 exact bytes.'], + [{ key: Buffer.from('x'.repeat(64) + '\n') }, 'The current hook key is 65 bytes including a trailing newline and must contain 32 to 64 exact bytes.'], + [{ key: Buffer.from('whsec_synthetic_key_text_for_test') }, 'The current hook key starts with whsec_ and must be supplied as exact key bytes.'], + [{ previousKey: key }, 'The previous hook key equals the current key. Pass the key the sender used before rotation, or omit the previous key.'], + ]) { + assert.throws(() => verifyHookDelivery(input(overrides)), + (error) => assertRefusal('invalid-key')(error) && error.message === message); + } }); -test('reports an invalid delivery time with its fix', () => { - const vector = require('../../registry-platform-crypto/tests/fixtures/delivery-signatures.json').find(value => !value.valid); - assert.throws(() => verifyHookDelivery(input({ - headers: { ...headers(), 'x-registry-delivery-time': vector.deliveryTime, 'x-registry-signature': vector.signature }, - })), assertExactRefusal( - 'invalid-delivery-time', - 'the Base Registry Engine hook delivery time is invalid; check the signed delivery time and sender clock', - )); +test('refuses shared backing stores before native verification', () => { + for (const [field, value] of [['body', body], ['key', key], ['previousKey', previousKey]]) { + const shared = Buffer.from(new SharedArrayBuffer(value.length)); + value.copy(shared); + assert.throws( + () => verifyHookDelivery(input({ [field]: shared })), + (error) => error instanceof BaseRegistryClientError && error.kind === 'invalid-request', + ); + } }); -test('reports a duplicate signed header with its fix', () => { - assert.throws(() => verifyHookDelivery(input({ - headers: { ...headers(), 'CE-TYPE': 'case-created-v1' }, - })), assertExactRefusal( - 'duplicate-header', - 'a Base Registry Engine hook header is repeated; remove duplicate signed headers', - )); +test('the default window is 300 seconds in both directions', () => { + for (const offset of [0, -295, 295]) { + assert.equal(verifyHookDelivery(fresh(offset)).id, id); + } + for (const offset of [-305, 305]) { + assert.throws(() => verifyHookDelivery(fresh(offset)), assertRefusal('stale-delivery')); + } }); -test('reports an oversized body with its fix', () => { - assert.throws( - () => verifyHookDelivery(input({ body: Buffer.alloc(1_048_577, 0x78) })), - assertExactRefusal( - 'body-too-large', - 'the Base Registry Engine hook body exceeds the Version 1 limit; reduce the body size', - ), - ); +test('an application that names no window refuses the old fixed vector', () => { + const { callerEnforcedFreshness, ...bare } = input(); + assert.equal(callerEnforcedFreshness, true); + assert.throws(() => verifyHookDelivery(bare), assertRefusal('stale-delivery')); }); -test('reports an invalid key with its fix', () => { +test('maxSkewSeconds replaces the default window', () => { + assert.equal(verifyHookDelivery(fresh(-600, { maxSkewSeconds: 900 })).id, id); assert.throws( - () => verifyHookDelivery(input({ key: Buffer.from('short-key') })), - assertExactRefusal( - 'invalid-key', - 'the Base Registry Engine hook verification key is too short; configure a key of at least 32 bytes', - ), + () => verifyHookDelivery(fresh(-60, { maxSkewSeconds: 10 })), + assertRefusal('stale-delivery'), ); + for (const edge of [1, 3600]) { + assert.equal(verifyHookDelivery(fresh(0, { maxSkewSeconds: edge })).id, id); + } }); -test('refuses an unknown signature version', () => { - assert.throws(() => verifyHookDelivery(input({ - headers: { ...headers(), 'x-registry-signature': signature.replace('v1=', 'v2=') }, - })), assertRefusal('unsupported-version')); -}); - -test('refuses a missing signed header', () => { - const deliveryHeaders = headers(); - delete deliveryHeaders['ce-time']; - assert.throws( - () => verifyHookDelivery(input({ headers: deliveryHeaders })), - assertRefusal('missing-header'), - ); +test('callerEnforcedFreshness accepts an old delivery', () => { + assert.equal(verifyHookDelivery(input()).id, id); }); -test('refuses shared backing stores before native verification', () => { - for (const [field, value] of [['body', body], ['key', key]]) { - const shared = Buffer.from(new SharedArrayBuffer(value.length)); - value.copy(shared); +test('refuses freshness options out of range, mistyped or combined', () => { + for (const overrides of [ + { maxSkewSeconds: 0 }, + { maxSkewSeconds: 3601 }, + { maxSkewSeconds: -1 }, + { maxSkewSeconds: 1.5 }, + { maxSkewSeconds: Number.NaN }, + { maxSkewSeconds: '10' }, + { callerEnforcedFreshness: 'yes' }, + { maxSkewSeconds: 10, callerEnforcedFreshness: true }, + ]) { assert.throws( - () => verifyHookDelivery(input({ [field]: shared })), + () => verifyHookDelivery(fresh(0, overrides)), (error) => error instanceof BaseRegistryClientError && error.kind === 'invalid-request', + JSON.stringify(overrides), ); } }); diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 4c283e7481..0c321103b2 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -14,40 +14,57 @@ export type SafeInteger = number export type HookVerificationRefusalCode = | 'missing-header' - | 'invalid-delivery-time' | 'duplicate-header' - | 'body-too-large' - | 'invalid-key' + | 'invalid-content-type' + | 'invalid-id' + | 'invalid-timestamp' + | 'stale-delivery' | 'malformed-signature' - | 'signature-mismatch' | 'unsupported-version' + | 'signature-mismatch' + | 'body-too-large' + | 'invalid-key' + | 'invalid-envelope' + | 'id-mismatch' export interface HookDeliveryInput { - method: string - path: string headers: Readonly> /** Exact bytes in a non-shared backing store. */ body: Buffer /** Secret bytes in a non-shared backing store. */ key: Buffer + /** Previous secret bytes during key rotation, in a non-shared backing store. */ + previousKey?: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. With + * neither this nor `callerEnforcedFreshness`, the window is 300 seconds. + * Cannot be combined with `callerEnforcedFreshness`. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed. The caller enforces its + * own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } export interface VerifiedHookDelivery { readonly id: string + /** Signed Unix seconds as a decimal string. */ + readonly timestamp: string readonly source: string readonly type: string readonly time: string readonly dataschema: string - readonly generation: string - readonly attempt: string - readonly deliveryTime: string - readonly idempotencyKey: string readonly body: Buffer } /** - * Authenticate one exact Base Registry Engine Version 1 hook delivery. - * Apply delivery-time skew and idempotency policy before acting on the body. + * Authenticate one exact Base Registry Engine Standard Webhooks delivery. The + * delivery time must be within 300 seconds of the receiver clock unless + * `maxSkewSeconds` or `callerEnforcedFreshness` says otherwise; a time outside + * the window is refused with code `stale-delivery`. Deduplicate on source and id + * before acting on the body. */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-breg-client-node/client.js b/crates/registry-breg-client-node/client.js index c5af4483ca..d5fe4108a0 100644 --- a/crates/registry-breg-client-node/client.js +++ b/crates/registry-breg-client-node/client.js @@ -64,7 +64,7 @@ function inputError(kind) { }); } -function plainDataObject(value, expectedFields) { +function plainDataObject(value, expectedFields, optionalFields = []) { if (value === null || typeof value !== 'object' || Array.isArray(value) || isProxy(value)) { throw inputError('invalid-request'); } @@ -72,10 +72,10 @@ function plainDataObject(value, expectedFields) { if (prototype !== Object.prototype && prototype !== null) throw inputError('invalid-request'); const keys = Reflect.ownKeys(value); if (keys.some((key) => typeof key !== 'string') - || keys.length !== expectedFields.length - || keys.some((key) => !expectedFields.includes(key))) throw inputError('invalid-request'); + || keys.some((key) => !expectedFields.includes(key) && !optionalFields.includes(key)) + || expectedFields.some((field) => !keys.includes(field))) throw inputError('invalid-request'); const result = Object.create(null); - for (const field of expectedFields) { + for (const field of keys) { const descriptor = Object.getOwnPropertyDescriptor(value, field); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { throw inputError('invalid-request'); @@ -107,15 +107,24 @@ function hookHeaders(value) { function verifyHookDelivery(value) { try { - const input = plainDataObject(value, ['method', 'path', 'headers', 'body', 'key']); - if (typeof input.method !== 'string' || typeof input.path !== 'string' - || !Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) - || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer)) { + const input = plainDataObject( + value, + ['headers', 'body', 'key'], + ['previousKey', 'maxSkewSeconds', 'callerEnforcedFreshness'], + ); + if (!Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) + || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer) + || (input.previousKey !== undefined && (!Buffer.isBuffer(input.previousKey) + || isSharedArrayBuffer(input.previousKey.buffer))) + || (input.maxSkewSeconds !== undefined && !Number.isSafeInteger(input.maxSkewSeconds)) + || (input.callerEnforcedFreshness !== undefined + && typeof input.callerEnforcedFreshness !== 'boolean')) { throw inputError('invalid-request'); } input.headers = hookHeaders(input.headers); input.body = Buffer.from(input.body); input.key = Buffer.from(input.key); + if (input.previousKey !== undefined) input.previousKey = Buffer.from(input.previousKey); return native.verifyHookDelivery(input); } catch (error) { throw normalize(error, 'invalid-request'); diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index 6c98dcc795..32cab7ca9f 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -376,11 +376,21 @@ export declare function eventRecordView(argumentsJson: string): string /** Exact BReg hook request supplied by a receiver. */ export interface HookDeliveryInput { - method: string - path: string headers: Record body: Buffer key: Buffer + previousKey?: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. + * With neither this nor `callerEnforcedFreshness`, the window is 300 + * seconds. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed; the caller enforces + * its own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } /** Validated product result serialized before the JavaScript number boundary. */ @@ -422,16 +432,18 @@ export interface RawOutcome { /** Authenticated BReg hook metadata and exact body. */ export interface VerifiedHookDelivery { id: string + timestamp: string source: string type: string time: string dataschema: string - generation: string - attempt: string - deliveryTime: string - idempotencyKey: string body: Buffer } -/** Verify a BReg Version 1 hook signature without applying receiver policy. */ +/** + * Verify a BReg Standard Webhooks delivery. The delivery time must fall within + * 300 seconds of the receiver clock unless `maxSkewSeconds` or + * `callerEnforcedFreshness` says otherwise. Deduplication stays with the + * caller. + */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-breg-client-node/src/lib.rs b/crates/registry-breg-client-node/src/lib.rs index 52c945065b..622c89ca0b 100644 --- a/crates/registry-breg-client-node/src/lib.rs +++ b/crates/registry-breg-client-node/src/lib.rs @@ -23,7 +23,7 @@ use registry_breg_client::{ BRegCurrentContinuation, BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, - BRegHookDelivery as CoreHookDelivery, BRegHookVerificationError, + BRegHookDelivery as CoreHookDelivery, BRegHookFreshness, BRegHookVerificationError, BRegIngestionChunk as CoreIngestionChunk, BRegIngestionError, BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, BRegMetadata as CoreMetadata, @@ -70,50 +70,76 @@ pub struct JsonOutcome { /// Exact BReg hook request supplied by a receiver. #[napi(object)] pub struct HookDeliveryInput { - pub method: String, - pub path: String, pub headers: BTreeMap, pub body: Buffer, pub key: Buffer, + pub previous_key: Option, + /// Window around the receiver clock, in whole seconds from 1 to 3600. + /// With neither this nor `callerEnforcedFreshness`, the window is 300 + /// seconds. + pub max_skew_seconds: Option, + /// Check only that the delivery time is well formed; the caller enforces + /// its own window. Cannot be combined with `maxSkewSeconds`. + pub caller_enforced_freshness: Option, } /// Authenticated BReg hook metadata and exact body. #[napi(object)] pub struct VerifiedHookDelivery { pub id: String, + pub timestamp: String, pub source: String, pub r#type: String, pub time: String, pub dataschema: String, - pub generation: String, - pub attempt: String, - pub delivery_time: String, - pub idempotency_key: String, pub body: Buffer, } -/// Verify a BReg Version 1 hook signature without applying receiver policy. +const HOOK_MAXIMUM_SKEW_SECONDS: f64 = 3600.0; + +fn hook_freshness( + max_skew_seconds: Option, + caller_enforced_freshness: Option, +) -> Result { + let invalid = || binding_error("invalid-request", "hook freshness options are invalid"); + match (max_skew_seconds, caller_enforced_freshness) { + (None, None | Some(false)) => Ok(BRegHookFreshness::DefaultWindow), + (None, Some(true)) => Ok(BRegHookFreshness::CallerEnforced), + (Some(_), Some(true)) => Err(invalid()), + (Some(seconds), None | Some(false)) => { + if seconds.fract() != 0.0 || !(1.0..=HOOK_MAXIMUM_SKEW_SECONDS).contains(&seconds) { + return Err(invalid()); + } + Ok(BRegHookFreshness::Within { + skew: std::time::Duration::from_secs(seconds as u64), + }) + } + } +} + +/// Verify a BReg Standard Webhooks delivery. The delivery time must fall within +/// 300 seconds of the receiver clock unless `maxSkewSeconds` or +/// `callerEnforcedFreshness` says otherwise. Deduplication stays with the +/// caller. #[napi] pub fn verify_hook_delivery(input: HookDeliveryInput) -> Result { + let freshness = hook_freshness(input.max_skew_seconds, input.caller_enforced_freshness)?; let headers = input.headers.into_iter().collect::>(); let verified = verify_core_hook_delivery(CoreHookDelivery { - method: &input.method, - path: &input.path, headers: &headers, body: input.body.as_ref(), key: input.key.as_ref(), + previous_key: input.previous_key.as_ref().map(AsRef::as_ref), + freshness, }) .map_err(hook_verification_error)?; Ok(VerifiedHookDelivery { id: verified.id, + timestamp: verified.timestamp.to_string(), source: verified.source, r#type: verified.event_type, time: verified.time, dataschema: verified.data_schema, - generation: verified.generation, - attempt: verified.attempt, - delivery_time: verified.delivery_time, - idempotency_key: verified.idempotency_key, body: verified.body.into(), }) } diff --git a/crates/registry-breg-client-py/README.md b/crates/registry-breg-client-py/README.md index b39f69f4c8..b66210d46b 100644 --- a/crates/registry-breg-client-py/README.md +++ b/crates/registry-breg-client-py/README.md @@ -58,26 +58,21 @@ read that Proposal. Both revision reads return it as the server sent it. ## Hook verification -`verify_hook_delivery(method=..., path=..., headers=..., body=..., key=...)` -authenticates one exact Base Registry Engine Version 1 delivery with the shared -Rust verifier. Arguments are keyword-only. `path` is the request target the -receiver was called on, `headers` is an ordered sequence of string name/value -pairs (names match without regard to ASCII case, and every repeated name is -refused), and `body` and `key` are `bytes`. The result is a `dict` with -`id`, `source`, `type`, `time`, `dataschema`, `generation`, `attempt`, -`delivery_time`, `idempotency_key`, and the exact `body`. Generation and attempt -remain decimal strings, as signed. - -The helper does not apply clock-skew or deduplication policy. Bound the returned -`delivery_time` against the receiver clock. `idempotency_key` collapses automatic -retries within one delivery generation; an effect that must remain once-only -across operator replay uses a durable apply-once operation keyed by authenticated -`source` plus `id`, or by an application business key, before acting on `body`. - -Refusal raises `BaseRegistryClientError` with kind `hook-verification` and a -`code` from `missing-header`, `invalid-delivery-time`, `duplicate-header`, `body-too-large`, `invalid-key`, `malformed-signature`, `signature-mismatch`, or `unsupported-version`; an -argument of the wrong type raises kind `invalid-request`. The message names -the input to check and never includes a header value, body, or key. +`verify_hook_delivery(headers=..., body=..., key=..., previous_key=...)` authenticates one +Base Registry Engine Standard Webhooks delivery with the shared Rust verifier. +Pass all received headers as ordered name/value pairs and supply the body and keys as bytes. +The optional previous key supports rotation. A key contains 32 to 64 exact bytes. + +The result contains the authenticated `id`, `timestamp` (an integer of signed Unix seconds), +`source`, `type`, `time`, `dataschema`, and exact `body`. Deduplicate on `source` and +`id` before acting. Retries and operator replays preserve the id. + +The default window is 300 seconds in either direction. Choose `max_skew_seconds` +(1 to 3600 seconds) for a custom window or `caller_enforced_freshness=True` to enforce freshness yourself. + +A refusal raises `BaseRegistryClientError` with kind `hook-verification` and one of +`missing-header`, `duplicate-header`, `invalid-content-type`, `invalid-id`, `invalid-timestamp`, `stale-delivery`, `malformed-signature`, `unsupported-version`, `signature-mismatch`, `body-too-large`, `invalid-key`, `invalid-envelope`, or `id-mismatch`. +The message names what to check without exposing header values, body, or keys. ## Direct and atomic mutations diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index 83cfbcb19d..ddcc9cb065 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -208,37 +208,43 @@ def encode_ingestion_chunk( HookVerificationRefusalCode = Literal[ "missing-header", - "invalid-delivery-time", "duplicate-header", - "body-too-large", - "invalid-key", + "invalid-content-type", + "invalid-id", + "invalid-timestamp", + "stale-delivery", "malformed-signature", - "signature-mismatch", "unsupported-version", + "signature-mismatch", + "body-too-large", + "invalid-key", + "invalid-envelope", + "id-mismatch", ] class VerifiedHookDelivery(TypedDict): id: str + timestamp: int source: str type: str time: str dataschema: str - generation: str - attempt: str - delivery_time: str - idempotency_key: str body: bytes def verify_hook_delivery( *, - method: str, - path: str, headers: Sequence[tuple[str, str]], body: bytes, key: bytes, + previous_key: bytes | None = None, + max_skew_seconds: int | None = None, + caller_enforced_freshness: bool | None = None, ) -> VerifiedHookDelivery: - """Authenticate one exact Base Registry Engine Version 1 hook delivery. - Apply delivery-time skew and deduplication policy before acting on the body.""" + """Authenticate one exact Base Registry Engine Standard Webhooks delivery. + The delivery time must be within 300 seconds of the receiver clock unless + `max_skew_seconds` (1 to 3600) names another window or + `caller_enforced_freshness` leaves the bound to the caller. A time outside + the window raises code `stale-delivery`. Deduplicate before acting on the body.""" ... def event_record_view(arguments: dict[str, JsonValue]) -> dict[str, JsonValue]: diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index b2e0958ea4..16557e651d 100644 --- a/crates/registry-breg-client-py/src/lib.rs +++ b/crates/registry-breg-client-py/src/lib.rs @@ -15,11 +15,12 @@ use breg_client_sdk::{ BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, BRegHookDelivery as CoreHookDelivery, - BRegHookVerificationError, BRegIdempotencyKey, BRegIngestionChunk as CoreIngestionChunk, - BRegIngestionError, BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, - BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, - BRegMetadata as CoreMetadata, BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, - BRegPage, BRegPatchBinding, BRegPatchRequest, BRegPreparedAction as CorePreparedAction, + BRegHookFreshness, BRegHookVerificationError, BRegIdempotencyKey, + BRegIngestionChunk as CoreIngestionChunk, BRegIngestionError, + BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, BRegIngestionRunListQuery, + BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, BRegMetadata as CoreMetadata, + BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, BRegPage, BRegPatchBinding, + BRegPatchRequest, BRegPreparedAction as CorePreparedAction, BRegPreparedCreate as CorePreparedCreate, BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, BRegRelationshipContinuation, BRegRelationshipContinuationProjection, BRegRelationshipListRequest, BRegReleaseSelection, @@ -955,14 +956,6 @@ fn encode_ingestion_chunk( .map_err(|error| ingestion_error(py, error)) } -fn hook_text(py: Python<'_>, value: &Bound<'_, PyAny>, field: &str) -> PyResult { - value - .cast::() - .ok() - .and_then(|text| text.to_str().ok().map(str::to_owned)) - .ok_or_else(|| invalid(py, format!("hook {field} must be a string"))) -} - fn hook_bytes<'py>( py: Python<'py>, value: &Bound<'py, PyAny>, @@ -1045,49 +1038,96 @@ fn event_record_view<'py>( json_to_python(py, view.as_value()) } -/// Verify one exact Base Registry Engine Version 1 hook delivery with the +const HOOK_MAXIMUM_SKEW_SECONDS: u32 = 3600; + +/// The freshness window of one hook delivery. A `bool` is not a count. +fn hook_freshness( + py: Python<'_>, + max_skew_seconds: Option<&Bound<'_, PyAny>>, + caller_enforced_freshness: Option<&Bound<'_, PyAny>>, +) -> PyResult { + let invalid = || { + to_py_err( + py, + MappedError::binding( + "invalid-request", + "hook freshness options are invalid: max_skew_seconds is a whole number from 1 to 3600, caller_enforced_freshness is a bool, and the two cannot be combined", + ), + ) + }; + let caller_enforced_freshness = match caller_enforced_freshness { + None => false, + Some(value) if value.is_none() => false, + Some(value) => match value.cast::() { + Ok(flag) => flag.is_true(), + Err(_) => return Err(invalid()), + }, + }; + let Some(value) = max_skew_seconds.filter(|value| !value.is_none()) else { + return Ok(if caller_enforced_freshness { + BRegHookFreshness::CallerEnforced + } else { + BRegHookFreshness::DefaultWindow + }); + }; + if caller_enforced_freshness || value.is_instance_of::() { + return Err(invalid()); + } + let seconds = value.extract::().map_err(|_| invalid())?; + if !(1..=HOOK_MAXIMUM_SKEW_SECONDS).contains(&seconds) { + return Err(invalid()); + } + Ok(BRegHookFreshness::Within { + skew: Duration::from_secs(u64::from(seconds)), + }) +} + +/// Verify one exact Base Registry Engine Standard Webhooks delivery with the /// shared Rust verifier and return its authenticated attributes and body. /// -/// `path` is the request target the receiver was called on, `headers` is an -/// ordered sequence of name/value pairs (matched without regard to ASCII case), `body` is -/// the exact request body, and `key` is the destination's HMAC key. Receiver -/// policy is the caller's: bound `delivery_time` against the receiver clock -/// and deduplicate before acting on `body`. Refusal raises +/// Pass `headers` as ordered name/value pairs, `body` as exact request bytes, +/// and `key` as the destination's HMAC key. Use `previous_key` during rotation. +/// The signed timestamp must fall within 300 seconds of the receiver clock. Pass +/// `max_skew_seconds` (a whole number from 1 to 3600) for another window, or +/// `caller_enforced_freshness=True` to enforce the window yourself. Choose one +/// freshness option. A timestamp outside the window raises code `stale-delivery`. +/// Deduplicate by `source` and `id` before acting on `body`. Refusal raises /// `BaseRegistryClientError` with kind `hook-verification` and a value-free /// `code`; input of the wrong shape raises kind `invalid-request`. #[pyfunction] -#[pyo3(signature = (*, method, path, headers, body, key))] +#[pyo3(signature = (*, headers, body, key, previous_key=None, max_skew_seconds=None, caller_enforced_freshness=None))] +#[allow(clippy::too_many_arguments)] fn verify_hook_delivery<'py>( py: Python<'py>, - method: &Bound<'py, PyAny>, - path: &Bound<'py, PyAny>, headers: &Bound<'py, PyAny>, body: &Bound<'py, PyAny>, key: &Bound<'py, PyAny>, + previous_key: Option<&Bound<'py, PyAny>>, + max_skew_seconds: Option<&Bound<'py, PyAny>>, + caller_enforced_freshness: Option<&Bound<'py, PyAny>>, ) -> PyResult> { - let method = hook_text(py, method, "method")?; - let path = hook_text(py, path, "path")?; + let freshness = hook_freshness(py, max_skew_seconds, caller_enforced_freshness)?; let headers = hook_headers(py, headers)?; let body = hook_bytes(py, body, "body")?; let key = hook_bytes(py, key, "key")?; + let previous_key = previous_key + .map(|value| hook_bytes(py, value, "previous_key")) + .transpose()?; let verified = verify_core_hook_delivery(CoreHookDelivery { - method: &method, - path: &path, headers: &headers, body: body.as_bytes(), key: key.as_bytes(), + previous_key: previous_key.as_ref().map(|value| value.as_bytes()), + freshness, }) .map_err(|error| hook_verification_error(py, error))?; let result = PyDict::new(py); result.set_item("id", verified.id)?; + result.set_item("timestamp", verified.timestamp)?; result.set_item("source", verified.source)?; result.set_item("type", verified.event_type)?; result.set_item("time", verified.time)?; result.set_item("dataschema", verified.data_schema)?; - result.set_item("generation", verified.generation)?; - result.set_item("attempt", verified.attempt)?; - result.set_item("delivery_time", verified.delivery_time)?; - result.set_item("idempotency_key", verified.idempotency_key)?; result.set_item("body", PyBytes::new(py, &verified.body))?; Ok(result) } diff --git a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py index c2db4472e0..24c817107c 100644 --- a/crates/registry-breg-client-py/tests/python/test_webhook_verification.py +++ b/crates/registry-breg-client-py/tests/python/test_webhook_verification.py @@ -1,14 +1,12 @@ -"""Verify Base Registry Engine hook deliveries through the shared Rust verifier. - -The fixed vector is the one `registry-breg-client/tests/webhook.rs` and the -Node binding's `hook-verification.test.js` use, which in turn belongs to -`registry-platform-crypto` delivery signatures. -""" - +"""Verify Base Registry Engine Standard Webhooks through the Rust client.""" from __future__ import annotations -import unittest +import base64 +import hmac import json +import re +import unittest +from datetime import datetime, timedelta, timezone from pathlib import Path from bootstrap import ensure_built @@ -20,66 +18,70 @@ BaseRegistryClientError = breg_client.BaseRegistryClientError verify_hook_delivery = breg_client.verify_hook_delivery -KEY = b"webhook-delivery-signing-key-0123456789abcdef" -BODY = b'{"entity":"case","values":{"label":"value"}}' -SIGNATURE = "v1=OzL5k0ghZJb9nPbb-JOVsroWeanipBlZXbeKDd52RcM" -IDEMPOTENCY_KEY = "sha256:" + "a" * 64 +KEY = b"0123456789abcdef0123456789abcdef" +PREVIOUS_KEY = b"abcdef0123456789abcdef0123456789" +BODY = b'{"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{},"dataschema":"https://example.test/schema","id":"00000000-0000-4000-8000-000000000001","source":"/products/breg/deployments/example","subject":{"recordReference":"breg/case/42","recordRevision":7},"time":"2026-08-30T00:00:00.123Z","type":"case-created-v1"}' +SIGNATURE = "v1,NELq97rzqnAqQUxh1eiskBB3oOl+4FsqaI1ZV/lAqQY=" +EVENT = json.loads(BODY) +TIMESTAMP = 1788048001 +CRATES = Path(__file__).resolve().parents[3] -def headers() -> list[tuple[str, str]]: +def headers(event_id=EVENT["id"], timestamp=TIMESTAMP, signature=SIGNATURE): return [ - ("Ce-Specversion", "1.0"), - ("CE-ID", "00000000-0000-4000-8000-000000000001"), - ("ce-source", "urn:registrystack:registry:example:instance:primary"), - ("ce-type", "case-created-v1"), - ("ce-time", "2026-08-30T00:00:00Z"), - ("ce-dataschema", "urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa"), - ("x-registry-event-generation", "1"), - ("x-registry-delivery-attempt", "1"), - ("x-registry-delivery-time", "2026-08-30T00:00:01Z"), - ("idempotency-key", IDEMPOTENCY_KEY), - ("content-type", "application/json"), - ("x-registry-signature", SIGNATURE), + ("Content-Type", "application/json"), + ("Webhook-ID", event_id), + ("webhook-timestamp", str(timestamp)), + ("webhook-signature", signature), ] -def replace_header(values: list[tuple[str, str]], name: str, value: str) -> list[tuple[str, str]]: - return [ - (candidate, value if candidate.lower() == name.lower() else current) - for candidate, current in values - ] +def verify(**overrides): + return verify_hook_delivery(**{ + "headers": headers(), "body": BODY, "key": KEY, + "caller_enforced_freshness": True, **overrides, + }) -def verify(**overrides): - arguments = { - "method": "POST", - "path": "/hooks/registry", - "headers": headers(), - "body": BODY, - "key": KEY, - } - arguments.update(overrides) - return verify_hook_delivery(**arguments) +def signed_headers(delivery_time, key=KEY, event_id=EVENT["id"]): + stamp = int(delivery_time.timestamp()) + digest = hmac.digest(key, f"{event_id}.{stamp}.".encode("ascii") + BODY, "sha256") + return headers(event_id, stamp, "v1," + base64.b64encode(digest).decode("ascii")) + + +def verify_default(delivery_time, **overrides): + return verify(headers=signed_headers(delivery_time), caller_enforced_freshness=False, **overrides) class HookVerificationTests(unittest.TestCase): - def test_shared_language_vectors_preserve_exact_rfc3339_fractions(self): - fixture = Path(__file__).resolve().parents[3] / "registry-platform-crypto/tests/fixtures/delivery-signatures.json" + def test_shared_language_vectors(self): + fixture = CRATES / "registry-platform-crypto/tests/fixtures/standard-webhooks.json" for vector in json.loads(fixture.read_text()): - exact = replace_header( - replace_header(headers(), "x-registry-delivery-time", vector["deliveryTime"]), - "x-registry-signature", - vector["signature"], - ) - with self.subTest(timestamp=vector["deliveryTime"]): - if vector["valid"]: - self.assertEqual(verify(headers=exact)["delivery_time"], vector["deliveryTime"]) - self.assert_refused( - "signature-mismatch", - headers=replace_header(exact, "x-registry-delivery-time", "2026-08-30T00:00:01.0000Z"), - ) - else: - self.assert_refused("invalid-delivery-time", headers=exact) + with self.subTest(vector=vector["name"]): + code = vector["expected"] + if code in {"accepted", "stale-delivery"}: + code = "invalid-envelope" + if vector["keyPolicy"] == "below-minimum": + code = "invalid-key" + previous = vector["previousKeyHex"] + self.assert_refused( + code, headers=headers(vector["id"], vector["timestamp"], vector["signature"]), + body=vector["body"].encode(), key=bytes.fromhex(vector["keyHex"]), + previous_key=bytes.fromhex(previous) if previous else None, + ) + + def test_stub_refusal_codes_match_rust(self): + rust = (CRATES / "registry-breg-client/src/hook.rs").read_text() + stub = (CRATES / "registry-breg-client-py/python/registry_breg_client/__init__.pyi").read_text() + codes = re.findall(r'=> "([a-z-]+)"', rust) + self.assertEqual(codes, re.findall(r'"([a-z-]+)"', stub.split("HookVerificationRefusalCode = Literal[", 1)[1].split("]", 1)[0])) + + def test_previous_key_and_envelope_identity(self): + stamp = datetime.fromtimestamp(TIMESTAMP, timezone.utc) + rotated = signed_headers(stamp, PREVIOUS_KEY) + self.assert_refused("signature-mismatch", headers=rotated) + self.assertEqual(verify(headers=rotated, previous_key=PREVIOUS_KEY)["id"], EVENT["id"]) + self.assert_refused("id-mismatch", headers=signed_headers(stamp, event_id="00000000-0000-4000-8000-000000000002")) def assert_refused(self, code: str, message: str | None = None, **overrides) -> None: with self.assertRaises(BaseRegistryClientError) as raised: @@ -95,103 +97,96 @@ def assert_refused(self, code: str, message: str | None = None, **overrides) -> self.assertNotIn(secret, rendered) def test_fixed_vector_verifies_and_returns_exact_delivery(self) -> None: - verified = verify() - self.assertEqual( - verified, - { - "id": "00000000-0000-4000-8000-000000000001", - "source": "urn:registrystack:registry:example:instance:primary", - "type": "case-created-v1", - "time": "2026-08-30T00:00:00Z", - "dataschema": "urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa", - "generation": "1", - "attempt": "1", - "delivery_time": "2026-08-30T00:00:01Z", - "idempotency_key": IDEMPOTENCY_KEY, - "body": BODY, - }, - ) - self.assertIsInstance(verified["body"], bytes) - - def test_arguments_are_keyword_only(self) -> None: - with self.assertRaises(TypeError): - verify_hook_delivery("POST", "/hooks/registry", headers(), BODY, KEY) - - def test_refuses_a_tampered_signed_header(self) -> None: - self.assert_refused( - "signature-mismatch", headers=replace_header(headers(), "ce-type", "case-patched-v1") - ) - - def test_refuses_a_tampered_body(self) -> None: - self.assert_refused("signature-mismatch", body=b'{"tampered":true}') - - def test_refuses_the_wrong_key(self) -> None: - self.assert_refused("signature-mismatch", key=b"k" * 32) - - def test_refuses_another_request_target(self) -> None: - self.assert_refused("signature-mismatch", path="/hooks/other") + stamp = datetime.fromtimestamp(TIMESTAMP, timezone.utc) + self.assertEqual(signed_headers(stamp), headers()) + self.assertEqual(verify(), { + **{field: EVENT[field] for field in ("id", "source", "type", "time", "dataschema")}, + "timestamp": TIMESTAMP, "body": BODY, + }) + + def test_default_window_is_300_seconds_in_both_directions(self) -> None: + now = datetime.now(timezone.utc) + for offset in (0, -295, 295): + with self.subTest(offset=offset): + self.assertEqual( + verify_default(now + timedelta(seconds=offset))["id"], + "00000000-0000-4000-8000-000000000001", + ) + for offset in (-305, 305): + with self.subTest(offset=offset): + with self.assertRaises(BaseRegistryClientError) as raised: + verify_default(now + timedelta(seconds=offset)) + self.assertEqual(raised.exception.kind, "hook-verification") + self.assertEqual(raised.exception.code, "stale-delivery") - def test_refuses_a_truncated_signature(self) -> None: - self.assert_refused( - "malformed-signature", - headers=replace_header(headers(), "x-registry-signature", "v1=truncated"), - ) + def test_default_window_refuses_the_old_fixed_vector(self) -> None: + self.assert_refused("stale-delivery", caller_enforced_freshness=False) - def test_refuses_a_header_repeated_under_another_case(self) -> None: - self.assert_refused( - "duplicate-header", - "a Base Registry Engine hook header is repeated; remove duplicate signed headers", - headers=[*headers(), ("CE-TYPE", "case-created-v1")], + def test_an_explicit_none_freshness_option_keeps_the_default_window(self) -> None: + self.assert_refused("stale-delivery", caller_enforced_freshness=None) + self.assertEqual( + verify( + headers=signed_headers(datetime.now(timezone.utc)), + max_skew_seconds=None, + caller_enforced_freshness=None, + )["id"], + EVENT["id"], ) - def test_ordered_header_pairs_preserve_verification_and_duplicate_refusals(self) -> None: - pairs = headers() - self.assertEqual(verify(headers=pairs)["id"], "00000000-0000-4000-8000-000000000001") - - tampered = [ - (name, "case-patched-v1" if name.lower() == "ce-type" else value) - for name, value in pairs - ] - self.assert_refused("signature-mismatch", headers=tampered) - self.assert_refused("duplicate-header", headers=[*pairs, ("ce-type", "withheld")]) - + def test_max_skew_seconds_replaces_the_default_window(self) -> None: + stamp = datetime.now(timezone.utc) - timedelta(seconds=600) + self.assertEqual(verify_default(stamp, max_skew_seconds=900)["id"], EVENT["id"]) with self.assertRaises(BaseRegistryClientError) as raised: - verify(headers=dict(headers())) - self.assertEqual(raised.exception.kind, "invalid-request") - self.assertNotIn("withheld", str(raised.exception)) - - def test_reports_an_invalid_delivery_time_with_its_fix(self) -> None: - fixture = Path(__file__).resolve().parents[3] / "registry-platform-crypto/tests/fixtures/delivery-signatures.json" - vector = next(value for value in json.loads(fixture.read_text()) if not value["valid"]) - self.assert_refused( - "invalid-delivery-time", - "the Base Registry Engine hook delivery time is invalid; check the signed delivery time and sender clock", - headers=replace_header( - replace_header(headers(), "x-registry-delivery-time", vector["deliveryTime"]), - "x-registry-signature", - vector["signature"], - ), - ) + verify_default(datetime.now(timezone.utc) - timedelta(seconds=60), max_skew_seconds=10) + self.assertEqual(raised.exception.code, "stale-delivery") - def test_reports_an_oversized_body_with_its_fix(self) -> None: - self.assert_refused( - "body-too-large", - "the Base Registry Engine hook body exceeds the Version 1 limit; reduce the body size", - body=b"x" * 1_048_577, - ) + def test_caller_enforced_freshness_accepts_an_old_delivery(self) -> None: + self.assertEqual(verify(caller_enforced_freshness=True)["id"], EVENT["id"]) - def test_reports_an_invalid_key_with_its_fix(self) -> None: - self.assert_refused( - "invalid-key", - "the Base Registry Engine hook verification key is too short; configure a key of at least 32 bytes", - key=b"short-key", - ) + def test_refuses_a_freshness_option_out_of_range_or_combined(self) -> None: + for overrides in ( + {"max_skew_seconds": 0}, + {"max_skew_seconds": 3601}, + {"max_skew_seconds": -1}, + {"max_skew_seconds": 1.5}, + {"max_skew_seconds": True}, + {"max_skew_seconds": "10"}, + {"max_skew_seconds": 10, "caller_enforced_freshness": True}, + {"caller_enforced_freshness": "yes"}, + {"caller_enforced_freshness": 1}, + ): + with self.subTest(overrides=overrides): + with self.assertRaises(BaseRegistryClientError) as raised: + verify(**{"caller_enforced_freshness": False, **overrides}) + self.assertEqual(raised.exception.kind, "invalid-request") + for edge in (1, 3600): + self.assertEqual( + verify_default(datetime.now(timezone.utc), max_skew_seconds=edge)["id"], EVENT["id"] + ) - def test_refuses_an_unknown_signature_version(self) -> None: - self.assert_refused( - "unsupported-version", - headers=replace_header(headers(), "x-registry-signature", SIGNATURE.replace("v1=", "v2=", 1)), - ) + def test_arguments_are_keyword_only(self) -> None: + with self.assertRaises(TypeError): + verify_hook_delivery("POST", "/hooks/registry", headers(), BODY, KEY) + + def test_refuses_invalid_headers_and_bytes(self): + self.assert_refused("signature-mismatch", body=b"{}") + self.assert_refused("signature-mismatch", key=b"k" * 32) + self.assert_refused("body-too-large", body=b"x" * 1_048_577) + self.assert_refused("duplicate-header", headers=[*headers(), ("webhook-id", EVENT["id"])]) + self.assert_refused("invalid-content-type", headers=[("Content-Type", "text/plain"), *headers()[1:]]) + + def test_reports_invalid_keys_without_their_bytes(self): + for overrides, expected in ( + ({"key": b"x" * 31}, 'The current hook key is 31 bytes and must contain 32 to 64 exact bytes.'), + ({"key": b"x" * 64 + b"\n"}, 'The current hook key is 65 bytes including a trailing newline and must contain 32 to 64 exact bytes.'), + ({"key": b"whsec_synthetic_key_text_for_test"}, 'The current hook key starts with whsec_ and must be supplied as exact key bytes.'), + ({"previous_key": KEY}, 'The previous hook key equals the current key. Pass the key the sender used before rotation, or omit the previous key.'), + ): + with self.assertRaises(BaseRegistryClientError) as raised: + verify(**overrides) + self.assertEqual(raised.exception.code, "invalid-key") + self.assertEqual(str(raised.exception), expected) + self.assertNotIn(next(iter(overrides.values())).decode(), str(raised.exception)) def test_refuses_each_missing_signed_header(self) -> None: for name, _ in headers(): @@ -201,10 +196,9 @@ def test_refuses_each_missing_signed_header(self) -> None: def test_refuses_input_of_the_wrong_shape_before_verification(self) -> None: for overrides in ( - {"method": b"POST"}, - {"path": None}, - {"headers": [("ce-id",)]}, - {"headers": [*headers(), ("ce-id", b"x")]}, + {"previous_key": KEY.decode()}, + {"headers": [("webhook-id",)]}, + {"headers": [*headers(), ("webhook-id", b"x")]}, {"headers": [*headers(), (1, "x")]}, {"headers": dict(headers())}, {"body": BODY.decode()}, diff --git a/crates/registry-breg-client/src/actions.rs b/crates/registry-breg-client/src/actions.rs index f8e1c36078..a8f0923d1c 100644 --- a/crates/registry-breg-client/src/actions.rs +++ b/crates/registry-breg-client/src/actions.rs @@ -849,6 +849,7 @@ fn decode_availability( | "recovery" | "missingInputs" | "guardReason" + | "guardLabel" ) }) { return Err(BRegActionError::InvalidResponse); @@ -875,6 +876,9 @@ fn decode_availability( }; let reason = optional_string("reason")?; let guard_reason = optional_string("guardReason")?; + // An authored label rides only beside its reason. Like every refusal + // text it is bounded and never retained. + let guard_label = optional_string("guardLabel")?; let recovery = optional_string("recovery")?; let missing_inputs = availability .get("missingInputs") @@ -917,6 +921,9 @@ fn decode_availability( || guard_reason.as_deref().is_some_and(|reason| { available != Some(false) || !crate::error::valid_guard_reason(reason) }) + || guard_label.as_deref().is_some_and(|label| { + guard_reason.is_none() || !crate::error::bounded_refusal_label(label) + }) { return Err(BRegActionError::InvalidResponse); } diff --git a/crates/registry-breg-client/src/error.rs b/crates/registry-breg-client/src/error.rs index 72584118ec..d2a34852d7 100644 --- a/crates/registry-breg-client/src/error.rs +++ b/crates/registry-breg-client/src/error.rs @@ -370,7 +370,7 @@ impl BRegProblemCode { "The record attachment slot already holds a file and is write-once." } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", - Self::AuthenticationRefused => "The bearer credential is missing or refused.", + Self::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", Self::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." } diff --git a/crates/registry-breg-client/src/hook.rs b/crates/registry-breg-client/src/hook.rs index f25ab7aa7f..4603fe0bc5 100644 --- a/crates/registry-breg-client/src/hook.rs +++ b/crates/registry-breg-client/src/hook.rs @@ -1,18 +1,38 @@ +use std::time::{Duration, SystemTime}; + use registry_platform_hooks::receiver::{ - verify_delivery, DeliveryFreshness, ReceiverError, SignedDelivery, + verify_hook_delivery as verify_standard_delivery, DeliveryFreshness, HookDelivery, }; +use registry_platform_hooks::{DeliveryKey, DeliveryKeys}; +use time::format_description::well_known::Rfc3339; + +/// How the verifier bounds the signed delivery time. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum BRegHookFreshness { + /// Refuse a delivery time further than 300 seconds from the receiver clock. + #[default] + DefaultWindow, + /// Refuse a delivery time further than `skew` from the receiver clock. + /// + /// The Rust verifier applies `skew` as given. The Node and Python + /// bindings accept 1 to 3600 seconds. Use [`Self::CallerEnforced`] to + /// enforce the window in the receiver. + Within { skew: Duration }, + /// Verify authenticity and timestamp syntax. The caller enforces the window. + CallerEnforced, +} -/// Exact request material supplied to the BReg Version 1 hook verifier. +/// Exact request material supplied to the BReg Standard Webhooks verifier. /// /// Header pairs retain order and duplicates; names are matched without regard /// to ASCII case. The key and body are never rendered by this type or by its /// refusal errors. pub struct BRegHookDelivery<'a> { - pub method: &'a str, - pub path: &'a str, pub headers: &'a [(String, String)], pub body: &'a [u8], pub key: &'a [u8], + pub previous_key: Option<&'a [u8]>, + pub freshness: BRegHookFreshness, } impl std::fmt::Debug for BRegHookDelivery<'_> { @@ -23,20 +43,18 @@ impl std::fmt::Debug for BRegHookDelivery<'_> { /// Authenticated BReg hook attributes and exact body. /// -/// Verification does not apply replay, delivery-time skew, or deduplication -/// policy. Receivers must apply those policies to `delivery_time` and -/// `idempotency_key` before acting on the body. +/// Verification applies the delivery-time window named by +/// [`BRegHookFreshness`], 300 seconds by default. It does not apply replay or +/// deduplication policy. Receivers must deduplicate on `source` and `id` +/// before acting on the body. #[derive(Clone, Eq, PartialEq)] pub struct BRegVerifiedHookDelivery { pub id: String, + pub timestamp: u64, pub source: String, pub event_type: String, pub time: String, pub data_schema: String, - pub generation: String, - pub attempt: String, - pub delivery_time: String, - pub idempotency_key: String, pub body: Vec, } @@ -50,99 +68,205 @@ impl std::fmt::Debug for BRegVerifiedHookDelivery { } /// Closed, value-free reason a BReg hook delivery was refused. -#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] #[non_exhaustive] pub enum BRegHookVerificationError { - #[error("a required Base Registry Engine hook header is missing")] + #[error("a required hook header is missing. Check Content-Type and the three webhook headers")] MissingHeader, - #[error("the Base Registry Engine hook delivery time is invalid; check the signed delivery time and sender clock")] - InvalidDeliveryTime, - #[error("a Base Registry Engine hook header is repeated; remove duplicate signed headers")] + #[error("a required hook header is repeated. Remove duplicate headers")] DuplicateHeader, + #[error("the hook content type is invalid. Set Content-Type to application/json")] + InvalidContentType, + #[error("the webhook id is invalid. Check the webhook-id header")] + InvalidId, #[error( - "the Base Registry Engine hook body exceeds the Version 1 limit; reduce the body size" + "the webhook timestamp is invalid. Use canonical Unix seconds and check the sender clock" )] - BodyTooLarge, - #[error("the Base Registry Engine hook verification key is too short; configure a key of at least 32 bytes")] - InvalidKey, - #[error("the Base Registry Engine hook signature is malformed")] + InvalidTimestamp, + #[error("the webhook timestamp is outside the freshness window. Check the clocks or configure a wider window")] + StaleDelivery, + #[error("the webhook signature is malformed. Check the Standard Webhooks signature encoding")] MalformedSignature, - #[error("the Base Registry Engine hook signature does not match")] - SignatureMismatch, - #[error("the Base Registry Engine hook signature version is unsupported")] + #[error("the webhook signature version is unsupported. Check that the sender signs with v1")] UnsupportedVersion, + #[error("the webhook signature does not match. Check the key and exact signed bytes")] + SignatureMismatch, + #[error("the hook body exceeds the size limit. Reduce the body size")] + BodyTooLarge, + #[error("{detail}")] + InvalidKey { detail: String }, + #[error("the hook envelope is invalid. Check the canonical JSON envelope")] + InvalidEnvelope, + #[error( + "the webhook id differs from the envelope id. Check that the sender uses the envelope id" + )] + IdMismatch, } impl BRegHookVerificationError { /// Stable refusal code exposed by language bindings. #[must_use] - pub const fn code(self) -> &'static str { + pub const fn code(&self) -> &'static str { match self { Self::MissingHeader => "missing-header", - Self::InvalidDeliveryTime => "invalid-delivery-time", Self::DuplicateHeader => "duplicate-header", - Self::BodyTooLarge => "body-too-large", - Self::InvalidKey => "invalid-key", + Self::InvalidContentType => "invalid-content-type", + Self::InvalidId => "invalid-id", + Self::InvalidTimestamp => "invalid-timestamp", + Self::StaleDelivery => "stale-delivery", Self::MalformedSignature => "malformed-signature", - Self::SignatureMismatch => "signature-mismatch", Self::UnsupportedVersion => "unsupported-version", + Self::SignatureMismatch => "signature-mismatch", + Self::BodyTooLarge => "body-too-large", + Self::InvalidKey { .. } => "invalid-key", + Self::InvalidEnvelope => "invalid-envelope", + Self::IdMismatch => "id-mismatch", } } } -/// Verify one exact BReg Version 1 hook delivery without applying receiver policy. +/// Verify one exact BReg Standard Webhooks delivery against the system clock. /// -/// This delegates header extraction, the signature input, RFC 3339 -/// delivery-time validation, and constant-time HMAC comparison to the shared -/// `registry_platform_hooks::receiver::verify_delivery`. Caller-enforced -/// freshness leaves the receiver's clock policy separate; the caller receives -/// the authenticated raw delivery time to enforce its own skew bound. +/// The shared hooks verifier authenticates the exact body and checks the +/// canonical envelope and event identity. The default freshness window is +/// 300 seconds in either direction. Deduplication stays with the caller. pub fn verify_hook_delivery( delivery: BRegHookDelivery<'_>, ) -> Result { - let verified = verify_delivery( - SignedDelivery { - method: delivery.method, - request_target: delivery.path, + verify_hook_delivery_at(delivery, SystemTime::now()) +} + +/// Same as [`verify_hook_delivery`], against `now`. For tests and for callers +/// with their own clock. +pub fn verify_hook_delivery_at( + delivery: BRegHookDelivery<'_>, + now: SystemTime, +) -> Result { + let freshness = match delivery.freshness { + BRegHookFreshness::DefaultWindow => DeliveryFreshness::default_at(now), + BRegHookFreshness::Within { skew } => DeliveryFreshness::Within { now, skew }, + BRegHookFreshness::CallerEnforced => DeliveryFreshness::CallerEnforced, + }; + let current = DeliveryKey::new(delivery.key) + .map_err(|error| invalid_key("current", delivery.key, error.code()))?; + let previous = delivery + .previous_key + .map(|bytes| { + DeliveryKey::new(bytes).map_err(|error| invalid_key("previous", bytes, error.code())) + }) + .transpose()?; + let keys = DeliveryKeys::new(current, previous).map_err(|_| { + BRegHookVerificationError::InvalidKey { + detail: "The previous hook key equals the current key. Pass the key the sender used before rotation, or omit the previous key.".into(), + } + })?; + let verified = verify_standard_delivery( + HookDelivery { headers: delivery .headers .iter() .map(|(name, value)| (name.as_str(), value.as_bytes())), body: delivery.body, - key: delivery.key, + keys: &keys, }, - DeliveryFreshness::CallerEnforced, + freshness, ) - .map_err(map_receiver_error)?; + .map_err(|error| { + map_receiver_error(error.code()).unwrap_or(BRegHookVerificationError::MalformedSignature) + })?; Ok(BRegVerifiedHookDelivery { id: verified.id.to_owned(), - source: verified.source.to_owned(), - event_type: verified.event_type.to_owned(), - time: verified.time.to_owned(), - data_schema: verified.data_schema.to_owned(), - generation: verified.generation.to_owned(), - attempt: verified.attempt.to_owned(), - delivery_time: verified.delivery_time.to_owned(), - idempotency_key: verified.idempotency_key.to_owned(), - body: delivery.body.to_vec(), + timestamp: verified.timestamp, + source: verified.envelope.source, + event_type: verified.envelope.event_type, + time: verified + .envelope + .time + .format(&Rfc3339) + .map_err(|_| BRegHookVerificationError::InvalidEnvelope)?, + data_schema: verified.envelope.dataschema, + body: verified.body.to_vec(), }) } -fn map_receiver_error(error: ReceiverError) -> BRegHookVerificationError { - match error { - ReceiverError::MissingHeader => BRegHookVerificationError::MissingHeader, - ReceiverError::InvalidDeliveryTime | ReceiverError::Stale => { - BRegHookVerificationError::InvalidDeliveryTime +fn invalid_key(which: &str, bytes: &[u8], code: &str) -> BRegHookVerificationError { + let detail = match code { + "key-is-secret-text" => format!( + "The {which} hook key starts with whsec_ and must be supplied as exact key bytes." + ), + _ => { + let length = bytes.len(); + let newline = if bytes.ends_with(b"\n") { + " including a trailing newline" + } else { + "" + }; + format!( + "The {which} hook key is {length} bytes{newline} and must contain 32 to 64 exact bytes." + ) } - ReceiverError::DuplicateHeader => BRegHookVerificationError::DuplicateHeader, - ReceiverError::BodyTooLarge => BRegHookVerificationError::BodyTooLarge, - ReceiverError::InvalidKey => BRegHookVerificationError::InvalidKey, - ReceiverError::UnsupportedVersion => BRegHookVerificationError::UnsupportedVersion, - ReceiverError::SignatureMismatch => BRegHookVerificationError::SignatureMismatch, - ReceiverError::MalformedHeader | ReceiverError::MalformedSignature => { - BRegHookVerificationError::MalformedSignature + }; + BRegHookVerificationError::InvalidKey { detail } +} + +fn map_receiver_error(code: &str) -> Option { + use BRegHookVerificationError::*; + Some(match code { + "missing-header" => MissingHeader, + "duplicate-header" => DuplicateHeader, + "invalid-content-type" => InvalidContentType, + "invalid-id" => InvalidId, + "invalid-timestamp" => InvalidTimestamp, + "stale-delivery" => StaleDelivery, + "malformed-signature" => MalformedSignature, + "unsupported-version" => UnsupportedVersion, + "signature-mismatch" => SignatureMismatch, + "body-too-large" => BodyTooLarge, + "invalid-envelope" => InvalidEnvelope, + "id-mismatch" => IdMismatch, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_shared_receiver_code_has_a_distinct_mapping() { + // The receiver enum is non-exhaustive and exposes no code inventory. + // Read both code methods so new upstream codes also enter this check. + let sources = [ + include_str!("../../registry-platform-hooks/src/receiver.rs") + .split_once("impl HookDeliveryError {") + .unwrap() + .1, + include_str!("../../registry-platform-crypto/src/delivery_signature.rs") + .split_once("impl DeliverySignatureError {") + .unwrap() + .1, + ]; + let codes = sources.into_iter().flat_map(|source| { + source + .split_once("\n}\n") + .unwrap() + .0 + .lines() + .filter_map(|line| { + let (_, value) = line.split_once("=> \"")?; + Some(value.split_once('"').unwrap().0) + }) + }); + let mut count = 0; + for code in codes { + count += 1; + assert_eq!( + map_receiver_error(code).map(|error| error.code()), + Some(code) + ); } - _ => BRegHookVerificationError::MalformedSignature, + assert!(count >= 12); + assert_eq!(map_receiver_error("unknown-receiver-code"), None); } } diff --git a/crates/registry-breg-client/src/response.rs b/crates/registry-breg-client/src/response.rs index 0a07c7915d..ab70ed4d8c 100644 --- a/crates/registry-breg-client/src/response.rs +++ b/crates/registry-breg-client/src/response.rs @@ -2,8 +2,9 @@ use registry_platform_httpsec::TraceId; use serde::{Deserialize, Serialize}; use std::fmt; +/// The probe answer. Members other than `status` are ignored so the client +/// keeps working against servers that report more. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] pub struct BRegProbeStatus { pub status: String, } diff --git a/crates/registry-breg-client/src/transport.rs b/crates/registry-breg-client/src/transport.rs index b158bda52f..a18ce14525 100644 --- a/crates/registry-breg-client/src/transport.rs +++ b/crates/registry-breg-client/src/transport.rs @@ -2,7 +2,7 @@ use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use reqwest::header::{HeaderMap, CONTENT_TYPE}; use reqwest::{Response, Url}; @@ -52,7 +52,7 @@ impl Transport { .send() .await .map_err(|error| BaseRegistryClientError::transport(send_failure_kind(&error)))?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { BaseRegistryClientError::protocol( response.status().as_u16(), BRegProtocolFailure::HeaderBounds, diff --git a/crates/registry-breg-client/tests/event_record_view.rs b/crates/registry-breg-client/tests/event_record_view.rs index 0cb1c76ff7..512fa36f1f 100644 --- a/crates/registry-breg-client/tests/event_record_view.rs +++ b/crates/registry-breg-client/tests/event_record_view.rs @@ -1817,7 +1817,7 @@ async fn other_failures_and_invalid_documents_stay_visible() { 401, "Unauthorized", "authentication.refused", - "The bearer credential is missing or refused.", + "The bearer token or delivery signature was not accepted.", ); let fixture = test_client(vec![MockResponse::problem( StatusCode::UNAUTHORIZED, diff --git a/crates/registry-breg-client/tests/http_boundary.rs b/crates/registry-breg-client/tests/http_boundary.rs index af46af8971..c162ad2cc8 100644 --- a/crates/registry-breg-client/tests/http_boundary.rs +++ b/crates/registry-breg-client/tests/http_boundary.rs @@ -1008,3 +1008,18 @@ async fn derived_response_limits_retain_credentials_and_leave_the_original_bound assert_eq!(requests[0].uri, requests[1].uri); assert_eq!(requests[0].authorization, requests[1].authorization); } + +#[test] +fn probe_status_ignores_members_it_does_not_know() { + let status: registry_breg_client::BRegProbeStatus = serde_json::from_str( + r#"{"status":"ready","posture":"production","developmentSettings":[]}"#, + ) + .expect("unknown members are ignored"); + assert_eq!(status.status, "ready"); + assert!( + serde_json::from_str::( + r#"{"posture":"production"}"# + ) + .is_err() + ); +} diff --git a/crates/registry-breg-client/tests/webhook.rs b/crates/registry-breg-client/tests/webhook.rs index b4434a3adc..e58bf8e795 100644 --- a/crates/registry-breg-client/tests/webhook.rs +++ b/crates/registry-breg-client/tests/webhook.rs @@ -1,201 +1,233 @@ -use registry_breg_client::{verify_hook_delivery, BRegHookDelivery, BRegHookVerificationError}; +use std::time::{Duration, UNIX_EPOCH}; -const KEY: &[u8] = b"webhook-delivery-signing-key-0123456789abcdef"; -const BODY: &[u8] = br#"{"entity":"case","values":{"label":"value"}}"#; -const SIGNATURE: &str = "v1=OzL5k0ghZJb9nPbb-JOVsroWeanipBlZXbeKDd52RcM"; +use registry_breg_client::{verify_hook_delivery_at, BRegHookDelivery, BRegHookFreshness}; -fn headers() -> Vec<(String, String)> { +const ID: &str = "00000000-0000-4000-8000-000000000001"; +const KEY: &[u8] = b"0123456789abcdef0123456789abcdef"; +const PREVIOUS: &[u8] = b"abcdef0123456789abcdef0123456789"; +const BODY: &[u8] = br#"{"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{},"dataschema":"https://example.test/schema","id":"00000000-0000-4000-8000-000000000001","source":"/products/breg/deployments/example","subject":{"recordReference":"breg/case/42","recordRevision":7},"time":"2026-08-30T00:00:00.123Z","type":"case-created-v1"}"#; +const TS: u64 = 1_788_048_001; +const SIGNATURE: &str = "v1,NELq97rzqnAqQUxh1eiskBB3oOl+4FsqaI1ZV/lAqQY="; + +fn headers(id: &str, timestamp: &str, signature: &str) -> Vec<(String, String)> { [ - ("Ce-Specversion", "1.0"), - ("CE-ID", "00000000-0000-4000-8000-000000000001"), - ( - "ce-source", - "urn:registrystack:registry:example:instance:primary", - ), - ("ce-type", "case-created-v1"), - ("ce-time", "2026-08-30T00:00:00Z"), - ( - "ce-dataschema", - "urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa", - ), - ("x-registry-event-generation", "1"), - ("x-registry-delivery-attempt", "1"), - ("x-registry-delivery-time", "2026-08-30T00:00:01Z"), - ( - "idempotency-key", - "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ), - ("content-type", "application/json"), - ("x-registry-signature", SIGNATURE), + ("Content-Type", "application/json"), + ("Webhook-ID", id), + ("webhook-timestamp", timestamp), + ("webhook-signature", signature), ] - .into_iter() - .map(|(name, value)| (name.to_owned(), value.to_owned())) - .collect() -} - -fn delivery<'a>( - headers: &'a [(String, String)], - body: &'a [u8], - key: &'a [u8], -) -> BRegHookDelivery<'a> { - BRegHookDelivery { - method: "POST", - path: "/hooks/registry", - headers, - body, - key, - } + .map(|(name, value)| (name.into(), value.into())) + .to_vec() } -fn set_header(headers: &mut [(String, String)], name: &str, value: impl Into) { - headers - .iter_mut() - .find(|(candidate, _)| candidate == name) - .unwrap() - .1 = value.into(); +fn verify( + freshness: BRegHookFreshness, + offset: i64, +) -> Result< + registry_breg_client::BRegVerifiedHookDelivery, + registry_breg_client::BRegHookVerificationError, +> { + verify_hook_delivery_at( + BRegHookDelivery { + headers: &headers(ID, &TS.to_string(), SIGNATURE), + body: BODY, + key: KEY, + previous_key: None, + freshness, + }, + UNIX_EPOCH + Duration::from_secs(TS.checked_add_signed(offset).unwrap()), + ) } #[test] -fn fixed_vector_verifies_and_returns_exact_delivery() { - let headers = headers(); - let verified = verify_hook_delivery(delivery(&headers, BODY, KEY)).unwrap(); - - assert_eq!(verified.id, "00000000-0000-4000-8000-000000000001"); - assert_eq!( - verified.source, - "urn:registrystack:registry:example:instance:primary" - ); - assert_eq!(verified.event_type, "case-created-v1"); - assert_eq!(verified.time, "2026-08-30T00:00:00Z"); - assert_eq!( - verified.data_schema, - "urn:registrystack:registry:example:event:case-created-v1:schema:sha256:aaa" - ); - assert_eq!(verified.generation, "1"); - assert_eq!(verified.attempt, "1"); - assert_eq!(verified.delivery_time, "2026-08-30T00:00:01Z"); - assert_eq!( - verified.idempotency_key, - "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ); - assert_eq!(verified.body, BODY); +fn a_signed_envelope_verifies_and_returns_its_attributes() { + let result = verify(BRegHookFreshness::DefaultWindow, 0).unwrap(); + assert_eq!(result.id, ID); + assert_eq!(result.timestamp, TS); + assert_eq!(result.source, "/products/breg/deployments/example"); + assert_eq!(result.event_type, "case-created-v1"); + assert_eq!(result.time, "2026-08-30T00:00:00.123Z"); + assert_eq!(result.data_schema, "https://example.test/schema"); + assert_eq!(result.body, BODY); +} - let debug = format!("{verified:?}"); - assert!(!debug.contains(&format!("{:?}", BODY.to_vec()))); - assert!(debug.contains("body_bytes")); +fn unhex(hex: &str) -> Vec { + (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()) + .collect() } #[test] -fn refusal_codes_are_closed_and_value_free() { - let mut missing = headers(); - missing.retain(|(name, _)| name != "ce-type"); - assert_eq!( - verify_hook_delivery(delivery(&missing, BODY, KEY)), - Err(BRegHookVerificationError::MissingHeader) - ); - - let mut malformed = headers(); - set_header(&mut malformed, "x-registry-signature", "v1=truncated"); - assert_eq!( - verify_hook_delivery(delivery(&malformed, BODY, KEY)), - Err(BRegHookVerificationError::MalformedSignature) - ); +fn every_committed_vector_gets_its_expected_code() { + let vectors: Vec = serde_json::from_str(include_str!( + "../../registry-platform-crypto/tests/fixtures/standard-webhooks.json" + )) + .unwrap(); + for vector in vectors { + let key = unhex(vector["keyHex"].as_str().unwrap()); + let previous = vector["previousKeyHex"].as_str().map(unhex); + let error = verify_hook_delivery_at( + BRegHookDelivery { + headers: &headers( + vector["id"].as_str().unwrap(), + vector["timestamp"].as_str().unwrap(), + vector["signature"].as_str().unwrap(), + ), + body: vector["body"].as_str().unwrap().as_bytes(), + key: &key, + previous_key: previous.as_deref(), + freshness: BRegHookFreshness::DefaultWindow, + }, + UNIX_EPOCH + Duration::from_secs(vector["now"].as_u64().unwrap()), + ) + .unwrap_err(); + let expected = match ( + vector["keyPolicy"].as_str(), + vector["expected"].as_str().unwrap(), + ) { + (Some("below-minimum"), _) => "invalid-key", + (_, "accepted") => "invalid-envelope", + (_, code) => code, + }; + assert_eq!(error.code(), expected, "{}", vector["name"]); + } +} - let mut unsupported = headers(); - set_header( - &mut unsupported, - "x-registry-signature", - SIGNATURE.replacen("v1=", "v2=", 1), - ); - assert_eq!( - verify_hook_delivery(delivery(&unsupported, BODY, KEY)), - Err(BRegHookVerificationError::UnsupportedVersion) - ); +#[test] +fn the_default_window_is_300_seconds_in_both_directions() { + for offset in [-300, 300] { + verify(BRegHookFreshness::DefaultWindow, offset).unwrap(); + } + for offset in [-301, 301] { + assert_eq!( + verify(BRegHookFreshness::DefaultWindow, offset) + .unwrap_err() + .code(), + "stale-delivery" + ); + } +} - let mut tampered = headers(); - set_header(&mut tampered, "ce-type", "case-patched-v1"); - assert_eq!( - verify_hook_delivery(delivery(&tampered, BODY, KEY)), - Err(BRegHookVerificationError::SignatureMismatch) - ); +#[test] +fn a_named_window_replaces_the_default() { + let freshness = BRegHookFreshness::Within { + skew: Duration::from_secs(10), + }; + verify(freshness, 10).unwrap(); + assert_eq!(verify(freshness, 11).unwrap_err().code(), "stale-delivery"); +} - for error in [ - BRegHookVerificationError::MissingHeader, - BRegHookVerificationError::MalformedSignature, - BRegHookVerificationError::SignatureMismatch, - BRegHookVerificationError::UnsupportedVersion, - ] { - assert!(!error.to_string().contains(SIGNATURE)); - assert!(!error.to_string().contains("case-patched-v1")); - } +#[test] +fn caller_enforced_freshness_accepts_a_year_old_delivery() { + verify(BRegHookFreshness::CallerEnforced, 365 * 24 * 3600).unwrap(); } #[test] -fn invalid_delivery_time_names_the_delivery_time_fix() { - let mut invalid = headers(); - let vectors: serde_json::Value = serde_json::from_str(include_str!( - "../../registry-platform-crypto/tests/fixtures/delivery-signatures.json" - )) - .unwrap(); - let vector = vectors - .as_array() - .unwrap() - .iter() - .find(|value| value["valid"] == false) - .unwrap(); - set_header( - &mut invalid, - "x-registry-delivery-time", - vector["deliveryTime"].as_str().unwrap(), - ); - set_header( - &mut invalid, - "x-registry-signature", - vector["signature"].as_str().unwrap(), - ); - let error = verify_hook_delivery(delivery(&invalid, BODY, KEY)).unwrap_err(); - assert_eq!(error, BRegHookVerificationError::InvalidDeliveryTime); - assert_eq!(error.code(), "invalid-delivery-time"); +fn a_previous_key_verifies_a_rotated_delivery() { + let input = BRegHookDelivery { + headers: &headers( + ID, + &TS.to_string(), + "v1,VJrqYnKSCnccY0zIQARwZ/xIh/dVWuudwj1QQyTzYx0=", + ), + body: BODY, + key: KEY, + previous_key: Some(PREVIOUS), + freshness: BRegHookFreshness::CallerEnforced, + }; assert_eq!( - error.to_string(), - "the Base Registry Engine hook delivery time is invalid; check the signed delivery time and sender clock" + registry_breg_client::verify_hook_delivery(input) + .unwrap() + .id, + ID ); } #[test] -fn duplicate_header_names_the_header_fix() { - let mut duplicate = headers(); - duplicate.push(("ce-type".into(), "case-created-v1".into())); - let error = verify_hook_delivery(delivery(&duplicate, BODY, KEY)).unwrap_err(); - assert_eq!(error, BRegHookVerificationError::DuplicateHeader); - assert_eq!(error.code(), "duplicate-header"); +fn a_webhook_id_that_differs_from_the_envelope_id_is_refused() { + let input = BRegHookDelivery { + headers: &headers( + "00000000-0000-4000-8000-000000000002", + &TS.to_string(), + "v1,5utAVSfp86oJRURFYIoR2F3is1nWXe+aIL6vtd13e1Y=", + ), + body: BODY, + key: KEY, + previous_key: None, + freshness: BRegHookFreshness::CallerEnforced, + }; assert_eq!( - error.to_string(), - "a Base Registry Engine hook header is repeated; remove duplicate signed headers" + registry_breg_client::verify_hook_delivery(input) + .unwrap_err() + .code(), + "id-mismatch" ); } #[test] -fn oversized_body_names_the_body_size_fix() { - let oversized = vec![b'x'; 1_048_577]; - let error = verify_hook_delivery(delivery(&headers(), &oversized, KEY)).unwrap_err(); - assert_eq!(error, BRegHookVerificationError::BodyTooLarge); - assert_eq!(error.code(), "body-too-large"); - assert_eq!( - error.to_string(), - "the Base Registry Engine hook body exceeds the Version 1 limit; reduce the body size" - ); - assert!(!error.to_string().contains(&"x".repeat(64))); +fn an_invalid_key_names_its_length_and_newline_without_its_bytes() { + for (key, previous_key, expected) in [ + (&[b'x'; 31][..], None, "The current hook key is 31 bytes and must contain 32 to 64 exact bytes."), + (&[&[b'x'; 64][..], b"\n"].concat()[..], None, "The current hook key is 65 bytes including a trailing newline and must contain 32 to 64 exact bytes."), + (&b"whsec_synthetic_key_text_for_test"[..], None, "The current hook key starts with whsec_ and must be supplied as exact key bytes."), + (KEY, Some(KEY), "The previous hook key equals the current key. Pass the key the sender used before rotation, or omit the previous key."), + ] { + let error = registry_breg_client::verify_hook_delivery(BRegHookDelivery { + headers: &headers(ID, &TS.to_string(), SIGNATURE), + body: BODY, + key, + previous_key, + freshness: BRegHookFreshness::CallerEnforced, + }) + .unwrap_err(); + assert_eq!(error.code(), "invalid-key"); + let message = error.to_string(); + assert_eq!(message, expected); + assert!(!message.contains(std::str::from_utf8(key).unwrap())); + } } #[test] -fn invalid_key_names_the_key_configuration_fix() { - let error = verify_hook_delivery(delivery(&headers(), BODY, b"short-key")).unwrap_err(); - assert_eq!(error, BRegHookVerificationError::InvalidKey); - assert_eq!(error.code(), "invalid-key"); +fn refusal_codes_are_closed_and_value_free() { + use registry_breg_client::BRegHookVerificationError::*; + let errors = [ + MissingHeader, + DuplicateHeader, + InvalidContentType, + InvalidId, + InvalidTimestamp, + StaleDelivery, + MalformedSignature, + UnsupportedVersion, + SignatureMismatch, + BodyTooLarge, + InvalidKey { + detail: "configure a 32-byte key".into(), + }, + InvalidEnvelope, + IdMismatch, + ]; assert_eq!( - error.to_string(), - "the Base Registry Engine hook verification key is too short; configure a key of at least 32 bytes" + errors.each_ref().map(|error| error.code()), + [ + "missing-header", + "duplicate-header", + "invalid-content-type", + "invalid-id", + "invalid-timestamp", + "stale-delivery", + "malformed-signature", + "unsupported-version", + "signature-mismatch", + "body-too-large", + "invalid-key", + "invalid-envelope", + "id-mismatch", + ] ); - assert!(!error.to_string().contains("short-key")); + for error in errors { + assert!(!error.to_string().contains(ID)); + assert!(!error.to_string().contains(SIGNATURE)); + } } diff --git a/crates/registry-breg-client/tests/write_http_boundary.rs b/crates/registry-breg-client/tests/write_http_boundary.rs index cc1f8cfc00..3aff3e657b 100644 --- a/crates/registry-breg-client/tests/write_http_boundary.rs +++ b/crates/registry-breg-client/tests/write_http_boundary.rs @@ -2144,7 +2144,7 @@ fn problem_detail(code: BRegProblemCode) -> &'static str { "The record attachment slot already holds a file and is write-once." } Code::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", - Code::AuthenticationRefused => "The bearer credential is missing or refused.", + Code::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", Code::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." } @@ -2498,7 +2498,16 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { json!({"availability":{"available":null,"observedRevision":7, "reason":"input-required","guardReason":"misplaced","recovery":"correct-input", "missingInputs":["legalName"]}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardLabel":"A label without its reason.","recovery":"none"}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"é".repeat(257),"recovery":"none"}}), + json!({"availability":{"available":false,"observedRevision":7, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"label\ncanary","recovery":"none"}}), ]; + let malformed_count = malformed.len(); let fixture = test_client( std::iter::once(MockResponse::json(StatusCode::OK, metadata)) .chain(std::iter::once(MockResponse::json( @@ -2515,6 +2524,14 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { ) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"))) + .chain(std::iter::once(MockResponse::json( + StatusCode::OK, + json!({"availability":{"available":false,"observedRevision":9, + "reason":"guard-not-satisfied","guardReason":"legal_name_unchanged", + "guardLabel":"The legal name cannot change here.","recovery":"none"}}), + ) + .with_header("cache-control", "no-store") + .with_header("vary", "authorization, accept"))) .chain(malformed.into_iter().map(|body| MockResponse::json(StatusCode::OK, body) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"))) @@ -2568,7 +2585,17 @@ async fn action_availability_is_metadata_bound_validated_and_sent_once() { assert_eq!(unavailable.available(), Some(false)); assert_eq!(unavailable.observed_revision(), Some(8)); assert_eq!(unavailable.guard_reason(), Some("legal_name_unchanged")); - for _ in 0..6 { + // An authored guard label rides beside its reason. The client checks its + // bounds and, like every refusal text, does not retain it. + let labelled = fixture + .client + .action_availability(&action, &request) + .await + .unwrap() + .value; + assert_eq!(labelled.observed_revision(), Some(9)); + assert_eq!(labelled.guard_reason(), Some("legal_name_unchanged")); + for _ in 0..malformed_count { let error = fixture .client .action_availability(&action, &request) diff --git a/crates/registry-breg-mcp/src/config.rs b/crates/registry-breg-mcp/src/config.rs index cc98f55aa9..9e01fdbc42 100644 --- a/crates/registry-breg-mcp/src/config.rs +++ b/crates/registry-breg-mcp/src/config.rs @@ -25,12 +25,12 @@ use registry_platform_config::{ ConfigBlockError, ConfigBlockErrorKind, LoadedRuntimeConfig, PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, TlsTermination, }; +use registry_platform_httputil::loopback::loopback_host; use registry_platform_yaml::{ escape_pointer_segment, BoundedU64, Diagnostic, Invalid, LocalId, Report, RetiredApiVersion, UniqueList, Url, }; use serde::{Deserialize, Deserializer}; -use url::Host; /// apiVersion of the gateway runtime configuration document. pub const RUNTIME_API_VERSION: &str = "id.registrystack.org/formats/breg/mcp-runtime/v1alpha1"; @@ -303,7 +303,7 @@ impl RuntimeConfig { /// its retired apiVersion. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) } @@ -451,7 +451,7 @@ fn endpoint_findings( ]; for (pointer, endpoint) in endpoints { let url = endpoint.to_url(); - let secure = url.scheme() == "https" || (development && loopback_host(&url)); + let secure = url.scheme() == "https" || (development && is_loopback(&url)); if termination_known && !secure { findings.push(Finding::new( "breg.mcp-runtime.plain-http-endpoint", @@ -520,14 +520,11 @@ fn cross_member_findings( } } -fn loopback_host(url: &url::Url) -> bool { +fn is_loopback(url: &url::Url) -> bool { url.scheme() == "http" - && match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain == "localhost", - None => false, - } + && url + .host_str() + .is_some_and(|host| loopback_host(host).is_some()) } /// A value that satisfies the member at `pointer`, so a deferred expression @@ -1260,6 +1257,29 @@ rateLimits: ); } + #[test] + fn plain_http_follows_the_shared_loopback_definition() { + let development = + document().replace("operator-controlled-upstream", "development-loopback"); + for host in ["LOCALHOST", "127.0.0.2", "[::1]", "[::ffff:127.0.0.1]"] { + let config = development.replace( + "https://registry.example.test/", + &format!("http://{host}:8080/"), + ); + load(&config).unwrap_or_else(|_| panic!("{host} is loopback")); + } + for host in ["localhost.", "app.localhost", "[::ffff:10.0.0.1]"] { + refused( + &development.replace( + "https://registry.example.test/", + &format!("http://{host}:8080/"), + ), + "breg.mcp-runtime.plain-http-endpoint", + "/registry/baseUrl", + ); + } + } + #[test] fn an_endpoint_carries_no_query_or_fragment() { for (from, to, path) in [ diff --git a/crates/registry-breg-mcp/src/gateway/tests.rs b/crates/registry-breg-mcp/src/gateway/tests.rs index 094166d7be..6f705e0dcf 100644 --- a/crates/registry-breg-mcp/src/gateway/tests.rs +++ b/crates/registry-breg-mcp/src/gateway/tests.rs @@ -76,7 +76,7 @@ impl AuditCapture { fn capture_audit() -> (ToolAuditLog, AuditCapture) { let buffer = AuditBuffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); ( ToolAuditLog::new(writer.clone()), AuditCapture { writer, buffer }, @@ -132,7 +132,11 @@ impl Fixture { ); let audit = match override_audit { Some(audit) => audit, - None => ToolAuditLog::new(AuditWriter::open(destination).await.expect("audit opens")), + None => ToolAuditLog::new( + AuditWriter::open_without_posture(destination) + .await + .expect("audit opens"), + ), }; let (binding, provider) = breg_binding_for_test( ®istry_config, diff --git a/crates/registry-breg-mcp/src/runtime.rs b/crates/registry-breg-mcp/src/runtime.rs index 466788949d..9660d01452 100644 --- a/crates/registry-breg-mcp/src/runtime.rs +++ b/crates/registry-breg-mcp/src/runtime.rs @@ -77,6 +77,16 @@ fn resource_server_failure(error: ResourceServerError) -> StartupError { StartupError::ResourceServer(description) } +/// Reads the static key document. The refusal text names what the document +/// got wrong and carries no key material, so it goes to the operator's log. +fn static_key_fetcher(document: &[u8]) -> Result { + let keys = parse_static_jwks(document).map_err(|error| { + tracing::error!(%error, "the static key set was refused"); + StartupError::Key("resourceServer.jwksSource.documentRef") + })?; + Ok(JwksFetcher::new_static(keys, JwksFetcherConfig::defaults())) +} + fn resolver(config: &RuntimeConfig) -> Result { config.secret_providers.resolver().map_err(|error| { StartupError::Secret(describe_secret_failure( @@ -144,15 +154,13 @@ async fn assemble(config: &RuntimeConfig) -> Result { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolve( &secrets, "resourceServer.jwksSource.documentRef", document_ref, )?; - let keys = parse_static_jwks(document.expose_secret()) - .map_err(|_| StartupError::Key("resourceServer.jwksSource.documentRef"))?; - JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) + static_key_fetcher(document.expose_secret())? } }; let resource_options = ResourceServerOptions { @@ -226,7 +234,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { .audit .destination() .map_err(|error| StartupError::Audit(error.to_string()))?; - let audit = ToolAuditLog::new(AuditWriter::open(destination).await?); + let audit = ToolAuditLog::new(AuditWriter::open_without_posture(destination).await?); let resource = config.resource_server.resource.to_url(); let info = GatewayInfo::new( "breg-mcp", @@ -274,6 +282,41 @@ where mod tests { use super::*; + /// A public EC key as a provider publishes it, with members the verifier + /// does not read. + fn provider_key_set(extra: &str) -> Vec { + format!( + r#"{{"keys":[{{"kty":"EC","crv":"P-256","kid":"key-1","use":"sig","alg":"ES256","ext":true,"x5c":["MIIB"],"x5t":"abc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"{extra}}}]}}"# + ) + .into_bytes() + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + static_key_fetcher(&provider_key_set("")) + .expect("a provider key set with ext and x5c members loads"); + } + + #[test] + fn a_static_key_set_with_a_private_member_keeps_its_code_and_logs_the_validator_text() { + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let error = tracing::dispatcher::with_default(&logs.subscriber(), || { + let Err(error) = static_key_fetcher(&provider_key_set(r#","d":"CANARY-PRIVATE""#)) + else { + panic!("a private member is refused"); + }; + error + }); + assert!(matches!( + error, + StartupError::Key("resourceServer.jwksSource.documentRef") + )); + let text = logs.text(); + assert!(text.contains("private-key member"), "{text}"); + assert!(!text.contains("CANARY-PRIVATE"), "{text}"); + assert!(!error.to_string().contains("CANARY-PRIVATE")); + } + #[test] fn neutral_principal_rate_limit_uses_breg_public_name() { let error = resource_server_failure(ResourceServerError::RateLimit("perPrincipal")); diff --git a/crates/registry-breg-review/src/config.rs b/crates/registry-breg-review/src/config.rs index 8e5f7239b4..64574af592 100644 --- a/crates/registry-breg-review/src/config.rs +++ b/crates/registry-breg-review/src/config.rs @@ -24,13 +24,12 @@ use registry_platform_config::{ PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, SecretReference, TlsTermination, }; -use registry_platform_httputil::{valid_resource_uri, valid_scope_token}; +use registry_platform_httputil::{loopback::loopback_host, valid_resource_uri, valid_scope_token}; use registry_platform_yaml::{ escape_pointer_segment, BoundedU32, BoundedU64, Diagnostic, ExternalId, Invalid, LocalId, Report, RetiredApiVersion, UniqueList, Url, }; use serde::{de, Deserialize, Deserializer}; -use url::Host; /// apiVersion of the review page runtime configuration document. pub const RUNTIME_API_VERSION: &str = "id.registrystack.org/formats/breg/review-runtime/v1alpha1"; @@ -505,7 +504,7 @@ impl RuntimeConfig { /// and its retired apiVersion. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) } @@ -682,7 +681,7 @@ fn endpoint_findings( ]; for (pointer, endpoint) in endpoints { let url = endpoint.to_url(); - let secure = url.scheme() == "https" || (development && loopback_host(&url)); + let secure = url.scheme() == "https" || (development && is_loopback(&url)); if termination_known && !secure { findings.push(Finding::new( "breg.review-runtime.plain-http-endpoint", @@ -713,14 +712,11 @@ fn endpoint_findings( } } -fn loopback_host(url: &url::Url) -> bool { +fn is_loopback(url: &url::Url) -> bool { url.scheme() == "http" - && match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain == "localhost", - None => false, - } + && url + .host_str() + .is_some_and(|host| loopback_host(host).is_some()) } /// Whether `url`, read from the provider's discovery document, is an @@ -729,7 +725,7 @@ fn loopback_host(url: &url::Url) -> bool { pub(crate) fn allowed_discovered_endpoint(url: &url::Url, development: bool) -> bool { let secure = match url.scheme() { "https" => true, - "http" => development && loopback_host(url), + "http" => development && is_loopback(url), _ => false, }; secure @@ -1355,6 +1351,21 @@ audit: ); } + #[test] + fn plain_http_follows_the_shared_loopback_definition() { + for host in ["LOCALHOST", "127.0.0.2", "[::ffff:127.0.0.1]"] { + load(&development().replace("http://127.0.0.1:9000", &format!("http://{host}:9000"))) + .unwrap_or_else(|_| panic!("{host} is loopback")); + } + for host in ["localhost.", "app.localhost", "[::ffff:10.0.0.1]"] { + refused( + &development().replace("http://127.0.0.1:9000", &format!("http://{host}:9000")), + "breg.review-runtime.plain-http-endpoint", + "/signIn/issuer", + ); + } + } + #[test] fn the_shared_listener_requires_an_explicit_bind() { let omitted = development().replace(" bind: 127.0.0.1:8115\n", ""); diff --git a/crates/registry-breg-review/src/journal.rs b/crates/registry-breg-review/src/journal.rs index b77d6ade2e..42d53d984f 100644 --- a/crates/registry-breg-review/src/journal.rs +++ b/crates/registry-breg-review/src/journal.rs @@ -219,7 +219,7 @@ mod tests { } fn journal(lines: &Lines) -> (Journal, AuditWriter) { - let writer = AuditWriter::from_line_sink(Box::new(lines.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(lines.clone())); let journal = Journal::new( writer.clone(), AuditProfile::unkeyed_dev_only().key_hasher(), diff --git a/crates/registry-breg-review/src/lib.rs b/crates/registry-breg-review/src/lib.rs index 14eccf5fb4..f405f55fb4 100644 --- a/crates/registry-breg-review/src/lib.rs +++ b/crates/registry-breg-review/src/lib.rs @@ -44,7 +44,7 @@ use jsonwebtoken::Algorithm; use registry_breg_client::{BaseRegistryClient, BaseRegistryClientConfig}; use registry_platform_audit::{AuditProfile, AuditWriter}; use registry_platform_crypto::PrivateJwk; -use registry_platform_httpsec::{security_headers, CspBuilder}; +use registry_platform_httpsec::{security_headers_without_posture, CspBuilder}; use registry_platform_httputil::client::{PrivateKeyJwt, PrivateKeyJwtConfig}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ @@ -683,7 +683,7 @@ async fn build(config: RuntimeConfig, writer: Option) -> Result writer, - None => AuditWriter::open( + None => AuditWriter::open_without_posture( config .audit .destination() @@ -727,7 +727,7 @@ async fn build(config: RuntimeConfig, writer: Option) -> Result { - let writer = registry_platform_audit::AuditWriter::from_line_sink(Box::new(sink)); + let writer = registry_platform_audit::AuditWriter::from_line_sink_without_posture( + Box::new(sink), + ); registry_breg_review::router_with_audit_writer(config, writer).await } None => registry_breg_review::router(config).await, diff --git a/crates/registry-breg/Cargo.toml b/crates/registry-breg/Cargo.toml index 42da9de42b..84c2011253 100644 --- a/crates/registry-breg/Cargo.toml +++ b/crates/registry-breg/Cargo.toml @@ -328,13 +328,13 @@ registry-platform-canonical-json.workspace = true registry-platform-calendar.workspace = true registry-manifest-core.workspace = true registry-platform-audit = { workspace = true, optional = true } -registry-platform-authcommon = { workspace = true, optional = true } +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"], optional = true } registry-platform-buildinfo = { workspace = true, optional = true } registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-dispatch = { workspace = true, features = ["postgres"], optional = true } registry-platform-hooks = { workspace = true, features = ["rhai"] } -registry-platform-httpsec = { workspace = true, features = ["server"], optional = true } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"], optional = true } registry-platform-httputil = { workspace = true, optional = true } registry-platform-metrics = { workspace = true, optional = true } registry-platform-objectstore = { workspace = true, optional = true } @@ -375,7 +375,7 @@ futures-core.workspace = true tempfile.workspace = true rcgen.workspace = true registry-evidence-authoring.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "token-fixtures"] } registry-breg-client.workspace = true tokio-rustls.workspace = true tower.workspace = true @@ -511,6 +511,16 @@ name = "http_auth" path = "tests/http_auth.rs" required-features = ["runtime"] +[[test]] +name = "authentication_refusals" +path = "tests/authentication_refusals.rs" +required-features = ["runtime"] + +[[test]] +name = "concealment_refusals" +path = "tests/concealment_refusals.rs" +required-features = ["runtime"] + [[test]] name = "http_read_only" path = "tests/http_read_only.rs" @@ -521,6 +531,11 @@ name = "issuer_portability" path = "tests/issuer_portability.rs" required-features = ["runtime"] +[[test]] +name = "token_characterisation" +path = "tests/token_characterisation.rs" +required-features = ["runtime"] + [[test]] name = "migration_plan" path = "tests/migration_plan.rs" diff --git a/crates/registry-breg/src/access_preview.rs b/crates/registry-breg/src/access_preview.rs index 07da382a53..69be9fd08c 100644 --- a/crates/registry-breg/src/access_preview.rs +++ b/crates/registry-breg/src/access_preview.rs @@ -92,7 +92,9 @@ pub fn preview_access( if !operation_granted { Some("operation-not-granted") } else { - authorize_profile_claims(profile, &claims).err() + authorize_profile_claims(profile, &claims) + .err() + .map(|refusal| refusal.reason) } } }; diff --git a/crates/registry-breg/src/api/access_log.rs b/crates/registry-breg/src/api/access_log.rs index 3462bcd27c..7d4c7c4d1a 100644 --- a/crates/registry-breg/src/api/access_log.rs +++ b/crates/registry-breg/src/api/access_log.rs @@ -50,7 +50,7 @@ async fn read( let mut surface = match super::authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -58,7 +58,7 @@ async fn read( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; } @@ -78,17 +78,23 @@ async fn read( ) .await; } - if claims.principal().is_none() - || record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) + let refused_check = if claims.principal().is_none() { + Some(FailedCheck::TokenClaims) + } else if record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) || headers.contains_key(crate::subject_access_log::REQUESTER_HEADER) || headers.contains_key(crate::subject_access_log::PURPOSE_HEADER) { + Some(FailedCheck::Visibility) + } else { + None + }; + if let Some(check) = refused_check { return audited_read_refusal( &service, &route, &surface, record_id, - concealed(), + concealed(check), &correlation, ) .await; @@ -121,7 +127,7 @@ async fn read( .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response } - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::CursorInvalid) => cursor_invalid(), Err(_) => unavailable(), } diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index f368f1317a..21815a5617 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -111,35 +111,54 @@ fn authorize_action<'a>( claims: &VerifiedRequestClaims, options: &QueryOptions, ) -> Option> { - service.mutations.as_ref()?; + authorize_action_checked(service, route, claims, options).ok() +} + +/// The admission of one Action route. The refusal names the first check that +/// failed, for the operator only. +fn authorize_action_checked<'a>( + service: &'a HttpService, + route: &'a CompiledActionRoute, + claims: &VerifiedRequestClaims, + options: &QueryOptions, +) -> Result, FailedCheck> { + if service.mutations.is_none() { + return Err(FailedCheck::Visibility); + } let inventory = service.registry.actions(); // A caller cannot construct an alternate path, operation or action under a // valid route identifier. Discovery and dispatch use this same inventory. if !inventory.routes.contains(route) || !matches!(route.operation, Operation::Invoke | Operation::Start) { - return None; + return Err(FailedCheck::Operation); } - let access = inventory.access.iter().find(|entry| { - entry.route_id == route.id - && entry.action_id == route.action_id - && entry.operation == route.operation - })?; + let access = inventory + .access + .iter() + .find(|entry| { + entry.route_id == route.id + && entry.action_id == route.action_id + && entry.operation == route.operation + }) + .ok_or(FailedCheck::AccessProfile)?; let selected = options .access_profile() .map(String::as_str) - .or(access.default_profile_id.as_deref())?; + .or(access.default_profile_id.as_deref()) + .ok_or(FailedCheck::AccessProfile)?; if !access.profile_ids.contains(selected) || !route.access_profiles.iter().any(|id| id == selected) { - return None; + return Err(FailedCheck::AccessProfile); } let action = inventory .actions .iter() - .find(|action| action.id == route.action_id)?; + .find(|action| action.id == route.action_id) + .ok_or(FailedCheck::Operation)?; if route.operation == Operation::Start { - proposals::authorize( + proposals::authorize_checked( &service.registry, action, claims, @@ -151,27 +170,36 @@ fn authorize_action<'a>( && (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) { - return None; + return Err(FailedCheck::TaskGrantMissing); } let grant = action .permissions .iter() - .find(|grant| grant.profile_id == selected)?; - if !grant.operations.contains(&route.operation) - || grant.principal_claim.as_deref() != claims.principal_claim() - || !grant - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - || (!grant.required_purposes.is_empty() - && !claims - .purpose() - .is_some_and(|purpose| grant.required_purposes.contains(purpose))) + .find(|grant| grant.profile_id == selected) + .ok_or(FailedCheck::AccessProfile)?; + if !grant.operations.contains(&route.operation) { + return Err(FailedCheck::Operation); + } + if grant.principal_claim.as_deref() != claims.principal_claim() { + return Err(FailedCheck::TokenClaims); + } + if !grant + .required_scopes + .iter() + .all(|scope| claims.has_scope(scope)) { - return None; + claims.declare_scope_refusal(&grant.required_scopes, Some(&grant.profile_id)); + return Err(FailedCheck::Scope); + } + if !grant.required_purposes.is_empty() + && !claims + .purpose() + .is_some_and(|purpose| grant.required_purposes.contains(purpose)) + { + return Err(FailedCheck::Purpose); } if let Some(expected) = grant.actor_kind { - let actual = claims.actor_kind()?; + let actual = claims.actor_kind().ok_or(FailedCheck::ActorKind)?; if !matches!( (expected, actual), ( @@ -185,14 +213,14 @@ fn authorize_action<'a>( registry_platform_oidc::ActorKind::Service ) ) { - return None; + return Err(FailedCheck::ActorKind); } if route.operation == Operation::Invoke && expected == crate::contract::ActorKindSource::Agent && claims.actor_subject().is_none() && claims.grant().is_none() { - return None; + return Err(FailedCheck::TaskGrantMissing); } } // A delegated token acts for its principal; only a grant written for @@ -200,18 +228,18 @@ fn authorize_action<'a>( if claims.actor_subject().is_some() && grant.actor_kind != Some(crate::contract::ActorKindSource::Agent) { - return None; + return Err(FailedCheck::Delegation); } if !grant.requester_clients.is_empty() && !claims .requester_client() .is_some_and(|client| grant.requester_clients.contains(client)) { - return None; + return Err(FailedCheck::RequesterClient); } - let principal = claims.principal()?; + let principal = claims.principal().ok_or(FailedCheck::TokenClaims)?; let task_grant = if route.operation == Operation::Invoke { - action_task_grant_binding(action, grant, claims).ok()? + action_task_grant_binding(action, grant, claims)? } else { None }; @@ -224,8 +252,9 @@ fn authorize_action<'a>( verified_row_boundaries_from_sources(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; - Some(AuthorizedActionSurface { + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; + Ok(AuthorizedActionSurface { route, action, context: AuthorizedActionContext::new( @@ -245,31 +274,34 @@ fn action_task_grant_binding( action: &CompiledAction, permission: &crate::model::CompiledActionPermission, claims: &VerifiedRequestClaims, -) -> Result, ()> { +) -> Result, FailedCheck> { match (&permission.task_grant, claims.grant()) { (None, None) => Ok(None), (Some(source), Some(grant)) => { - if permission.actor_kind != Some(crate::contract::ActorKindSource::Agent) - || !grant - .bounds() - .breg_permissions() - .is_some_and(|permissions| { - permissions.iter().any(|bound| { - bound.collection() == format!("action:{}", action.id) - && bound - .operations() - .iter() - .any(|operation| operation == "invoke") - }) + if permission.actor_kind != Some(crate::contract::ActorKindSource::Agent) { + return Err(FailedCheck::ActorKind); + } + if !grant + .bounds() + .breg_permissions() + .is_some_and(|permissions| { + permissions.iter().any(|bound| { + bound.collection() == format!("action:{}", action.id) + && bound + .operations() + .iter() + .any(|operation| operation == "invoke") }) + }) { - return Err(()); + return Err(FailedCheck::TaskGrantScope); } bind_task_grant(&source.source_issuer, claims) .map(Some) - .map_err(|_| ()) + .map_err(|refusal| refusal.check) } - _ => Err(()), + (Some(_), None) => Err(FailedCheck::TaskGrantMissing), + (None, Some(_)) => Err(FailedCheck::TaskGrantScope), } } @@ -284,7 +316,7 @@ pub(super) async fn dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (options, valid_options) = match QueryOptions::parse(raw_query.as_deref(), false) { Ok(options) => (options, true), @@ -293,10 +325,11 @@ pub(super) async fn dispatch( let refusal = |response| action_refusal(mutations, &route, &claims, &options, &correlation, response); if !valid_options { - return refusal(concealed()).await; + return refusal(concealed(FailedCheck::Visibility)).await; } - let Some(surface) = authorize_action(&service, &route, &claims, &options) else { - return refusal(concealed()).await; + let surface = match authorize_action_checked(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(check) => return refusal(concealed(check)).await, }; if !single_content_type(&headers, "application/json") { return refusal(unsupported_media_type()).await; @@ -398,12 +431,23 @@ pub(super) async fn dispatch( ) .await { - Ok(availability::Availability::NotSatisfied { guard_reason, .. }) => { - crate::correlation::action_guard_failure_response(guard_reason) - } + Ok(availability::Availability::NotSatisfied { + guard_reason, + guard_label, + .. + }) => crate::correlation::note_refusal( + crate::correlation::action_guard_failure_response( + guard_reason, + guard_label, + ), + FailedCheck::ActionGuard, + ), // Visibility and the record may have changed since rollback. // Never turn the private cause into an existence oracle. - _ => precondition_failed(), + _ => crate::correlation::note_refusal( + precondition_failed(), + FailedCheck::ActionGuard, + ), } } Err(error) => mutation_problem(error), @@ -421,7 +465,9 @@ pub(super) async fn dispatch( .await { Ok(response) => exact_non_record_no_store(response), - Err(crate::mutation::MutationError::PreconditionFailed) => concealed(), + Err(crate::mutation::MutationError::PreconditionFailed) => { + concealed(FailedCheck::RowBoundary) + } Err(error) => mutation_problem(error), } } diff --git a/crates/registry-breg/src/api/actions/availability.rs b/crates/registry-breg/src/api/actions/availability.rs index 5f1e89ea6b..93eb72ffb1 100644 --- a/crates/registry-breg/src/api/actions/availability.rs +++ b/crates/registry-breg/src/api/actions/availability.rs @@ -14,6 +14,7 @@ pub(super) enum Availability { NotSatisfied { revision: u64, guard_reason: Option, + guard_label: Option, }, InputRequired { revision: u64, @@ -31,6 +32,7 @@ impl Availability { Self::NotSatisfied { revision, guard_reason, + guard_label, } => { let mut value = json!({ "available": false, "observedRevision": revision, @@ -38,6 +40,9 @@ impl Availability { }); if let Some(reason) = guard_reason { value["guardReason"] = json!(reason); + if let Some(label) = guard_label { + value["guardLabel"] = json!(label); + } } value } @@ -143,6 +148,7 @@ pub(super) async fn observe( return Ok(Availability::NotSatisfied { revision, guard_reason: guard.reason.clone(), + guard_label: guard.label.clone(), }); } } @@ -238,7 +244,7 @@ pub(in crate::api) async fn observe_target( ReadServiceError::FieldEncryptionUnavailable => field_encryption_unavailable(), _ => unavailable(), })? - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; // Held bytes have already passed the ordinary GET terminal audit gate. let value: Value = serde_json::from_slice(read.body()).map_err(|_| unavailable())?; let data = value @@ -277,7 +283,48 @@ pub(in crate::api) async fn observe_target( ) .map_err(|_| unavailable())? { - return Err(concealed()); + return Err(concealed(FailedCheck::RowBoundary)); } Ok(Some(ObservedTarget { revision, current })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_satisfied_guard_label_rides_only_beside_its_reason() { + let labelled = Availability::NotSatisfied { + revision: 3, + guard_reason: Some("not-submitted".into()), + guard_label: Some("Only a submitted application can be approved.".into()), + }; + assert_eq!( + labelled.value(), + json!({ + "available": false, "observedRevision": 3, + "reason": "guard-not-satisfied", "recovery": "none", + "guardReason": "not-submitted", + "guardLabel": "Only a submitted application can be approved." + }) + ); + let unlabelled = Availability::NotSatisfied { + revision: 3, + guard_reason: Some("not-submitted".into()), + guard_label: None, + }; + assert!(unlabelled.value().get("guardLabel").is_none()); + let orphan = Availability::NotSatisfied { + revision: 3, + guard_reason: None, + guard_label: Some("A label without its reason.".into()), + }; + assert!(orphan.value().get("guardLabel").is_none()); + assert!(Availability::NotDisclosed + .value() + .as_object() + .unwrap() + .keys() + .all(|key| !key.starts_with("guard"))); + } +} diff --git a/crates/registry-breg/src/api/attachments.rs b/crates/registry-breg/src/api/attachments.rs index 412a09eafa..fb52f50999 100644 --- a/crates/registry-breg/src/api/attachments.rs +++ b/crates/registry-breg/src/api/attachments.rs @@ -71,40 +71,47 @@ async fn authorize( method: HttpMethod, correlation: &RequestCorrelation, ) -> Result<(String, ProposalAuthority), Response> { - let mutations = service.mutations.as_ref().ok_or_else(concealed)?; + let mutations = service + .mutations + .as_ref() + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let action_id = mutations .proposal_action_id(id) .await .map_err(super::proposals::proposal_problem)? - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let action = service .registry .actions() .actions .iter() .find(|action| action.id == action_id) - .ok_or_else(concealed)?; + .ok_or_else(|| concealed(FailedCheck::Visibility))?; let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return Err(concealed()); + return Err(concealed(FailedCheck::Operation)); }; - let Some(authority) = super::proposals::authorize( + let authority = match super::proposals::authorize_checked( &service.registry, action, claims, selected, ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return Err(super::proposals::known_action_refusal( - mutations, - action, - claims, - selected, - ProposalAuthorityOperation::Lifecycle(operation), - method, - correlation, - ) - .await); + ) { + Ok(authority) => authority, + Err(check) => { + return Err(super::proposals::known_action_refusal( + mutations, + action, + claims, + selected, + ProposalAuthorityOperation::Lifecycle(operation), + method, + correlation, + check, + ) + .await); + } }; let grant = proposal.permissions.iter().find(|grant| { grant.profile_id == authority.common.access_profile() @@ -125,7 +132,7 @@ async fn authorize( &authority, method, correlation, - concealed(), + concealed(FailedCheck::Operation), ) .await); } @@ -145,13 +152,13 @@ async fn mutate( removal: bool, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = super::proposals::selected_profile(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (action_id, authority) = match authorize( &service, @@ -211,7 +218,7 @@ async fn mutate( .find(|action| action.id == action_id) .expect("admitted Action"); let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return concealed(); + return concealed(FailedCheck::Operation); }; let definition = &proposal.attachments[&slot]; let (content_type, bytes) = if removal { @@ -322,13 +329,13 @@ async fn download( RawQuery(raw): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(query) = parse_download_query(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let (field, operation) = match &query.review { Some(review) => ( @@ -360,7 +367,7 @@ async fn download( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(records) = super::proposals::review_record_authorities( &service.registry, @@ -375,7 +382,7 @@ async fn download( &authority, HttpMethod::Get, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -411,7 +418,7 @@ async fn download( .header(VARY, "authorization") .body(Body::from(bytes)) .unwrap_or_else(|_| unavailable()), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => super::proposals::proposal_problem(error), } } diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index 86174dc862..1c338605eb 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -85,6 +85,16 @@ pub struct VerifiedRequestClaims { grant_subjects: BTreeMap, human_identity: Option, recipients: BTreeSet, + scope_declaration: Option, +} + +/// Where a scope refusal records the values the operator declared: the name of +/// the claim that carries scopes, and the request's slot for the recording +/// layer. Both come from configuration and the request, never from the token. +#[derive(Clone, Debug, Eq, PartialEq)] +struct ScopeDeclaration { + scope_claim: std::sync::Arc, + slot: crate::correlation::DeclaredScopeSlot, } /// The verified claims of an authenticated caller, as a handler extractor. @@ -106,11 +116,56 @@ impl axum::extract::FromRequestParts for Authenticated { .get::() .cloned() .map(Self) - .ok_or_else(crate::auth::authentication_refused) + .ok_or_else(|| { + crate::auth::authentication_refused( + registry_platform_authcommon::FailedCheck::CredentialMissing, + ) + }) } } impl VerifiedRequestClaims { + /// Bind the claims to the request's recording slot, so a scope refusal can + /// name the configured scope claim. + #[must_use] + pub(crate) fn with_scope_declaration( + mut self, + scope_claim: &str, + slot: crate::correlation::DeclaredScopeSlot, + ) -> Self { + self.scope_declaration = Some(ScopeDeclaration { + scope_claim: scope_claim.into(), + slot, + }); + self + } + + /// Record, for the operator's refusal line, the scope the operation needs + /// and the access profile that was applied. Both are declared by the + /// package, never read from the token. The first required scope the token + /// lacks is the one named. + pub(crate) fn declare_scope_refusal<'a>( + &self, + required_scopes: impl IntoIterator, + access_profile: Option<&str>, + ) { + let Some(declaration) = &self.scope_declaration else { + return; + }; + let mut declared = + registry_platform_authcommon::DeclaredScope::new(&*declaration.scope_claim); + if let Some(scope) = required_scopes + .into_iter() + .find(|scope| !self.has_scope(scope)) + { + declared = declared.with_required_scope(scope); + } + if let Some(profile) = access_profile { + declared = declared.with_access_profile(profile); + } + declaration.slot.set(declared); + } + pub fn authenticated( principal_claim: impl Into, principal: impl Into, @@ -137,6 +192,7 @@ impl VerifiedRequestClaims { grant_subjects: BTreeMap::new(), human_identity: None, recipients: BTreeSet::new(), + scope_declaration: None, }) } diff --git a/crates/registry-breg/src/api/external_views.rs b/crates/registry-breg/src/api/external_views.rs index 6c7a752fe9..ee9fc8847d 100644 --- a/crates/registry-breg/src/api/external_views.rs +++ b/crates/registry-breg/src/api/external_views.rs @@ -178,20 +178,27 @@ fn root_context( access_profile: Option, claims: &VerifiedRequestClaims, headers: &HeaderMap, -) -> Option { - let route = service.registry.routes().routes.iter().find(|route| { - route.entity_id == view.record_type.as_str() - && route.operation == operation - && read_path_for_route(service, route).is_none() - })?; +) -> Result { + let route = service + .registry + .routes() + .routes + .iter() + .find(|route| { + route.entity_id == view.record_type.as_str() + && route.operation == operation + && read_path_for_route(service, route).is_none() + }) + .ok_or(FailedCheck::AccessProfile)?; let mut options = QueryOptions::default(); options.parsed.access_profile = access_profile; - let authorised = authorize_route(service, route, claims, &options)?; + let authorised = authorize_route_with_reason(service, route, claims, &options) + .map_err(|refusal| refusal.check)?; let mut context = authorised.context; context .bind_access_attribution(authorised.response_entity, headers) - .ok()?; - Some(context) + .map_err(|_| FailedCheck::Delegation)?; + Ok(context) } fn refresh_deadline( @@ -354,7 +361,7 @@ fn worker_request( &claims, &HeaderMap::new(), ) - .ok_or(ExternalViewError::Concealed)?; + .map_err(|_| ExternalViewError::Concealed)?; Ok(ExternalViewRequest { context, correlation: RequestCorrelation::breg_created(), @@ -378,25 +385,44 @@ async fn admit_source_change( request: axum::extract::Request, ) -> Response { let Some(backend) = service.external_views.as_ref() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(plan) = backend.managed_plan(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let permits = |notifier: &crate::external_refresh_config::ResolvedExternalRefreshNotifier| { - claims.actor_kind() == Some(ActorKind::Service) - && claims.principal().is_some() - && claims.requester_client() == Some(notifier.requester_client.as_str()) - && claims.has_scope(¬ifier.required_scope) + if claims.actor_kind() != Some(ActorKind::Service) { + Err(FailedCheck::ActorKind) + } else if claims.principal().is_none() { + Err(FailedCheck::TokenClaims) + } else if claims.requester_client() != Some(notifier.requester_client.as_str()) { + Err(FailedCheck::RequesterClient) + } else if !claims.has_scope(¬ifier.required_scope) { + claims.declare_scope_refusal([¬ifier.required_scope], None); + Err(FailedCheck::Scope) + } else { + Ok(()) + } }; - if !plan.notifiers.values().any(permits) { - return concealed(); + if !plan + .notifiers + .values() + .any(|notifier| permits(notifier).is_ok()) + { + let check = plan + .notifiers + .values() + .find_map(|notifier| permits(notifier).err()) + .unwrap_or(FailedCheck::AccessProfile); + return concealed(check); } let Some(change) = refresh_body::(request).await else { return invalid_request(); }; - if !plan.notifiers.get(&change.projection).is_some_and(permits) { - return concealed(); + match plan.notifiers.get(&change.projection).map(permits) { + Some(Ok(())) => {} + Some(Err(check)) => return concealed(check), + None => return concealed(FailedCheck::AccessProfile), } if !service .registry @@ -404,7 +430,7 @@ async fn admit_source_change( .projections .contains_key(&change.projection) { - return concealed(); + return concealed(FailedCheck::Visibility); } if !registry_adapter_core::projection_token_valid(&change.selector) { return invalid_request(); @@ -516,14 +542,14 @@ async fn handle( ) -> Response { let inventory = service.registry.external_views(); let Some(view) = inventory.views.get(&target.view) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(link) = view .links .iter() .find(|link| link.id.as_str() == target.link) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(projection) = inventory.projections.get(link.projection.as_str()) else { return unavailable(); @@ -535,26 +561,27 @@ async fn handle( Operation::List }; let profile_selection = admission_profile(raw.as_deref()); - let Some(context) = root_context( + let context = match root_context( service, view, root_operation, profile_selection.clone(), claims, headers, - ) else { - return concealed(); + ) { + Ok(context) => context, + Err(check) => return concealed(check), }; let profile = context.selected_profile(); if context.purpose() != Some(projection.purpose.as_str()) { - return concealed(); + return concealed(FailedCheck::Purpose); } let grant = if target.refresh { let Some(ids) = inventory.refresh.get(profile) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if projection.mode != ExternalProjectionMode::Indexed || !ids.contains(&projection.id) { - return concealed(); + return concealed(FailedCheck::Visibility); } None } else { @@ -564,20 +591,20 @@ async fn handle( .and_then(|views| views.get(&target.view)) .and_then(|grant| grant.links.iter().find(|grant| grant.link == link.id)) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if !is_detail && (projection.mode != ExternalProjectionMode::Indexed || projection.cardinality != ExternalCardinality::One) { - return concealed(); + return concealed(FailedCheck::Visibility); } Some(grant) }; let root = match target.root { Some(root) => match Uuid::parse_str(&root) { Ok(id) if id.hyphenated().to_string() == root => Some(id), - _ => return concealed(), + _ => return concealed(FailedCheck::Visibility), }, None => None, }; @@ -627,7 +654,7 @@ async fn handle( fn external_view_problem(error: ExternalViewError) -> Response { match error { - ExternalViewError::Concealed => concealed(), + ExternalViewError::Concealed => concealed(FailedCheck::Visibility), ExternalViewError::InvalidCursor => cursor_invalid(), ExternalViewError::Incomplete => fixed_problem(ProblemCode::ExternalViewIncomplete), ExternalViewError::Unavailable => unavailable(), @@ -880,8 +907,10 @@ mod tests { plan.worker.required_scopes = BTreeSet::from(["registry:licensing:read".to_owned()]); let officer = &service.registry.entities()["licence"].access_profiles["officer"]; assert_eq!( - crate::api::authorize_profile_claims(officer, &plan.worker_claims().unwrap()).err(), - Some("actor-kind-mismatched") + crate::api::authorize_profile_claims(officer, &plan.worker_claims().unwrap()) + .err() + .map(|refusal| (refusal.reason, refusal.check)), + Some(("actor-kind-mismatched", FailedCheck::ActorKind)) ); assert!(refused(&service, &plan)); } diff --git a/crates/registry-breg/src/api/gis.rs b/crates/registry-breg/src/api/gis.rs index f0420b2e6b..4b7ea04a87 100644 --- a/crates/registry-breg/src/api/gis.rs +++ b/crates/registry-breg/src/api/gis.rs @@ -29,6 +29,7 @@ use crate::correlation::RequestCorrelation; use crate::cursor::{CursorAdapter, CursorRepresentation}; use crate::model::{CompiledEntity, CompiledQueryKind, CompiledQueryOperation, CompiledRoute}; use crate::query as strict_query; +use registry_platform_authcommon::FailedCheck; const GIS_ROOT: &str = "/v1/gis"; const SERVICE_DESC_MEDIA_TYPE: &str = "application/vnd.oai.openapi+json;version=3.0"; @@ -247,8 +248,10 @@ async fn collection( RawQuery(raw_query): RawQuery, Path(collection): Path, ) -> Response { - let Some(collection) = authorize_gis_collection(&service, &claims, &collection) else { - return concealed(); + let collection = match authorize_gis_collection_with_reason(&service, &claims, &collection) { + Some(Ok(collection)) => collection, + Some(Err(refusal)) => return concealed(refusal.refusal.check), + None => return concealed(FailedCheck::Visibility), }; if parse_metadata_query(raw_query.as_deref()).is_err() { return invalid_query(); @@ -270,7 +273,7 @@ async fn items( let mut authorized = match authorize_gis_collection_with_reason(&service, &claims, &collection) { Some(Ok(authorized)) => authorized, - Some(Err(refusal)) if refusal.reason == ReadRefusalReason::ProfileAdmission => { + Some(Err(refusal)) if refusal.refusal.reason == ReadRefusalReason::ProfileAdmission => { return audited_read_concealment( &service, refusal.route, @@ -278,11 +281,12 @@ async fn items( &claims, None, &correlation, - refusal.reason, + refusal.refusal, ) .await; } - Some(Err(_)) | None => return concealed(), + Some(Err(refusal)) => return concealed(refusal.refusal.check), + None => return concealed(FailedCheck::Visibility), }; if let Err(binding) = authorized .surface @@ -400,7 +404,7 @@ async fn items( &claims, None, &correlation, - crate::audit::ReadRefusalReason::SelectOverreach, + super::RouteRefusal::select_overreach(), ) .await; } @@ -434,7 +438,7 @@ async fn items( struct GisAdmissionRefusal<'a> { route: &'a CompiledRoute, profile_id: &'a str, - reason: ReadRefusalReason, + refusal: super::RouteRefusal, } struct AuthorizedGisCollection<'a> { @@ -547,11 +551,11 @@ fn authorize_gis_collection_with_reason<'a>( let options = profile_query_options(&operation.profile_id); let surface = match authorize_route_with_reason(service, route, claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return Some(Err(GisAdmissionRefusal { route, profile_id: &operation.profile_id, - reason, + refusal, })) } }; diff --git a/crates/registry-breg/src/api/ingestion.rs b/crates/registry-breg/src/api/ingestion.rs index a92e1e0b43..889600bbdd 100644 --- a/crates/registry-breg/src/api/ingestion.rs +++ b/crates/registry-breg/src/api/ingestion.rs @@ -103,7 +103,7 @@ async fn create_run( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -113,19 +113,24 @@ async fn create_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -202,7 +207,7 @@ async fn list_runs( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let admission = match ingestion_list_admission_options(raw_query.as_deref()) { Ok(options) => options, @@ -214,20 +219,25 @@ async fn list_runs( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; } }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &admission) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &admission, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &admission) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &admission, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let query = match parse_list_query(raw_query.as_deref()) { Ok(query) => query, @@ -267,7 +277,7 @@ async fn read_run( Path(path): Path>, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -277,19 +287,24 @@ async fn read_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -297,7 +312,7 @@ async fn read_run( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -323,7 +338,7 @@ async fn cancel_run( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -333,19 +348,24 @@ async fn cancel_run( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -386,7 +406,7 @@ async fn cancel_run( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -431,7 +451,7 @@ async fn submit_chunk( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -441,19 +461,24 @@ async fn submit_chunk( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; // The chunk items are the batch items of the compiled route, so the // entity must carry a batch surface at all. @@ -529,7 +554,7 @@ async fn submit_chunk( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -579,7 +604,7 @@ async fn chunk_receipt( Path(path): Path>, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -589,19 +614,24 @@ async fn chunk_receipt( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(surface) = authorize_route(&service, &binding.base, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - ) - .await; + let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &binding.base, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -609,7 +639,7 @@ async fn chunk_receipt( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -620,7 +650,7 @@ async fn chunk_receipt( &binding.base, &surface.context, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -677,10 +707,11 @@ fn ingestion_problem(error: IngestionServiceError) -> Response { IngestionServiceError::RequestInvalid | IngestionServiceError::InvalidTimerWindow { .. } => invalid_request(), IngestionServiceError::PreconditionFailed => precondition_failed(), - IngestionServiceError::NotFound => concealed(), - IngestionServiceError::ProfileMismatch => { - fixed_problem(ProblemCode::IngestionProfileMismatch) - } + IngestionServiceError::NotFound => concealed(FailedCheck::Visibility), + IngestionServiceError::ProfileMismatch => refusal_problem( + ProblemCode::IngestionProfileMismatch, + FailedCheck::AccessProfile, + ), IngestionServiceError::RunNotOpen => fixed_problem(ProblemCode::IngestionRunNotOpen), IngestionServiceError::RunBlocked => fixed_problem(ProblemCode::IngestionRunBlocked), IngestionServiceError::ChunkMismatch => fixed_problem(ProblemCode::IngestionChunkMismatch), diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index f06dced295..6fb5e80993 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -21,15 +21,13 @@ use std::sync::Arc; use axum::body::{to_bytes, Body}; use axum::extract::{Path, RawQuery, State}; -use axum::http::header::{ - ACCEPT, AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_MATCH, LINK, VARY, -}; +use axum::http::header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_MATCH, LINK, VARY}; use axum::http::{HeaderMap, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, patch, post}; use axum::{middleware, Extension, Json, Router}; use registry_platform_canonical_json::parse_json_strict; -use registry_platform_httpsec::{security_headers, CspBuilder}; +use registry_platform_httpsec::{security_headers_without_posture, CspBuilder}; use serde_json::{json, Map, Value}; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; @@ -75,6 +73,7 @@ use crate::problem_location::{BatchItemMember, RequestLocation}; use crate::query as strict_query; use crate::query_binding::CursorBindingQuery; use crate::record_profile::{self, RecordRepresentation}; +use registry_platform_authcommon::FailedCheck; use uuid::Uuid; use crate::artifacts::{ @@ -91,8 +90,8 @@ const MAX_RAW_QUERY_BYTES: usize = 16 * 1024; const MAX_FILTER_CLAUSES: usize = 32; const MAX_IN_VALUES: usize = 100; const MAX_REVIEW_COMPLETION_BODY_BYTES: usize = 2048; -const REVIEW_COMPLETION_RECIPIENT_HEADER: &str = "registry-recipient-binding"; const IDEMPOTENCY_KEY_HEADER: &str = "idempotency-key"; +const REVIEW_COMPLETION_RECIPIENT_HEADER: &str = "registry-recipient-binding"; /// Construct the low-level route set for callers that already hold verified /// claims. Production network listeners must use [`authenticated_router`]. @@ -116,7 +115,7 @@ pub fn router(service: Arc) -> Router { .merge(probe_routes(service)) .layer(middleware::from_fn(metadata::no_store)) .layer(middleware::from_fn(crate::correlation::observe)) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } fn route_set(service: Arc) -> Router { @@ -258,7 +257,7 @@ fn probe_routes(service: Arc) -> Router { } async fn probe_method_not_allowed() -> Response { - concealed() + unknown_route() } /// axum's `get` also answers HEAD by running the whole read under the @@ -303,7 +302,7 @@ pub fn authenticated_router( }; app.layer(middleware::from_fn(metadata::no_store)) .layer(middleware::from_fn(crate::correlation::observe)) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } async fn review_completion( @@ -312,29 +311,37 @@ async fn review_completion( body: Body, ) -> Response { let Some(receiver) = service.review_completions.as_ref() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authorization) = single_header(&headers, AUTHORIZATION.as_str()) else { - return review_completion_refused(); + let Some(recipient) = single_header(&headers, REVIEW_COMPLETION_RECIPIENT_HEADER) + .filter(|recipient| receiver.contains_recipient(recipient)) + else { + return review_completion_refused(FailedCheck::DeliverySignature); }; - let Ok(token) = registry_platform_authcommon::parse_bearer_token(authorization) else { - return review_completion_refused(); + let (Some(id), Some(timestamp), Some(signature)) = ( + single_header(&headers, "webhook-id"), + single_header(&headers, "webhook-timestamp"), + single_header(&headers, "webhook-signature"), + ) else { + return review_completion_refused(FailedCheck::DeliverySignature); }; - let Some(recipient) = single_header(&headers, REVIEW_COMPLETION_RECIPIENT_HEADER) else { - return review_completion_refused(); + let Ok(body) = to_bytes(body, MAX_REVIEW_COMPLETION_BODY_BYTES).await else { + return StatusCode::PAYLOAD_TOO_LARGE.into_response(); }; - let Some((authority, recovery_days)) = receiver.authority(token, recipient) else { - return review_completion_refused(); + let content = registry_platform_crypto::delivery_signature::SignedContent { + id, + timestamp, + signature, + body: &body, }; + let (authority, recovery_days) = + match receiver.verify_completion(recipient, content, std::time::SystemTime::now()) { + Ok(authority) => authority, + Err(check) => return review_completion_refused(check), + }; if !single_content_type(&headers, "application/json") { return unsupported_media_type(); } - let Some(idempotency_key) = single_header(&headers, IDEMPOTENCY_KEY_HEADER) else { - return invalid_request(); - }; - let Ok(body) = bounded_body_to(body, MAX_REVIEW_COMPLETION_BODY_BYTES).await else { - return invalid_request(); - }; let Ok(value) = parse_json_strict(&body) else { return invalid_request(); }; @@ -342,7 +349,7 @@ async fn review_completion( else { return invalid_request(); }; - if idempotency_key != completion.event_id.to_string() + if id != completion.event_id.to_string() || completion.event_id.is_nil() || completion.request_id.is_nil() || completion.result_id.is_nil() @@ -353,7 +360,7 @@ async fn review_completion( if !completion_timestamp_is_acceptable(completion.completed_at, now, recovery_days) { return invalid_request(); } - match receiver.receive(&authority, &completion).await { + match receiver.receive(authority, &completion).await { Ok(()) => StatusCode::NO_CONTENT.into_response(), Err(MutationError::InvalidRequest | MutationError::PreconditionFailed) => invalid_request(), Err(_) => unavailable(), @@ -387,8 +394,15 @@ mod review_completion_tests { } } -fn review_completion_refused() -> Response { - fixed_problem(ProblemCode::AuthenticationRefused) +fn review_completion_refused(check: FailedCheck) -> Response { + let mut response = refusal_problem(ProblemCode::AuthenticationRefused, check); + response.headers_mut().insert( + axum::http::header::WWW_AUTHENTICATE, + axum::http::HeaderValue::from_static( + r#"Registry-Signature scheme="standard-webhooks", version="v1""#, + ), + ); + response } async fn health() -> Response { @@ -409,7 +423,7 @@ async fn openapi( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let visible = visible_surfaces(&service, &claims, &options); let visible_actions = actions::visible_actions(&service, &claims, &options); @@ -422,7 +436,7 @@ async fn openapi( && visible_statistics.is_empty() && visible_proposals.is_empty() { - return concealed(); + return concealed(FailedCheck::Visibility); } let mut paths = Map::new(); @@ -598,7 +612,7 @@ async fn registry_metadata( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let surfaces = visible_surfaces(&service, &claims, &options); let operations = metadata::operations(&service, &surfaces); @@ -611,7 +625,7 @@ async fn registry_metadata( && visible_statistics.is_empty() && visible_proposals.is_empty() { - return concealed(); + return concealed(FailedCheck::Visibility); } let mut entities: BTreeMap = BTreeMap::new(); @@ -625,10 +639,10 @@ async fn registry_metadata( for (_, entry) in visible { let Some(response_entity) = service.registry.entities().get(&entry.response_entity_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(dataset_identifier) = response_entity.primary_dataset.as_ref() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; entities .entry(response_entity.id.clone()) @@ -844,14 +858,14 @@ async fn record_schema( RawQuery(raw_query): RawQuery, ) -> Response { let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let surfaces = visible_surfaces(&service, &claims, &options) .into_iter() .filter(|surface| surface.response_entity.id == record_type_id) .collect::>(); let Some(first) = surfaces.first() else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let readable = surfaces @@ -863,7 +877,7 @@ async fn record_schema( }); match filtered_schema(&service, &record_type_id, &readable) { Some(schema) => Json(schema).into_response(), - None => concealed(), + None => concealed(FailedCheck::Visibility), } } @@ -892,7 +906,7 @@ async fn read_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { let response = audited_read_concealment( &service, &route, @@ -900,7 +914,7 @@ async fn read_dispatch( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; return response; @@ -946,7 +960,7 @@ async fn read_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -957,7 +971,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -975,7 +989,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, Some(ReadRefusalReason::SelectOverreach), ) @@ -988,7 +1002,7 @@ async fn read_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1015,7 +1029,7 @@ async fn read_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::Unavailable | ReadServiceError::SnapshotUnreadable) => { unavailable() } @@ -1034,7 +1048,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1093,7 +1107,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1104,7 +1118,7 @@ async fn read_dispatch( &route, &surface, path.get("record_id"), - concealed(), + concealed(FailedCheck::Disclosure), &correlation, ) .await; @@ -1149,7 +1163,7 @@ async fn read_dispatch( Err(ReadServiceError::CursorInvalid) => cursor_invalid(), } } - _ => concealed(), + _ => concealed(FailedCheck::Operation), } } @@ -1178,7 +1192,7 @@ async fn lookup_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -1186,7 +1200,7 @@ async fn lookup_dispatch( &claims, None, &correlation, - reason, + refusal, ) .await; } @@ -1234,7 +1248,7 @@ async fn lookup_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Disclosure), &correlation, Some(ReadRefusalReason::SelectOverreach), ) @@ -1314,8 +1328,15 @@ async fn lookup_dispatch( } }; if !readable_fields.is_subset(&surface.readable_fields) { - return audited_read_refusal(&service, &route, &surface, None, concealed(), &correlation) - .await; + return audited_read_refusal( + &service, + &route, + &surface, + None, + concealed(FailedCheck::Disclosure), + &correlation, + ) + .await; } let Some(operation) = lookup_query_operation_for_selector(&service, &route, &surface, &selector.selector_id) @@ -1334,8 +1355,15 @@ async fn lookup_dispatch( .iter() .all(|field| operation.projection_fields.contains(field)) { - return audited_read_refusal(&service, &route, &surface, None, concealed(), &correlation) - .await; + return audited_read_refusal( + &service, + &route, + &surface, + None, + concealed(FailedCheck::Disclosure), + &correlation, + ) + .await; } let request = RecordReadRequest { entity_id: route.entity_id.clone(), @@ -1357,7 +1385,7 @@ async fn lookup_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => lookup_unresolved(), + Ok(None) => crate::correlation::note_refusal(lookup_unresolved(), FailedCheck::Visibility), Err(ReadServiceError::Unavailable | ReadServiceError::SnapshotUnreadable) => unavailable(), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(ReadServiceError::CursorInvalid) => cursor_invalid(), @@ -1412,7 +1440,7 @@ async fn revision_dispatch( Path(path): Path>, ) -> Response { let Some(revisions) = &service.revisions else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let options = match QueryOptions::parse(raw_query.as_deref(), false) { Ok(options) => options, @@ -1430,7 +1458,7 @@ async fn revision_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_revision_concealment( revisions.as_ref(), &route, @@ -1438,7 +1466,7 @@ async fn revision_dispatch( &claims, path.get("record_id"), &correlation, - reason, + refusal, ) .await; } @@ -1466,7 +1494,7 @@ async fn revision_dispatch( &route, &surface, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1483,7 +1511,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1496,7 +1524,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1508,7 +1536,7 @@ async fn revision_dispatch( &route, &surface, Some(record_id), - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1545,7 +1573,7 @@ async fn revision_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(_) => unavailable(), }, @@ -1555,11 +1583,11 @@ async fn revision_dispatch( surface.response_entity, public_deployment_prefix(&service), ), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(ReadServiceError::FieldEncryptionUnavailable) => field_encryption_unavailable(), Err(_) => unavailable(), }, - None => concealed(), + None => concealed(FailedCheck::Operation), } } @@ -1572,7 +1600,7 @@ async fn snapshot_dispatch( headers: HeaderMap, ) -> Response { let Some(snapshots) = &service.snapshots else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let options = match QueryOptions::parse_snapshot(raw_query.as_deref()) { Ok(options) => options, @@ -1582,7 +1610,7 @@ async fn snapshot_dispatch( &route, &claims, None, - concealed(), + concealed(FailedCheck::Visibility), &correlation, ) .await; @@ -1590,7 +1618,7 @@ async fn snapshot_dispatch( }; let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &route, @@ -1598,7 +1626,7 @@ async fn snapshot_dispatch( &claims, None, &correlation, - reason, + refusal, ) .await; } @@ -1736,7 +1764,7 @@ async fn audited_revision_concealment( claims: &VerifiedRequestClaims, target_record: Option<&String>, correlation: &RequestCorrelation, - reason: ReadRefusalReason, + refusal: RouteRefusal, ) -> Response { let selected_access_profile = options.access_profile().and_then(|profile| { route @@ -1747,7 +1775,7 @@ async fn audited_revision_concealment( }); match revisions .refusal(RevisionReadRefusal { - refusal_reason: Some(reason), + refusal_reason: Some(refusal.reason), method: route.method, operation_id: route.id.clone(), target_record: target_record.cloned(), @@ -1759,7 +1787,7 @@ async fn audited_revision_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(refusal.check), Err(_) => unavailable(), } } @@ -1852,7 +1880,7 @@ async fn audited_read_concealment( claims: &VerifiedRequestClaims, target_record: Option<&String>, correlation: &RequestCorrelation, - reason: ReadRefusalReason, + refusal: RouteRefusal, ) -> Response { let selected_access_profile = options.access_profile().and_then(|profile| { route @@ -1865,7 +1893,7 @@ async fn audited_read_concealment( .read_refusal( route.operation, RecordReadRefusal { - refusal_reason: Some(reason), + refusal_reason: Some(refusal.reason), method: route.method, operation_id: route.id.clone(), target_record: target_record.cloned(), @@ -1878,7 +1906,7 @@ async fn audited_read_concealment( ) .await { - Ok(()) => concealed(), + Ok(()) => concealed(refusal.check), Err(_) => unavailable(), } } @@ -1893,7 +1921,7 @@ async fn create_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -1903,19 +1931,24 @@ async fn create_dispatch( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - None, - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2024,7 +2057,7 @@ async fn patch_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(record_id) = path.get("record_id") else { return invalid_request(); @@ -2037,19 +2070,24 @@ async fn patch_dispatch( &claims, Some(record_id.as_str()), &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - Some(record_id.as_str()), - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + Some(record_id.as_str()), + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2193,7 +2231,7 @@ async fn batch_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(options) = QueryOptions::parse(raw_query.as_deref(), false) else { return audited_mutation_concealment( @@ -2203,19 +2241,24 @@ async fn batch_dispatch( &claims, None, &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - None, - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + None, + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2340,7 +2383,7 @@ async fn tombstone_dispatch( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(record_id) = path.get("record_id") else { return invalid_request(); @@ -2353,19 +2396,24 @@ async fn tombstone_dispatch( &claims, Some(record_id.as_str()), &correlation, + FailedCheck::Visibility, ) .await; }; - let Some(mut surface) = authorize_route(&service, &route, &claims, &options) else { - return audited_mutation_concealment( - mutations, - &route, - &options, - &claims, - Some(record_id.as_str()), - &correlation, - ) - .await; + let mut surface = match authorize_route_with_reason(&service, &route, &claims, &options) { + Ok(surface) => surface, + Err(refusal) => { + return audited_mutation_concealment( + mutations, + &route, + &options, + &claims, + Some(record_id.as_str()), + &correlation, + refusal.check, + ) + .await; + } }; if let Err(binding) = surface.context.bind_access_reason(&headers) { return audited_mutation_refusal( @@ -2506,6 +2554,7 @@ async fn audited_mutation_concealment( claims: &VerifiedRequestClaims, target_record: Option<&str>, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { // Only a profile the compiled route grants may reach the journal, so an // unknown caller-supplied value is recorded as absent. @@ -2532,7 +2581,7 @@ async fn audited_mutation_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => mutation_problem(MutationError::Unavailable), } } @@ -2552,7 +2601,7 @@ async fn not_found( { statistics::unknown(&service, &claims, &correlation, &method).await } - _ => concealed(), + _ => unknown_route(), } } @@ -2611,6 +2660,45 @@ fn metadata_entry_for_surface<'a>( Some((entity, entry)) } +/// A route the caller was not admitted to. The reason is the audit journal's +/// closed vocabulary. The check is the operator's, and it names which +/// admission rule refused, which the reason alone cannot. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct RouteRefusal { + pub(crate) reason: ReadRefusalReason, + pub(crate) check: FailedCheck, +} + +impl RouteRefusal { + const fn surface(check: FailedCheck) -> Self { + Self { + reason: ReadRefusalReason::SurfaceUnavailable, + check, + } + } + + const fn admission(refusal: ClaimRefusal) -> Self { + Self { + reason: ReadRefusalReason::ProfileAdmission, + check: refusal.check, + } + } + + const fn admission_check(check: FailedCheck) -> Self { + Self { + reason: ReadRefusalReason::ProfileAdmission, + check, + } + } + + const fn select_overreach() -> Self { + Self { + reason: ReadRefusalReason::SelectOverreach, + check: FailedCheck::Disclosure, + } + } +} + fn authorize_route<'a>( service: &'a HttpService, route: &'a CompiledRoute, @@ -2625,7 +2713,7 @@ fn authorize_route_with_reason<'a>( route: &'a CompiledRoute, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { +) -> Result, RouteRefusal> { if let Some((read_path, response_entity)) = read_path_for_route(service, route) { return authorize_read_path_route( service, @@ -2683,7 +2771,7 @@ fn authorize_direct_route<'a>( route: &'a CompiledRoute, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { +) -> Result, RouteRefusal> { if claims.grant().is_none() && (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) @@ -2696,40 +2784,40 @@ fn authorize_direct_route<'a>( | Operation::Import ) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::TaskGrantMissing)); } - let access = - access_entry_for_route(service, route).ok_or(ReadRefusalReason::SurfaceUnavailable)?; + let access = access_entry_for_route(service, route) + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let selected_profile = options .access_profile() .map(String::as_str) .or(access.default_profile_id.as_deref()) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !access.profile_ids.contains(selected_profile) || !route .access_profiles .iter() .any(|id| id == selected_profile) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } let entity = service .registry .entities() .get(&route.entity_id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let profile = entity .access_profiles .get(selected_profile) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !profile.operations.contains(&route.operation) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } if route.operation == Operation::Revisions && !profile.revision_access { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } - let row_boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + let row_boundaries = + authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; let readable_fields = profile .readable_fields .iter() @@ -2748,9 +2836,7 @@ fn authorize_direct_route<'a>( selected_profile.to_owned(), row_boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims) .with_access_reason_requirement(profile.require_access_reason); @@ -2771,41 +2857,41 @@ fn authorize_read_path_route<'a>( response_entity: &'a CompiledEntity, claims: &VerifiedRequestClaims, options: &QueryOptions, -) -> Result, ReadRefusalReason> { - let access = - access_entry_for_route(service, route).ok_or(ReadRefusalReason::SurfaceUnavailable)?; +) -> Result, RouteRefusal> { + let access = access_entry_for_route(service, route) + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let selected_profile = options .access_profile() .map(String::as_str) .or(access.default_profile_id.as_deref()) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !access.profile_ids.contains(selected_profile) || !route .access_profiles .iter() .any(|id| id == selected_profile) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } let entity = service .registry .entities() .get(&route.entity_id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let profile = entity .access_profiles .get(selected_profile) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let grant = profile .read_paths .iter() .find(|grant| grant.path == read_path.id) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::Operation))?; if route.operation != Operation::List || route.query_kind != Some(CompiledQueryKind::List) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::Operation)); } - let row_boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + let row_boundaries = + authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; let readable_fields = grant.readable_fields.iter().cloned().collect(); Ok(AuthorizedSurface { route, @@ -2817,9 +2903,7 @@ fn authorize_read_path_route<'a>( selected_profile.to_owned(), row_boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims) .with_access_reason_requirement(profile.require_access_reason), @@ -2903,33 +2987,61 @@ fn served_operation(service: &HttpService, route: &CompiledRoute) -> bool { } } +/// Why a profile or a task grant did not admit a request. The reason is the +/// offline preview's vocabulary and the check is the operator's. Neither +/// crosses the public HTTP concealment boundary. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct ClaimRefusal { + pub(crate) reason: &'static str, + pub(crate) check: FailedCheck, +} + +impl ClaimRefusal { + const fn new(reason: &'static str, check: FailedCheck) -> Self { + Self { reason, check } + } +} + /// Shared by real HTTP admission and offline synthetic access previews. /// Detailed reasons never cross the public HTTP concealment boundary. pub(crate) fn authorize_profile_claims( profile: &AccessProfileSource, claims: &VerifiedRequestClaims, -) -> Result, &'static str> { +) -> Result, ClaimRefusal> { if Some(profile.principal_claim.as_str()) != claims.principal_claim() || claims.principal().is_none() { - return Err("principal-missing-or-mismatched"); + return Err(ClaimRefusal::new( + "principal-missing-or-mismatched", + FailedCheck::TokenClaims, + )); } if !profile .required_scopes .iter() .all(|scope| claims.has_scope(scope)) { - return Err("required-scope-missing"); + claims.declare_scope_refusal(&profile.required_scopes, Some(&profile.id)); + return Err(ClaimRefusal::new( + "required-scope-missing", + FailedCheck::Scope, + )); } if !profile.required_purposes.is_empty() && !claims .purpose() .is_some_and(|purpose| profile.required_purposes.contains(purpose)) { - return Err("purpose-missing-or-not-allowed"); + return Err(ClaimRefusal::new( + "purpose-missing-or-not-allowed", + FailedCheck::Purpose, + )); } if let Some(expected) = profile.actor_kind { - let actual = claims.actor_kind().ok_or("actor-kind-missing")?; + let actual = claims.actor_kind().ok_or(ClaimRefusal::new( + "actor-kind-missing", + FailedCheck::ActorKind, + ))?; let matches = matches!( (expected, actual), ( @@ -2944,7 +3056,10 @@ pub(crate) fn authorize_profile_claims( ) ); if !matches { - return Err("actor-kind-mismatched"); + return Err(ClaimRefusal::new( + "actor-kind-mismatched", + FailedCheck::ActorKind, + )); } } // A delegated token acts for its principal; only a profile written for @@ -2952,44 +3067,72 @@ pub(crate) fn authorize_profile_claims( if claims.actor_subject().is_some() && profile.actor_kind != Some(crate::contract::ActorKindSource::Agent) { - return Err("delegated_actor_requires_agent_profile"); + return Err(ClaimRefusal::new( + "delegated_actor_requires_agent_profile", + FailedCheck::Delegation, + )); } if !profile.requester_clients.is_empty() && !claims .requester_client() .is_some_and(|client| profile.requester_clients.contains(client)) { - return Err("requester-client-missing-or-mismatched"); + return Err(ClaimRefusal::new( + "requester-client-missing-or-mismatched", + FailedCheck::RequesterClient, + )); } match (&profile.task_grant, claims.grant()) { - (Some(_), None) => return Err("task_grant_missing"), - (None, Some(_)) => return Err("task_grant_profile_required"), + (Some(_), None) => { + return Err(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + )) + } + (None, Some(_)) => { + return Err(ClaimRefusal::new( + "task_grant_profile_required", + FailedCheck::TaskGrantScope, + )) + } (None, None) if profile.actor_kind == Some(crate::contract::ActorKindSource::Agent) && claims.actor_subject().is_none() => { - return Err("trusted_actor_missing"); + return Err(ClaimRefusal::new( + "trusted_actor_missing", + FailedCheck::Delegation, + )); } _ => {} } - verified_row_boundaries(profile, claims).ok_or("row-claim-missing-or-wrong-cardinality") + verified_row_boundaries(profile, claims).ok_or(ClaimRefusal::new( + "row-claim-missing-or-wrong-cardinality", + FailedCheck::RowBoundary, + )) } fn task_grant_binding( profile: &AccessProfileSource, claims: &VerifiedRequestClaims, -) -> Result, &'static str> { +) -> Result, ClaimRefusal> { let Some(expected) = &profile.task_grant else { return Ok(None); }; - let grant = claims.grant().ok_or("task_grant_missing")?; + let grant = claims.grant().ok_or(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + ))?; if !profile.required_purposes.contains(grant.purpose()) { - return Err("task_grant_binding_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_binding_mismatched", + FailedCheck::TaskGrantBinding, + )); } - let actual = grant - .bounds() - .breg_permissions() - .ok_or("task_grant_bounds_wrong_type")?; + let actual = grant.bounds().breg_permissions().ok_or(ClaimRefusal::new( + "task_grant_bounds_wrong_type", + FailedCheck::TaskGrantScope, + ))?; let actual = actual .iter() .map(|permission| { @@ -3019,7 +3162,10 @@ fn task_grant_binding( Some((permission.collection.clone(), operations)) }) .collect::>>() - .ok_or("task_grant_bounds_invalid")?; + .ok_or(ClaimRefusal::new( + "task_grant_bounds_invalid", + FailedCheck::TaskGrantScope, + ))?; // A verified token can compose independently scoped Proposal authority. // Record routes still use only this static profile's fields and operations. if !expected_bounds.iter().all(|(collection, operations)| { @@ -3027,7 +3173,10 @@ fn task_grant_binding( .get(collection) .is_some_and(|actual| operations.is_subset(actual)) }) { - return Err("task_grant_bounds_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_bounds_mismatched", + FailedCheck::TaskGrantScope, + )); } bind_task_grant(&expected.source_issuer, claims).map(Some) } @@ -3039,20 +3188,29 @@ fn task_grant_binding( fn bind_task_grant( source_issuer: &str, claims: &VerifiedRequestClaims, -) -> Result { - let grant = claims.grant().ok_or("task_grant_missing")?; +) -> Result { + let grant = claims.grant().ok_or(ClaimRefusal::new( + "task_grant_missing", + FailedCheck::TaskGrantMissing, + ))?; if grant.source_issuer() != source_issuer || Some(grant.client()) != claims.requester_client() || Some(grant.principal()) != claims.principal() || Some(grant.purpose()) != claims.purpose() { - return Err("task_grant_binding_mismatched"); + return Err(ClaimRefusal::new( + "task_grant_binding_mismatched", + FailedCheck::TaskGrantBinding, + )); } let binding = crate::task_grant::TaskGrantBinding::from_verified(grant, claims.grant_subjects().clone()) - .map_err(|_| "task_grant_invalid")?; + .map_err(|_| ClaimRefusal::new("task_grant_invalid", FailedCheck::TaskGrantClaims))?; if !binding.is_current() { - return Err("task_grant_expired"); + return Err(ClaimRefusal::new( + "task_grant_expired", + FailedCheck::TaskGrantExpired, + )); } Ok(binding) } @@ -4984,8 +5142,19 @@ fn method_name(method: crate::model::HttpMethod) -> &'static str { } } -fn concealed() -> Response { - fixed_problem(ProblemCode::ResourceNotFound) +/// The 404 that hides whether the target exists or what the caller may see. +/// The check names, for the operator only, which rule refused. +fn concealed(check: FailedCheck) -> Response { + refusal_problem(ProblemCode::ResourceNotFound, check) +} + +/// The 404 of a path or method the service does not serve. No check refused +/// the caller, so nothing is counted. +fn unknown_route() -> Response { + build_problem( + ProblemCode::ResourceNotFound, + ProblemCode::ResourceNotFound.description(), + ) } fn unavailable() -> Response { @@ -5001,7 +5170,7 @@ fn field_encryption_unavailable() -> Response { /// refused forwarded attribution stays concealed. fn access_binding_refusal(refusal: context::AccessBindingRefusal) -> Response { match refusal { - context::AccessBindingRefusal::Attribution => concealed(), + context::AccessBindingRefusal::Attribution => concealed(FailedCheck::Delegation), context::AccessBindingRefusal::ReasonRequired => { fixed_problem(ProblemCode::RequestAccessReasonRequired) } @@ -5579,17 +5748,28 @@ fn precondition_failed() -> Response { } fn mutation_problem(error: MutationError) -> Response { + let check = error.failed_check(); + let response = mutation_problem_response(error); + match check { + Some(check) => crate::correlation::note_refusal(response, check), + None => response, + } +} + +fn mutation_problem_response(error: MutationError) -> Response { match error { MutationError::InvalidRequest | MutationError::InvalidTimerWindow { .. } => { invalid_request() } MutationError::InvalidRequestAt(location) => invalid_request_at(&location), - MutationError::AuthorizationRefused + MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::TimerGenerationUnsupported => precondition_failed(), - MutationError::WriteOutsideBoundary => fixed_problem(ProblemCode::WriteOutsideBoundary), + MutationError::WriteOutsideBoundary => { + refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::RowBoundary) + } MutationError::Conflict | MutationError::ProposalUniqueConflict => { fixed_problem(ProblemCode::MutationConflict) } @@ -5660,11 +5840,39 @@ fn mutation_problem_for_fields( } } +/// An answer that is not a refusal of authority. A code that refuses authority +/// (401, 403, or the 404 that conceals) is built with [`refusal_problem`] so it +/// names its check. A refusal code arriving here is a defect: it is answered +/// unchanged and logged once, and a debug build stops. fn fixed_problem(code: ProblemCode) -> Response { problem_with_detail(code, code.description()) } fn problem_with_detail(code: ProblemCode, detail: &'static str) -> Response { + if refuses_authority(code) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = code.code(), + "a refusal was answered without its failed check" + ); + } + build_problem(code, detail) +} + +/// A refusal of authority, with the check it failed. The check reaches the +/// operator's counter and log line through the response extensions and never +/// the caller's body. +pub(crate) fn refusal_problem(code: ProblemCode, check: FailedCheck) -> Response { + crate::correlation::note_refusal(build_problem(code, code.description()), check) +} + +/// The codes answered as a refusal of authority: every 401 and 403, and the +/// 404 that hides what the caller may see. +fn refuses_authority(code: ProblemCode) -> bool { + matches!(code.status(), 401 | 403) || code == ProblemCode::ResourceNotFound +} + +fn build_problem(code: ProblemCode, detail: &'static str) -> Response { let status = StatusCode::from_u16(code.status()).expect("problem catalogue status is valid"); crate::correlation::problem_response(status, code.title(), detail, code.code()) } @@ -6215,3 +6423,133 @@ mod temporal_instant_tests { assert!(normalize_history_valid_at(entity, "2026-06-05T00:00:00+05:30").is_err()); } } + +#[cfg(test)] +mod refusal_check_tests { + use super::*; + use registry_platform_authcommon::RefusalNote; + + fn noted(response: &Response) -> Option { + response + .extensions() + .get::() + .map(|note| note.check) + } + + #[test] + fn a_concealed_answer_carries_its_check_and_an_unknown_route_carries_none() { + let hidden = concealed(FailedCheck::Visibility); + assert_eq!(hidden.status(), StatusCode::NOT_FOUND); + assert_eq!(noted(&hidden), Some(FailedCheck::Visibility)); + let unknown = unknown_route(); + assert_eq!(unknown.status(), StatusCode::NOT_FOUND); + assert_eq!(noted(&unknown), None); + } + + /// The codes answered as a refusal of authority, read from the catalogue + /// so a code added later is covered. + fn refusal_codes() -> Vec { + ProblemCode::ALL + .iter() + .copied() + .filter(|code| refuses_authority(*code)) + .collect() + } + + /// Every code answered as a 401, a 403 or the concealing 404 is built with + /// its check, and building one without the check is a defect. + #[test] + fn every_refusal_code_is_built_with_its_check() { + let refusals = refusal_codes(); + for status in [401, 403, 404] { + assert!( + refusals.iter().any(|code| code.status() == status), + "the catalogue lists a {status} refusal" + ); + } + for code in ProblemCode::ALL { + let status = code.status(); + if matches!(status, 401 | 403) { + assert!(refusals.contains(code), "{} is a refusal", code.code()); + } + } + for code in refusals { + let response = refusal_problem(code, FailedCheck::Visibility); + assert_eq!(response.status().as_u16(), code.status()); + assert_eq!(noted(&response), Some(FailedCheck::Visibility)); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_refusal_code_without_its_check_stops_a_debug_build() { + let refusals = refusal_codes(); + assert!(!refusals.is_empty()); + for code in refusals { + let outcome = std::panic::catch_unwind(|| fixed_problem(code)); + assert!( + outcome.is_err(), + "{} was built without a check", + code.code() + ); + } + } + + #[test] + fn a_mutation_refusal_names_the_check_and_a_plain_failure_names_none() { + for (error, check) in [ + ( + MutationError::AuthorizationRefused(FailedCheck::Operation), + FailedCheck::Operation, + ), + ( + MutationError::AuthorizationRefused(FailedCheck::TaskGrantScope), + FailedCheck::TaskGrantScope, + ), + ( + MutationError::AuthorizationRefused(FailedCheck::Ownership), + FailedCheck::Ownership, + ), + ( + MutationError::WriteOutsideBoundary, + FailedCheck::RowBoundary, + ), + ( + MutationError::FieldGuardFailed { + input: "input".to_owned(), + }, + FailedCheck::ActionGuard, + ), + ] { + let response = mutation_problem(error); + assert_eq!(noted(&response), Some(check)); + } + for error in [ + MutationError::PreconditionFailed, + MutationError::Conflict, + MutationError::Unavailable, + ] { + assert_eq!(noted(&mutation_problem(error)), None); + } + assert_eq!( + noted(&mutation_problem(MutationError::WriteOutsideBoundary)).map(FailedCheck::as_str), + Some("row-boundary") + ); + } + + #[test] + fn a_route_refusal_keeps_the_audit_reason_beside_the_check() { + let refusal = RouteRefusal::surface(FailedCheck::AccessProfile); + assert_eq!(refusal.reason, ReadRefusalReason::SurfaceUnavailable); + assert_eq!(refusal.check, FailedCheck::AccessProfile); + let overreach = RouteRefusal::select_overreach(); + assert_eq!(overreach.reason, ReadRefusalReason::SelectOverreach); + assert_eq!(overreach.check, FailedCheck::Disclosure); + let admission = RouteRefusal::admission(ClaimRefusal::new( + "task_grant_expired", + FailedCheck::TaskGrantExpired, + )); + assert_eq!(admission.reason, ReadRefusalReason::ProfileAdmission); + assert_eq!(admission.check, FailedCheck::TaskGrantExpired); + } +} diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index c58eb74417..13c20a3a83 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -12,7 +12,7 @@ use crate::postgres::{ProposalAuthority, ProposalAuthorityOperation, RowBoundary pub(super) fn proposal_problem(error: MutationError) -> Response { match error { - MutationError::AuthorizationRefused => concealed(), + MutationError::AuthorizationRefused(check) => concealed(check), error => mutation_problem(error), } } @@ -156,34 +156,65 @@ fn permission_matches( permission: &CompiledProposalPermission, claims: &VerifiedRequestClaims, standing_own_draft: bool, -) -> bool { - permission.principal_claim.as_deref() == claims.principal_claim() - && permission - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - && (permission.required_purposes.is_empty() - || claims - .purpose() - .is_some_and(|purpose| permission.required_purposes.contains(purpose))) - && actor_matches(permission.actor_kind, claims, standing_own_draft) - && (permission.requester_clients.is_empty() - || claims - .requester_client() - .is_some_and(|client| permission.requester_clients.contains(client))) +) -> Result<(), FailedCheck> { + request_matches( + permission.principal_claim.as_deref(), + &permission.required_scopes, + &permission.required_purposes, + permission.actor_kind, + &permission.requester_clients, + claims, + standing_own_draft, + ) +} + +/// The checks a Proposal permission and an Action start grant share, in the +/// order they are made. The first that fails names itself. +fn request_matches( + principal_claim: Option<&str>, + required_scopes: &BTreeSet, + required_purposes: &BTreeSet, + actor_kind: Option, + requester_clients: &BTreeSet, + claims: &VerifiedRequestClaims, + standing_own_draft: bool, +) -> Result<(), FailedCheck> { + if principal_claim != claims.principal_claim() { + return Err(FailedCheck::TokenClaims); + } + if !required_scopes.iter().all(|scope| claims.has_scope(scope)) { + claims.declare_scope_refusal(required_scopes, None); + return Err(FailedCheck::Scope); + } + if !required_purposes.is_empty() + && !claims + .purpose() + .is_some_and(|purpose| required_purposes.contains(purpose)) + { + return Err(FailedCheck::Purpose); + } + actor_matches(actor_kind, claims, standing_own_draft)?; + if !requester_clients.is_empty() + && !claims + .requester_client() + .is_some_and(|client| requester_clients.contains(client)) + { + return Err(FailedCheck::RequesterClient); + } + Ok(()) } fn actor_matches( expected: Option, claims: &VerifiedRequestClaims, standing_own_draft: bool, -) -> bool { +) -> Result<(), FailedCheck> { use crate::contract::ActorKindSource; use registry_platform_oidc::ActorKind; if claims.actor_subject().is_some() && expected != Some(ActorKindSource::Agent) { - return false; + return Err(FailedCheck::Delegation); } - match expected { + let matches = match expected { None => true, Some(ActorKindSource::Human) => claims.actor_kind() == Some(ActorKind::Human), Some(ActorKindSource::Agent) => { @@ -193,6 +224,11 @@ fn actor_matches( || standing_own_draft) } Some(ActorKindSource::Service) => claims.actor_kind() == Some(ActorKind::Service), + }; + if matches { + Ok(()) + } else { + Err(FailedCheck::ActorKind) } } @@ -233,15 +269,28 @@ pub(crate) fn authorize( operation: ProposalAuthorityOperation, proposal_id: Option, ) -> Option { + authorize_checked(registry, action, claims, selected, operation, proposal_id).ok() +} + +/// The admission of a Proposal operation. The refusal names the first check +/// that failed, for the operator only. +pub(crate) fn authorize_checked( + registry: &CompiledRegistry, + action: &CompiledAction, + claims: &VerifiedRequestClaims, + selected: Option<&str>, + operation: ProposalAuthorityOperation, + proposal_id: Option, +) -> Result { let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return None; + return Err(FailedCheck::Operation); }; if matches!( operation, ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply | ProposalOperation::Retry) ) && !external_recovery_actor_allowed(&proposal.application, Some(claims)) { - return None; + return Err(FailedCheck::ActorKind); } let standing_agent = (claims.actor_subject().is_some() || claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Agent)) @@ -254,31 +303,27 @@ pub(crate) fn authorize( | ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) ) { - return None; + return Err(FailedCheck::TaskGrantMissing); } let (profile, targets, task_source) = match operation { ProposalAuthorityOperation::Start => { - let grant = action.permissions.iter().find(|grant| { - selected.map_or(grant.default, |profile| profile == grant.profile_id) - && grant.operations.contains(&Operation::Start) - })?; - if grant.principal_claim.as_deref() != claims.principal_claim() - || !grant - .required_scopes - .iter() - .all(|scope| claims.has_scope(scope)) - || (!grant.required_purposes.is_empty() - && !claims - .purpose() - .is_some_and(|p| grant.required_purposes.contains(p))) - || !actor_matches(grant.actor_kind, claims, standing_agent) - || (!grant.requester_clients.is_empty() - && !claims - .requester_client() - .is_some_and(|c| grant.requester_clients.contains(c))) - { - return None; - } + let grant = action + .permissions + .iter() + .find(|grant| { + selected.map_or(grant.default, |profile| profile == grant.profile_id) + && grant.operations.contains(&Operation::Start) + }) + .ok_or(FailedCheck::AccessProfile)?; + request_matches( + grant.principal_claim.as_deref(), + &grant.required_scopes, + &grant.required_purposes, + grant.actor_kind, + &grant.requester_clients, + claims, + standing_agent, + )?; let targets = grant .targets .iter() @@ -288,7 +333,8 @@ pub(crate) fn authorize( boundaries(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), targets, @@ -296,15 +342,19 @@ pub(crate) fn authorize( ) } ProposalAuthorityOperation::Lifecycle(operation) => { - let grant = proposal.permissions.iter().find(|grant| { - selected.map_or(grant.default, |profile| profile == grant.profile_id) - && grant.operations.contains(&operation) - })?; + let grant = proposal + .permissions + .iter() + .find(|grant| { + selected.map_or(grant.default, |profile| profile == grant.profile_id) + && grant.operations.contains(&operation) + }) + .ok_or(FailedCheck::AccessProfile)?; if standing_agent && operation == ProposalOperation::Edit && grant.ownership != Some(crate::model::ProposalOwnership::Caller) { - return None; + return Err(FailedCheck::Operation); } // A standing agent edits only its caller-owned draft. The one // additional operation is current review-context disclosure, and @@ -315,16 +365,14 @@ pub(crate) fn authorize( && operation == ProposalOperation::GetReviewContext && (claims.actor_subject().is_none() || grant.requester_clients.is_empty()) { - return None; - } - if !permission_matches(grant, claims, standing_agent) { - return None; + return Err(FailedCheck::Delegation); } + permission_matches(grant, claims, standing_agent)?; if grant.review_authority.is_some() && (operation != ProposalOperation::GetReviewStatus || claims.actor_kind() != Some(registry_platform_oidc::ActorKind::Service)) { - return None; + return Err(FailedCheck::ActorKind); } let targets = grant .targets @@ -335,7 +383,8 @@ pub(crate) fn authorize( boundaries(&target.row_boundaries, claims)?, )) }) - .collect::>>()?; + .collect::>>() + .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), targets, @@ -347,20 +396,24 @@ pub(crate) fn authorize( registry, &action.id, operation, - claims.principal()?, + claims.principal().ok_or(FailedCheck::TokenClaims)?, profile, claims.purpose(), targets, ) - .ok()?; + .map_err(|_| FailedCheck::Operation)?; authority.common = authority .common .with_audit_context(crate::audit::RequestAuditContext::from_claims(claims)); match (task_source, claims.grant()) { (None, None) => {} (Some(source), Some(grant)) => { - let binding = bind_task_grant(&source.source_issuer, claims).ok()?; - let bounds = grant.bounds().breg_permissions()?; + let binding = + bind_task_grant(&source.source_issuer, claims).map_err(|refusal| refusal.check)?; + let bounds = grant + .bounds() + .breg_permissions() + .ok_or(FailedCheck::TaskGrantScope)?; let operation_name = crate::mutation::proposal_operation_name(operation); let scope = match operation { ProposalAuthorityOperation::Start => { @@ -369,7 +422,7 @@ pub(crate) fn authorize( bound.collection() == collection && bound.operations().iter().any(|op| op == operation_name) }) { - return None; + return Err(FailedCheck::TaskGrantScope); } None } @@ -384,7 +437,7 @@ pub(crate) fn authorize( }) .collect::>(); if scope.is_empty() || proposal_id.is_some_and(|id| !scope.contains(&id)) { - return None; + return Err(FailedCheck::TaskGrantScope); } Some(scope) } @@ -392,13 +445,14 @@ pub(crate) fn authorize( authority.common = authority .common .with_proposal_task_grant(binding.clone(), operation) - .ok()?; + .map_err(|_| FailedCheck::TaskGrantScope)?; authority.task_grant = Some(binding); authority.proposal_scope = scope; } - _ => return None, + (Some(_), None) => return Err(FailedCheck::TaskGrantMissing), + (None, Some(_)) => return Err(FailedCheck::TaskGrantScope), } - Some(authority) + Ok(authority) } pub(super) fn selected_profile(raw: Option<&str>) -> Result, ()> { @@ -490,6 +544,7 @@ pub(super) async fn known_action_refusal( operation: ProposalAuthorityOperation, method: HttpMethod, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { let profile = selected.filter(|profile| match operation { ProposalAuthorityOperation::Start => action.permissions.iter().any(|grant| { @@ -526,7 +581,7 @@ pub(super) async fn known_action_refusal( ) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => unavailable(), } } @@ -537,6 +592,7 @@ async fn audited_list_concealment( claims: &VerifiedRequestClaims, selected: Option<&str>, correlation: &RequestCorrelation, + check: FailedCheck, ) -> Response { let selected_access_profile = selected.filter(|selected| { service.registry.actions().actions.iter().any(|action| { @@ -565,7 +621,7 @@ async fn audited_list_concealment( }) .await { - Ok(()) => concealed(), + Ok(()) => concealed(check), Err(_) => unavailable(), } } @@ -581,10 +637,10 @@ pub(super) async fn start( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(action) = service .registry @@ -593,29 +649,33 @@ pub(super) async fn start( .iter() .find(|action| action.id == route.action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if route.operation != Operation::Start || route.path != action.route { - return concealed(); + return concealed(FailedCheck::Visibility); } - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Start, None, - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Start, - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Start, + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; if !single_content_type(&headers, "application/json") { return admitted_http_refusal( @@ -728,17 +788,17 @@ pub(super) async fn get( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -748,33 +808,37 @@ pub(super) async fn get( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; match mutations .proposal_document(id, &authority, &claims, &correlation) .await { Ok((value, etag)) => json_response(value, Some(&etag)), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -790,24 +854,24 @@ pub(super) async fn submission( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Some(version) = version .parse::() .ok() .filter(|parsed| *parsed > 0 && parsed.to_string() == version) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -817,26 +881,30 @@ pub(super) async fn submission( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; match mutations .proposal_submission_read(id, version, &authority, &correlation) @@ -844,7 +912,7 @@ pub(super) async fn submission( { Ok(Some(value)) => json_response(value, None), Ok(None) => fixed_problem(ProblemCode::ProposalSubmissionExpired), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -860,10 +928,10 @@ pub(super) async fn transition( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let operation = match operation.as_str() { "edit" => ProposalOperation::Edit, @@ -873,14 +941,14 @@ pub(super) async fn transition( "apply" => ProposalOperation::Apply, "rebase" => ProposalOperation::Rebase, "retry" => ProposalOperation::Retry, - _ => return concealed(), + _ => return concealed(FailedCheck::Operation), }; let Ok(selected) = selected_profile(raw_query.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -890,29 +958,33 @@ pub(super) async fn transition( .iter() .find(|a| a.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; let rebase_start_authority = if operation == ProposalOperation::Rebase { - match authorize( + match authorize_checked( &service.registry, action, &claims, @@ -920,14 +992,14 @@ pub(super) async fn transition( ProposalAuthorityOperation::Start, None, ) { - Some(authority) => Some(authority), - None => { + Ok(authority) => Some(authority), + Err(check) => { return admitted_http_refusal( mutations, &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(check), ) .await; } @@ -1105,7 +1177,7 @@ pub(super) async fn transition( "", service.field_encryption.as_deref(), ), - Err(MutationError::ProposalGuardFailed(failure)) => { + Err(MutationError::ProposalGuardFailed(failure)) => crate::correlation::note_refusal( guard_failure_response( &service, &authority, @@ -1114,8 +1186,9 @@ pub(super) async fn transition( &correlation, *failure, ) - .await - } + .await, + FailedCheck::ActionGuard, + ), Err(error) => proposal_problem(error), } } @@ -1172,7 +1245,7 @@ async fn guard_failure_response( ) { return mutation_problem(MutationError::PreconditionFailed); } - crate::correlation::action_guard_failure_response(guard.reason.clone()) + crate::correlation::action_guard_failure_response(guard.reason.clone(), guard.label.clone()) } /// Batch transport only: every item retains the scalar context read's current @@ -1184,23 +1257,23 @@ pub(super) async fn review_context_batch( RawQuery(raw): RawQuery, ) -> Response { let Some(raw) = raw.filter(|raw| raw.len() <= MAX_RAW_QUERY_BYTES) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let mut ids = None; let mut profile = Vec::new(); for pair in raw.split('&') { let Some((key, value)) = pair.split_once('=') else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(key) = percent_decode(key) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; if key == "ids" { if ids.is_some() { - return concealed(); + return concealed(FailedCheck::Visibility); } let Ok(value) = percent_decode(value) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; ids = Some(value); } else { @@ -1208,7 +1281,7 @@ pub(super) async fn review_context_batch( } } let Some(ids) = ids else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let ids = ids.split(',').collect::>(); let mut distinct = BTreeSet::new(); @@ -1219,15 +1292,16 @@ pub(super) async fn review_context_batch( || !distinct.insert(*id) }) { - return concealed(); + return concealed(FailedCheck::Visibility); } let profile = Some(profile.join("&")); if selected_profile(profile.as_deref()).is_err() { - return concealed(); + return concealed(FailedCheck::Visibility); } // Bound the aggregate independently of each Proposal's configured context. let mut remaining = 8 * 1024 * 1024 - 64 * 1024; let mut items = Vec::with_capacity(ids.len()); + let mut concealed_items = Vec::new(); for id in ids { let response = review_read( service.clone(), @@ -1249,10 +1323,19 @@ pub(super) async fn review_context_batch( }; items.push(json!({"id":id,"status":"visible","context":context})); } - StatusCode::NOT_FOUND => items.push(json!({"id":id,"status":"concealed"})), + StatusCode::NOT_FOUND => { + concealed_items.push(response); + items.push(json!({"id":id,"status":"concealed"})); + } _ => return response, } } + // The batch answers 200, so each concealed item records its own refusal. + // They are recorded only once the batch answers, so a batch that ends with + // another answer counts nothing the caller did not see. + for response in &concealed_items { + crate::correlation::record_noted_refusal(response, &correlation); + } json_response(json!({"items":items}), None) } @@ -1302,17 +1385,17 @@ pub(super) async fn task_grant_context( body: Body, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(selected) = selected_profile(raw.as_deref()) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -1322,27 +1405,31 @@ pub(super) async fn task_grant_context( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let operation = ProposalOperation::GetTaskGrantContext; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Post, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Post, + &correlation, + check, + ) + .await; + } }; if !single_content_type(&headers, "application/json") { return admitted_http_refusal( @@ -1393,13 +1480,13 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; } let selected_fields = request.fields.iter().cloned().collect::>(); let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return concealed(); + return concealed(FailedCheck::Operation); }; let granted = proposal.permissions.iter().find(|permission| { permission.profile_id == authority.common.access_profile() @@ -1414,7 +1501,7 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Disclosure), ) .await; } @@ -1431,7 +1518,7 @@ pub(super) async fn task_grant_context( &authority, HttpMethod::Post, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -1455,7 +1542,7 @@ pub(super) async fn task_grant_context( ); response } - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -1469,21 +1556,21 @@ async fn review_read( correlation: RequestCorrelation, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok(id) = Uuid::parse_str(&id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let Ok((selected, include_progress)) = (if operation == ProposalOperation::GetReviewStatus { review_status_options(raw.as_deref()) } else { selected_profile(raw.as_deref()).map(|selected| (selected, false)) }) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let action_id = match mutations.proposal_action_id(id).await { Ok(Some(id)) => id, - Ok(None) => return concealed(), + Ok(None) => return concealed(FailedCheck::Visibility), Err(error) => return proposal_problem(error), }; let Some(action) = service @@ -1493,26 +1580,30 @@ async fn review_read( .iter() .find(|action| action.id == action_id) else { - return concealed(); + return concealed(FailedCheck::Visibility); }; - let Some(authority) = authorize( + let authority = match authorize_checked( &service.registry, action, &claims, selected.as_deref(), ProposalAuthorityOperation::Lifecycle(operation), Some(id), - ) else { - return known_action_refusal( - mutations, - action, - &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(operation), - HttpMethod::Get, - &correlation, - ) - .await; + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(operation), + HttpMethod::Get, + &correlation, + check, + ) + .await; + } }; let records = review_record_authorities( &service.registry, @@ -1528,7 +1619,7 @@ async fn review_read( &authority, HttpMethod::Get, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -1537,7 +1628,7 @@ async fn review_read( .await { Ok((value, etag)) => json_response(value, etag.as_deref()), - Err(MutationError::PreconditionFailed) => concealed(), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_problem(error), } } @@ -1634,31 +1725,42 @@ pub(super) async fn list( RawQuery(raw_query): RawQuery, ) -> Response { let Some(mutations) = &service.mutations else { - return concealed(); + return concealed(FailedCheck::Visibility); }; let selected = match proposal_list_admission_profile(raw_query.as_deref()) { Ok(selected) => selected, Err(()) => { - return audited_list_concealment(mutations, &service, &claims, None, &correlation) - .await; - } - }; - let authorities = service - .registry - .actions() - .actions - .iter() - .filter_map(|action| { - authorize( - &service.registry, - action, + return audited_list_concealment( + mutations, + &service, &claims, - selected.as_deref(), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), None, + &correlation, + FailedCheck::AccessProfile, ) - }) - .collect::>(); + .await; + } + }; + // When no Proposal action admits the caller, the first Proposal action's + // refusal names the check. A registry with none refuses on the profile. + let mut first_refusal = None; + let mut authorities = Vec::new(); + for action in &service.registry.actions().actions { + match authorize_checked( + &service.registry, + action, + &claims, + selected.as_deref(), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), + None, + ) { + Ok(authority) => authorities.push(authority), + Err(check) if matches!(action.execution, CompiledActionExecution::Proposal { .. }) => { + first_refusal.get_or_insert(check); + } + Err(_) => {} + } + } if authorities.is_empty() { return audited_list_concealment( mutations, @@ -1666,6 +1768,7 @@ pub(super) async fn list( &claims, selected.as_deref(), &correlation, + first_refusal.unwrap_or(FailedCheck::AccessProfile), ) .await; } diff --git a/crates/registry-breg/src/api/record_attachments.rs b/crates/registry-breg/src/api/record_attachments.rs index 528902a9c1..3b2dc33e9b 100644 --- a/crates/registry-breg/src/api/record_attachments.rs +++ b/crates/registry-breg/src/api/record_attachments.rs @@ -65,7 +65,7 @@ async fn download( let mut surface = match super::authorize_route_with_reason(&service, &route, &claims, &options) { Ok(surface) => surface, - Err(reason) => { + Err(refusal) => { return audited_read_concealment( &service, &audit_route, @@ -73,7 +73,7 @@ async fn download( &claims, record_id, &correlation, - reason, + refusal, ) .await; } @@ -103,16 +103,22 @@ async fn download( }); // The attachment row-level policy needs a principal, so a principal-less // caller is refused here rather than by an empty database answer. - if claims.principal().is_none() - || record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) - || !granted - { + let refused_check = if claims.principal().is_none() { + Some(FailedCheck::TokenClaims) + } else if record_id.is_none_or(|id| !valid_canonical_record_uuid(id)) { + Some(FailedCheck::Visibility) + } else if !granted { + Some(FailedCheck::Operation) + } else { + None + }; + if let Some(check) = refused_check { return audited_read_refusal( &service, &audit_route, &surface, record_id, - concealed(), + concealed(check), &correlation, ) .await; @@ -139,7 +145,7 @@ async fn download( .await { Ok(Some(held)) => attachment_response(held), - Ok(None) => concealed(), + Ok(None) => concealed(FailedCheck::Visibility), Err(_) => unavailable(), } } diff --git a/crates/registry-breg/src/api/statistics.rs b/crates/registry-breg/src/api/statistics.rs index 2b5f6f856c..07726dd907 100644 --- a/crates/registry-breg/src/api/statistics.rs +++ b/crates/registry-breg/src/api/statistics.rs @@ -156,7 +156,7 @@ pub(super) fn authorize_with_reason( kind: Kind, claims: &VerifiedRequestClaims, selected: Option<&str>, -) -> Result { +) -> Result { let eligible = |id: &str| match kind { Kind::Live => dataset.live_profiles.contains(id), Kind::Exact => dataset @@ -181,13 +181,13 @@ pub(super) fn authorize_with_reason( let selected = selected .or(configured_default) .or_else(|| default.map(String::as_str)) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; if !eligible(selected) { - return Err(ReadRefusalReason::SurfaceUnavailable); + return Err(RouteRefusal::surface(FailedCheck::AccessProfile)); } claims .principal() - .ok_or(ReadRefusalReason::ProfileAdmission)?; + .ok_or(RouteRefusal::admission_check(FailedCheck::TokenClaims))?; if matches!( kind, Kind::Live | Kind::Publish | Kind::DryRun | Kind::Withdraw @@ -202,7 +202,7 @@ pub(super) fn authorize_with_reason( && route.operation == Operation::List && read_path_for_route(service, route).is_none() }) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; let mut options = QueryOptions::default(); options.parsed.access_profile = Some(selected.to_owned()); return authorize_route_with_reason(service, route, claims, &options) @@ -211,18 +211,15 @@ pub(super) fn authorize_with_reason( let profile = dataset .access_profiles .get(selected) - .ok_or(ReadRefusalReason::SurfaceUnavailable)?; - let boundaries = authorize_profile_claims(profile, claims) - .map_err(|_| ReadRefusalReason::ProfileAdmission)?; + .ok_or(RouteRefusal::surface(FailedCheck::AccessProfile))?; + let boundaries = authorize_profile_claims(profile, claims).map_err(RouteRefusal::admission)?; Ok(AuthorizedRequestContext::new( claims.principal().map(str::to_owned), claims.purpose().map(str::to_owned), selected.to_owned(), boundaries, ) - .with_task_grant( - task_grant_binding(profile, claims).map_err(|_| ReadRefusalReason::ProfileAdmission)?, - ) + .with_task_grant(task_grant_binding(profile, claims).map_err(RouteRefusal::admission)?) .with_audit_context(claims) .with_recipients(claims)) } @@ -397,7 +394,7 @@ async fn dispatch( &claims, None, &correlation, - concealed(), + concealed(FailedCheck::Visibility), ) .await; }; @@ -405,17 +402,17 @@ async fn dispatch( let context = match authorize_with_reason(&service, dataset, route.kind, &claims, selected.as_deref()) { Ok(context) => context, - Err(reason) => { + Err(refusal) => { let reason = (route.kind.method() == HttpMethod::Get - && reason == ReadRefusalReason::ProfileAdmission) - .then_some(reason); + && refusal.reason == ReadRefusalReason::ProfileAdmission) + .then_some(refusal.reason); return refusal_with_reason( &service, &route, &claims, selected.as_deref(), &correlation, - concealed(), + concealed(refusal.check), reason, ) .await; @@ -681,13 +678,13 @@ async fn execute( } Kind::Latest | Kind::Version => { if route.kind == Kind::Version && version.is_none() { - return Err(concealed()); + return Err(concealed(FailedCheck::Visibility)); } let stored = backend .read_version(StatisticsVersionReadRequest { context, dataset_id: &route.dataset, - period_code: period.ok_or_else(concealed)?, + period_code: period.ok_or_else(|| concealed(FailedCheck::Visibility))?, version, selection, deadline, @@ -791,7 +788,7 @@ async fn execute( .dry_run(StatisticsDryRunRequest { context, dataset_id: &route.dataset, - period_code: period.ok_or_else(concealed)?, + period_code: period.ok_or_else(|| concealed(FailedCheck::Visibility))?, status, computed_at: now, today, @@ -825,7 +822,7 @@ async fn execute( .as_object() .filter(|o| o.len() == 1) .ok_or_else(invalid_request)?; - let period = period.ok_or_else(concealed)?; + let period = period.ok_or_else(|| concealed(FailedCheck::Visibility))?; let held = if route.kind == Kind::Publish { let status = match object.get("status").and_then(Value::as_str) { Some("provisional") => ReleaseStatus::Provisional, @@ -858,7 +855,7 @@ async fn execute( context, dataset_id: &route.dataset, period_code: period, - version: version.ok_or_else(concealed)?, + version: version.ok_or_else(|| concealed(FailedCheck::Visibility))?, reason, idempotency_key: key, route_id: &route.id(), @@ -953,7 +950,7 @@ fn negotiate(headers: &HeaderMap) -> bool { } fn service_problem(error: StatisticsServiceError) -> Response { match error { - StatisticsServiceError::Concealed => concealed(), + StatisticsServiceError::Concealed => concealed(FailedCheck::Visibility), StatisticsServiceError::QueryInvalid { field_path } => { statistics_invalid_query_at(field_path) } @@ -1142,7 +1139,7 @@ pub(super) async fn unknown( claims, None, correlation, - concealed(), + super::unknown_route(), RefusalHttpMethod::from_request(method), "statistics.unknown", None, diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 94dcb824a8..0eb719aef4 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -135,7 +135,7 @@ async fn task_granted_invoke_uses_exact_action_scope_and_frozen_subjects() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -329,7 +329,7 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -677,7 +677,7 @@ async fn signed_task_token_cannot_discover_or_invoke_an_ordinary_immediate_actio Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) @@ -1132,7 +1132,7 @@ async fn human_identity_is_the_principal_claim_and_a_human_token_without_it_is_r Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) @@ -1188,7 +1188,7 @@ async fn delegated_token_is_refused_at_immediate_action_admission() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())) .with_contextual_claims( @@ -1708,7 +1708,7 @@ async fn task_record_reads_intersect_profile_with_composed_proposal_scope() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -1849,7 +1849,7 @@ impl BoundGrantFixture { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("request_purpose".into())), ) @@ -2068,7 +2068,7 @@ async fn task_statistics_reads_bind_the_grant_to_the_request_principal_and_purpo }; for (case, claims) in [("principal", &other_principal), ("purpose", &other_purpose)] { assert_eq!( - read(claims).err(), + read(claims).err().map(|refusal| refusal.reason), Some(ReadRefusalReason::ProfileAdmission), "a grant for another {case} cannot read released statistics" ); diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 38b65afaf4..57b2a6edc3 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -1046,6 +1046,7 @@ pub(crate) fn openapi_action_availability_response_schema(action: &CompiledActio "observedRevision": observed_revision, "reason": {"const": "guard-not-satisfied"}, "guardReason": {"type":"string","pattern":"^[a-z][a-z0-9_-]{0,63}$"}, + "guardLabel": {"type":"string","minLength":1,"maxLength":256}, "recovery": {"const": "none"}, }, }, @@ -1942,13 +1943,7 @@ fn action_problem_responses( detail: "The request is invalid.", }], ), - ( - "401", - vec![ProblemExample { - code: "authentication.refused", - detail: "The bearer credential is missing or refused.", - }], - ), + ("401", vec![AUTHENTICATION_REFUSAL_EXAMPLE]), ( "404", vec![ProblemExample { @@ -2741,8 +2736,8 @@ pub(crate) fn append_review_completion_openapi( "post": { "operationId": "receiveReviewCompletion", "summary": "Receive a Casework review completion", - "description": "Available when a review authority configures a completion token and recipient binding.", - "security": [{"bearerAuth": []}], + "description": "Available when a review authority configures a completion block.", + "security": [{"reviewCompletion": []}], "parameters": [ { "name": "Registry-Recipient-Binding", @@ -2751,11 +2746,23 @@ pub(crate) fn append_review_completion_openapi( "schema": {"type": "string", "minLength": 1, "maxLength": 256} }, { - "name": "Idempotency-Key", + "name": "webhook-id", "in": "header", "required": true, "description": "Must equal eventId.", "schema": {"type": "string", "format": "uuid"} + }, + { + "name": "webhook-timestamp", + "in": "header", + "required": true, + "schema": {"type": "string", "pattern": "^(0|[1-9][0-9]{0,19})$"} + }, + { + "name": "webhook-signature", + "in": "header", + "required": true, + "schema": {"type": "string"} } ], "requestBody": { @@ -2768,8 +2775,16 @@ pub(crate) fn append_review_completion_openapi( }, "responses": { "204": {"description": "Completion accepted or already recorded."}, - "400": {"description": "The completion or idempotency binding is invalid."}, - "401": {"description": "The completion authority could not be authenticated."}, + "400": {"description": "The completion is invalid or eventId differs from webhook-id."}, + "401": { + "description": "The completion authority could not be authenticated.", + "headers": { + "WWW-Authenticate": { + "schema": {"type": "string", "const": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\""} + } + } + }, + "413": {"description": "The completion body exceeds 2048 bytes. The response body is empty."}, "415": {"description": "The request is not application/json."}, "503": {"description": "The completion could not be durably recorded."} } @@ -2827,6 +2842,12 @@ pub(crate) fn openapi_components( "type": "http", "scheme": "bearer", "bearerFormat": "JWT" + }, + "reviewCompletion": { + "type": "apiKey", + "in": "header", + "name": "webhook-signature", + "description": "The review authority's configured completion key verifies the Standard Webhooks signature." } }, "schemas": schemas @@ -4258,6 +4279,14 @@ struct ProblemExample { detail: &'static str, } +const AUTHENTICATION_REFUSAL_EXAMPLE: ProblemExample = { + let code = crate::problem::ProblemCode::AuthenticationRefused; + ProblemExample { + code: code.code(), + detail: code.description(), + } +}; + const FILTER_REQUIRED: ProblemExample = ProblemExample { code: crate::problem::ProblemCode::QueryFilterRequired.code(), detail: crate::problem::ProblemCode::QueryFilterRequired.description(), @@ -4325,13 +4354,7 @@ fn problem_responses( detail: "The request is invalid.", }], ), - ( - "401", - vec![ProblemExample { - code: "authentication.refused", - detail: "The bearer credential is missing or refused.", - }], - ), + ("401", vec![AUTHENTICATION_REFUSAL_EXAMPLE]), ( "404", vec![ProblemExample { diff --git a/crates/registry-breg/src/audit.rs b/crates/registry-breg/src/audit.rs index cb97c254ed..1c0fbd6e22 100644 --- a/crates/registry-breg/src/audit.rs +++ b/crates/registry-breg/src/audit.rs @@ -89,7 +89,7 @@ impl RegistryAudit { .destination() .for_process(COMPANION_PROCESS_ROLE) .map_err(|_| RegistryAuditError::Unavailable)?; - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|_| RegistryAuditError::Unavailable)?; Ok(Self::new(profile, writer)) @@ -1316,7 +1316,9 @@ pub mod test_support { /// process appending to the same destination would. #[must_use] pub fn audit(&self, profile: AuditProfile) -> RegistryAudit { - let writer = AuditWriter::from_line_sink(Box::new(CaptureSink(Arc::clone(&self.0)))); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(CaptureSink( + Arc::clone(&self.0), + ))); self.0 .lock() .expect("audit capture lock") diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 4cfab7bc98..b3e6d53c14 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -10,13 +10,15 @@ use std::time::{SystemTime, UNIX_EPOCH}; use axum::body::Body; use axum::extract::State; use axum::http::header::AUTHORIZATION; -use axum::http::{Request, StatusCode}; +use axum::http::Request; use axum::middleware::Next; use axum::response::Response; -use registry_platform_authcommon::{parse_bearer_token, validate_compact_access_token}; +use registry_platform_authcommon::{ + parse_bearer_token, validate_compact_access_token, BearerParseError, FailedCheck, +}; use registry_platform_oidc::{ - actor_kind, grant_claims, is_access_token_typ_pair, Audience, ClaimNames, JwksFetcher, - OidcError, TokenVerifier, TokenVerifierConfig, + actor_kind, grant_claims, is_access_token_typ_pair, Audience, ClaimError, ClaimNames, + GrantContextError, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, }; use serde_json::Value; use thiserror::Error; @@ -161,6 +163,28 @@ pub enum AuthenticationError { InvalidClaims, } +impl AuthenticationError { + /// Pair the failure with the check that produced it. The check is + /// operator-side only: it reaches the refusal counter and log line, never + /// the response. + fn because(self, check: FailedCheck) -> Refusal { + Refusal { error: self, check } + } +} + +/// A closed request failure and the check that failed. Every refusal built in +/// this module names its check, so none reaches the recording layer without +/// one. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Refusal { + error: AuthenticationError, + check: FailedCheck, +} + +fn invalid_claims(check: FailedCheck) -> Refusal { + AuthenticationError::InvalidClaims.because(check) +} + /// Production OIDC verifier plus the only claim mapping allowed to construct /// [`VerifiedRequestClaims`]. pub struct RegistryAuthenticator { @@ -183,14 +207,6 @@ pub struct RegistryAuthenticator { } impl RegistryAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "BReg authentication refused" - ); - } - /// Bind one exact platform verifier profile and one exact authority mapping /// to the immutable compiled Registry served by this process. pub fn new( @@ -229,16 +245,20 @@ impl RegistryAuthenticator { &self, token: &str, ) -> Result { + self.authenticate_checked(token) + .await + .map_err(|refusal| refusal.error) + } + + /// [`Self::authenticate`], with the check that refused the token. + pub(crate) async fn authenticate_checked( + &self, + token: &str, + ) -> Result { validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::MalformedCredential + AuthenticationError::MalformedCredential.because(FailedCheck::CredentialMalformed) })?; let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "BReg authentication refused" - ); // UnknownKid precedes signature verification and also covers denied // keys. It cannot establish rotation, regardless of the key source. if matches!(error, OidcError::UnknownKid) @@ -251,10 +271,10 @@ impl RegistryAuthenticator { check issuer key configuration and key policy before changing trust" ); } - AuthenticationError::VerificationRefused + AuthenticationError::VerificationRefused.because(error.failed_check()) })?; if !accepted_audience(verified.claims.aud.as_ref(), &self.audience) { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::TokenAudience)); } let claims = &verified.claims.extra; @@ -267,22 +287,25 @@ impl RegistryAuthenticator { subject.as_ref() } else { claims.get(&self.principal_claim) - })?; + }) + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let purpose = self .purpose_claim .as_deref() .map(|name| optional_direct_string(claims.get(name))) - .transpose()? + .transpose() + .map_err(|error| error.because(FailedCheck::TokenClaims))? .flatten(); if verified.scopes.len() > MAX_SCOPE_VALUES { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::TokenClaims)); } let scopes = verified .scopes .iter() .cloned() .map(validate_scope) - .collect::, _>>()?; + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let direct_claims = self .direct_claims .iter() @@ -296,19 +319,21 @@ impl RegistryAuthenticator { mapped_claim(value, expectation).map(|value| (name.clone(), value)) }) }) - .collect::, _>>()?; + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TokenClaims))?; let requester_client = verified .matched_client_id() - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::TokenClient))? .map(str::to_owned); - let actor_subject = optional_actor_subject(claims.get("act"), &self.issuer)?; + let actor_subject = optional_actor_subject(claims.get("act"), &self.issuer) + .map_err(|error| error.because(FailedCheck::Delegation))?; if let Some(actor) = actor_subject.as_deref() { let client = requester_client .as_deref() - .ok_or(AuthenticationError::InvalidClaims)?; + .ok_or_else(|| invalid_claims(FailedCheck::TokenClient))?; if self.trusted_actors.get(client).map(String::as_str) != Some(actor) { - return Err(AuthenticationError::InvalidClaims); + return Err(invalid_claims(FailedCheck::Delegation)); } } // A token exchange copies the subject's claims, so a kind claim on a @@ -318,10 +343,10 @@ impl RegistryAuthenticator { registry_platform_oidc::ActorKind::Agent } else { if !claims.contains_key(&self.contextual_claims.actor_kind) { - return Err(AuthenticationError::MissingActorKind); + return Err(AuthenticationError::MissingActorKind.because(FailedCheck::ActorKind)); } actor_kind(&verified.claims, &self.contextual_claims) - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::ActorKind))? }); // The person is named by the configured principal claim, the same // claim every access profile reads. A review authority compares this @@ -337,25 +362,25 @@ impl RegistryAuthenticator { }; let now = SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|_| AuthenticationError::InvalidClaims)? + .map_err(|_| invalid_claims(FailedCheck::TokenTime))? .as_secs(); - let grant = grant_claims(&verified.claims, &self.contextual_claims, now) - .map_err(|_| AuthenticationError::InvalidClaims)?; + let grant = + grant_claims(&verified.claims, &self.contextual_claims, now).map_err(|error| { + invalid_claims(match error { + ClaimError::Expired => FailedCheck::TaskGrantExpired, + _ => FailedCheck::TaskGrantClaims, + }) + })?; if let Some(grant) = &grant { grant - .verify_context(&verified, &self.audience) - .map_err(|_| AuthenticationError::InvalidClaims)?; - if !task_grant_token_lifetime_is_short( - verified.claims.iat, - verified.claims.exp, - now, - self.leeway, - ) { - return Err(AuthenticationError::InvalidClaims); - } + .verify_context_without_peer_policy(&verified, &self.audience) + .map_err(|error| invalid_claims(grant_context_check(error)))?; + task_grant_token_lifetime(verified.claims.iat, verified.claims.exp, now, self.leeway) + .map_err(invalid_claims)?; } let grant_subjects = if grant.is_some() { - bounded_identity(claims.get("identity"))? + bounded_identity(claims.get("identity")) + .map_err(|error| error.because(FailedCheck::TaskGrantClaims))? } else { BTreeMap::new() }; @@ -372,7 +397,8 @@ impl RegistryAuthenticator { mapped_claim(value, expectation).map(|value| (name.clone(), value)) }) }) - .collect::, _>>()? + .collect::, _>>() + .map_err(|error| error.because(FailedCheck::TaskGrantClaims))? } else { direct_claims }; @@ -401,29 +427,38 @@ impl RegistryAuthenticator { }) .and_then(|claims| claims.with_human_identity(human_identity)) .and_then(|claims| claims.with_consent_claims(recipients, &self.consent_decisions)) - .map_err(|_| AuthenticationError::InvalidClaims) + .map_err(|_| invalid_claims(FailedCheck::TokenClaims)) } } -/// A task-grant token must carry `iat` and `exp`, be issued for between 1 and -/// [`MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS`], and carry an `iat` no later than -/// `now` plus the verifier's clock leeway, so its issued lifetime also bounds -/// the time it is honoured from this clock. -fn task_grant_token_lifetime_is_short( +/// A task-grant token must carry `iat` and `exp`, with `exp` after `iat` and +/// `iat` no later than `now` plus the verifier's clock leeway. A token that +/// fails any of those is a malformed grant token (`TaskGrantClaims`). One that +/// is well formed but issued for more than +/// [`MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS`] is refused as `TaskGrantLifetime`, +/// so its issued lifetime also bounds the time it is honoured from this clock. +fn task_grant_token_lifetime( issued_at: Option, expires_at: Option, now: u64, leeway: Duration, -) -> bool { +) -> Result<(), FailedCheck> { let latest_issued_at = now .checked_add(leeway.as_secs()) .and_then(|latest| i64::try_from(latest).ok()); - issued_at - .zip(expires_at) - .zip(latest_issued_at) - .filter(|((issued_at, _), latest_issued_at)| issued_at <= latest_issued_at) - .and_then(|((issued_at, expires_at), _)| expires_at.checked_sub(issued_at)) - .is_some_and(|lifetime| (1..=MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS).contains(&lifetime)) + let (Some(issued_at), Some(expires_at), Some(latest_issued_at)) = + (issued_at, expires_at, latest_issued_at) + else { + return Err(FailedCheck::TaskGrantClaims); + }; + let lifetime = expires_at.saturating_sub(issued_at); + if issued_at > latest_issued_at || lifetime < 1 { + return Err(FailedCheck::TaskGrantClaims); + } + if lifetime > MAX_TASK_GRANT_TOKEN_LIFETIME_SECONDS { + return Err(FailedCheck::TaskGrantLifetime); + } + Ok(()) } fn admit_refusal_warning(last_warning: &Mutex>, now: Instant) -> bool { @@ -470,45 +505,58 @@ pub(crate) async fn authenticate_request( ) -> Response { request.extensions_mut().remove::(); let token = match bearer_token(request.headers()) { - Ok(Some(token)) => token, - Ok(None) | Err(_) => { - authenticator.record_header_refusal(); - return authentication_refused(); - } + Ok(token) => token, + Err(check) => return authentication_refused(check), }; - let claims = match authenticator.authenticate(token).await { + let claims = match authenticator.authenticate_checked(token).await { Ok(claims) => claims, - Err(AuthenticationError::MissingActorKind) => { - // A caller can replay such a credential, so the warning is bounded - // the same way as an unknown key identifier. - if admit_refusal_warning(&authenticator.last_actor_kind_warning, Instant::now()) { - tracing::warn!( - target: "registry_breg::auth", - message = "verified credential is missing the configured actor-kind claim" - ); + Err(refusal) => { + if refusal.error == AuthenticationError::MissingActorKind { + // A caller can replay such a credential, so the warning is bounded + // the same way as an unknown key identifier. + if admit_refusal_warning(&authenticator.last_actor_kind_warning, Instant::now()) { + tracing::warn!( + target: "registry_breg::auth", + message = "verified credential is missing the configured actor-kind claim" + ); + } } - return authentication_refused(); + return authentication_refused(refusal.check); } - Err(_) => return authentication_refused(), + }; + let claims = match request + .extensions() + .get::() + { + Some(correlation) => claims.with_scope_declaration( + &authenticator.scope_claim, + correlation.declared_scope_slot(), + ), + None => claims, }; request.extensions_mut().insert(claims); next.run(request).await } -fn bearer_token(headers: &axum::http::HeaderMap) -> Result, AuthenticationError> { +/// The one bearer credential on a request, or the check it failed. A request +/// with no credential, or one in another scheme, names the missing +/// credential. A repeated or unreadable header, or a bearer that is not one +/// well-formed token, names the malformed credential. +pub(crate) fn bearer_token(headers: &axum::http::HeaderMap) -> Result<&str, FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); let Some(value) = values.next() else { - return Ok(None); + return Err(FailedCheck::CredentialMissing); }; if values.next().is_some() { - return Err(AuthenticationError::MalformedCredential); + return Err(FailedCheck::CredentialMalformed); } let value = value .to_str() - .map_err(|_| AuthenticationError::MalformedCredential)?; - parse_bearer_token(value) - .map(Some) - .map_err(|_| AuthenticationError::MalformedCredential) + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn validate_verifier_profile( @@ -956,19 +1004,89 @@ fn mapped_scalar_claim( Ok(value) } -pub(crate) fn authentication_refused() -> Response { - crate::correlation::problem_response( - StatusCode::UNAUTHORIZED, - "Unauthorized", - "The bearer credential is missing or refused.", - "authentication.refused", - ) +/// The check a task grant refused by its token context failed. A token with +/// no usable verified client fails the client check, and a grant bound to +/// another client or resource fails its binding. +fn grant_context_check(error: GrantContextError) -> FailedCheck { + match error { + GrantContextError::MissingVerifiedClient | GrantContextError::InvalidVerifiedClient => { + FailedCheck::TokenClient + } + GrantContextError::ClientMismatch | GrantContextError::ResourceMismatch => { + FailedCheck::TaskGrantBinding + } + _ => FailedCheck::TaskGrantClaims, + } +} + +/// The 401 for a missing or refused credential. The answer is the same for +/// every check, so a caller learns nothing about which one failed. +pub(crate) fn authentication_refused(check: FailedCheck) -> Response { + crate::api::refusal_problem(crate::problem::ProblemCode::AuthenticationRefused, check) } #[cfg(test)] mod tests { use super::*; + #[test] + fn a_grant_context_refusal_names_the_check_it_failed() { + for (error, check) in [ + ( + GrantContextError::MissingVerifiedClient, + FailedCheck::TokenClient, + ), + ( + GrantContextError::InvalidVerifiedClient, + FailedCheck::TokenClient, + ), + ( + GrantContextError::ClientMismatch, + FailedCheck::TaskGrantBinding, + ), + ( + GrantContextError::ResourceMismatch, + FailedCheck::TaskGrantBinding, + ), + ] { + assert_eq!(grant_context_check(error), check, "{error:?}"); + } + } + + #[test] + fn a_bearer_names_the_check_its_header_failed() { + let headers = |values: &[&'static str]| { + let mut headers = axum::http::HeaderMap::new(); + for value in values { + headers.append(AUTHORIZATION, axum::http::HeaderValue::from_static(value)); + } + headers + }; + assert_eq!(bearer_token(&headers(&["Bearer a.b.c"])), Ok("a.b.c")); + for (values, check) in [ + (&[][..], FailedCheck::CredentialMissing), + (&["Basic abc"][..], FailedCheck::CredentialMissing), + ( + &["Bearer a", "Bearer b"][..], + FailedCheck::CredentialMalformed, + ), + (&["Bearer a"][..], FailedCheck::CredentialMalformed), + (&["Bearer"][..], FailedCheck::CredentialMalformed), + (&["Bearer a b"][..], FailedCheck::CredentialMalformed), + ] { + assert_eq!(bearer_token(&headers(values)), Err(check), "{values:?}"); + } + let mut unreadable = axum::http::HeaderMap::new(); + unreadable.insert( + AUTHORIZATION, + axum::http::HeaderValue::from_bytes(b"Bearer \xff").unwrap(), + ); + assert_eq!( + bearer_token(&unreadable), + Err(FailedCheck::CredentialMalformed) + ); + } + #[test] fn refusal_warnings_recover_poisoned_timestamps_and_preserve_rate_limits() { let last_warning = Mutex::new(None); @@ -1017,35 +1135,98 @@ mod tests { )); } + /// Every 401 the service answers carries the failed check. Only the two + /// runtime constructors and the generated OpenAPI example can name the + /// refusal. Adding another call site requires updating this list. + #[test] + fn only_the_noting_constructors_build_a_401() { + fn visit(root: &std::path::Path, dir: &std::path::Path, found: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("source directory is readable") { + let path = entry.expect("directory entry is readable").path(); + if path.is_dir() { + visit(root, &path, found); + continue; + } + // Judge the path below `src`, so where the checkout lives + // cannot exclude the files. + let name = path + .strip_prefix(root) + .expect("the file is below the source directory") + .to_string_lossy() + .into_owned(); + if !name.ends_with(".rs") + || name.contains("tests") + || name == "problem.rs" + || name == "compiler.rs" + { + continue; + } + let text = std::fs::read_to_string(&path).expect("source file is readable"); + let production = text + .split("#[cfg(test)]\nmod tests {") + .next() + .unwrap_or_default(); + for needle in [ + "StatusCode::UNAUTHORIZED", + "ProblemCode::AuthenticationRefused", + ] { + for _ in production.matches(needle) { + found.push(format!( + "{needle} in {}", + path.file_name().expect("file name").to_string_lossy() + )); + } + } + } + } + let mut found = Vec::new(); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + visit(&root, &root, &mut found); + found.sort(); + assert_eq!( + found, + [ + "ProblemCode::AuthenticationRefused in artifacts.rs", + "ProblemCode::AuthenticationRefused in auth.rs", + "ProblemCode::AuthenticationRefused in mod.rs", + ] + ); + } + #[test] fn task_grant_tokens_must_be_issued_for_at_most_fifteen_minutes() { let issued = 1_800_000_000; let now = 1_800_000_000; let leeway = Duration::from_secs(60); - assert!(task_grant_token_lifetime_is_short( - Some(issued), - Some(issued + 900), - now, - leeway - )); - assert!(task_grant_token_lifetime_is_short( - Some(issued), - Some(issued + 1), - now, - leeway - )); + assert_eq!( + task_grant_token_lifetime(Some(issued), Some(issued + 900), now, leeway), + Ok(()) + ); + assert_eq!( + task_grant_token_lifetime(Some(issued), Some(issued + 1), now, leeway), + Ok(()) + ); for (issued_at, expires_at) in [ (Some(issued), Some(issued + 901)), (Some(issued - 604_200), Some(issued + 600)), + (Some(i64::MIN), Some(i64::MAX)), + ] { + assert_eq!( + task_grant_token_lifetime(issued_at, expires_at, now, leeway), + Err(FailedCheck::TaskGrantLifetime), + "iat {issued_at:?} and exp {expires_at:?} are too long" + ); + } + for (issued_at, expires_at) in [ (None, Some(issued + 600)), (Some(issued), None), (Some(issued), Some(issued)), (Some(issued + 1), Some(issued)), - (Some(i64::MIN), Some(i64::MAX)), ] { - assert!( - !task_grant_token_lifetime_is_short(issued_at, expires_at, now, leeway), - "iat {issued_at:?} and exp {expires_at:?} are refused" + assert_eq!( + task_grant_token_lifetime(issued_at, expires_at, now, leeway), + Err(FailedCheck::TaskGrantClaims), + "iat {issued_at:?} and exp {expires_at:?} are malformed" ); } } @@ -1056,29 +1237,22 @@ mod tests { let leeway = Duration::from_secs(60); let at = |offset: i64| i64::try_from(now).expect("test clock fits i64") + offset; for issued_at in [at(86_400), at(61)] { - assert!( - !task_grant_token_lifetime_is_short( - Some(issued_at), - Some(issued_at + 900), - now, - leeway - ), + assert_eq!( + task_grant_token_lifetime(Some(issued_at), Some(issued_at + 900), now, leeway), + Err(FailedCheck::TaskGrantClaims), "iat {issued_at} later than now plus leeway is refused" ); } for issued_at in [at(59), at(60)] { - assert!( - task_grant_token_lifetime_is_short( - Some(issued_at), - Some(issued_at + 900), - now, - leeway - ), + assert_eq!( + task_grant_token_lifetime(Some(issued_at), Some(issued_at + 900), now, leeway), + Ok(()), "iat {issued_at} within the leeway is accepted" ); } - assert!( - !task_grant_token_lifetime_is_short(Some(at(0)), Some(at(900)), u64::MAX, leeway), + assert_eq!( + task_grant_token_lifetime(Some(at(0)), Some(at(900)), u64::MAX, leeway), + Err(FailedCheck::TaskGrantClaims), "a clock that cannot bound iat refuses the token" ); } diff --git a/crates/registry-breg/src/commit_guard.rs b/crates/registry-breg/src/commit_guard.rs index 5ee66e8da8..50382b033b 100644 --- a/crates/registry-breg/src/commit_guard.rs +++ b/crates/registry-breg/src/commit_guard.rs @@ -44,7 +44,12 @@ pub(crate) fn guard_matches( actual.as_i64().is_some_and(|actual| actual <= maximum) } (None, None, None, None, Some(relation), None, None) => { - let Some(today) = registry_today(registry, now, guard.current_date_offset_days) else { + let Some(today) = registry_today( + registry, + now, + guard.current_date_offset_days, + guard.current_date_offset_months, + ) else { return false; }; actual @@ -68,24 +73,18 @@ pub(crate) fn guard_matches( } /// The registry's calendar date at `now`, the "today" a `currentDate` guard -/// compares against. A date that cannot be resolved fails the guard closed. +/// compares against, shifted by whole days or whole calendar months. A date +/// that cannot be resolved fails the guard closed. fn registry_today( registry: &CompiledRegistry, now: time::OffsetDateTime, offset_days: i32, + offset_months: i32, ) -> Option { - // The same years 1 through 9999 the Rhai date helpers allow. let shifted = registry .local_date_at(now) .ok() - .and_then(|date| { - if offset_days >= 0 { - date.checked_add_days(chrono::Days::new(offset_days as u64)) - } else { - date.checked_sub_days(chrono::Days::new(u64::from(offset_days.unsigned_abs()))) - } - }) - .filter(|date| (1..=9999).contains(&chrono::Datelike::year(date))); + .and_then(|date| shift_date(date, offset_days, offset_months)); match shifted { Some(date) => Some(date), None => { @@ -94,6 +93,7 @@ fn registry_today( #[cfg(feature = "runtime")] tracing::error!( offset_days, + offset_months, "a currentDate guard could not resolve the registry's offset date and fails closed" ); None @@ -101,6 +101,26 @@ fn registry_today( } } +/// Shift a date by whole days, or by whole calendar months that clamp to the +/// last day of a shorter month, and keep it within the years 1 through 9999 +/// the Rhai date helpers allow. A compiled guard carries at most one nonzero +/// offset. +fn shift_date(date: chrono::NaiveDate, days: i32, months: i32) -> Option { + let shifted = if months >= 0 { + date.checked_add_months(chrono::Months::new(months.unsigned_abs())) + } else { + date.checked_sub_months(chrono::Months::new(months.unsigned_abs())) + }?; + let shifted = if days >= 0 { + shifted.checked_add_days(chrono::Days::new(u64::from(days.unsigned_abs()))) + } else { + shifted.checked_sub_days(chrono::Days::new(u64::from(days.unsigned_abs()))) + }?; + (1..=9999) + .contains(&chrono::Datelike::year(&shifted)) + .then_some(shifted) +} + /// Order a stored value against a submitted one. The compiler only pairs a /// field with an input of the same integer, date, or instant type, so the value /// shape tells the three apart: numbers are integers, strings are instants for a @@ -202,7 +222,9 @@ mod tests { at_least: None, at_most: None, current_date: None, + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, } @@ -211,7 +233,7 @@ mod tests { #[test] fn the_offset_date_stays_within_years_1_to_9999() { let registry = registry(Some("UTC")); - let date = |now, offset| registry_today(®istry, now, offset); + let date = |now, offset| registry_today(®istry, now, offset, 0); assert_eq!( date(datetime!(9999-12-30 12:00 UTC), 1), chrono::NaiveDate::from_ymd_opt(9999, 12, 31) @@ -224,6 +246,82 @@ mod tests { assert_eq!(date(datetime!(0001-01-01 12:00 UTC), -1), None); } + #[test] + fn a_month_offset_clamps_to_the_last_day_of_a_shorter_month() { + let registry = registry(Some("UTC")); + let date = |now, months| registry_today(®istry, now, 0, months); + let ymd = |year, month, day| chrono::NaiveDate::from_ymd_opt(year, month, day); + // January 31 plus one month is February 28, or 29 in a leap year. + assert_eq!(date(datetime!(2026-01-31 12:00 UTC), 1), ymd(2026, 2, 28)); + assert_eq!(date(datetime!(2028-01-31 12:00 UTC), 1), ymd(2028, 2, 29)); + // March 31 minus one month is the last day of February. + assert_eq!(date(datetime!(2026-03-31 12:00 UTC), -1), ymd(2026, 2, 28)); + assert_eq!(date(datetime!(2028-03-31 12:00 UTC), -1), ymd(2028, 2, 29)); + // A shift across a year boundary changes the year. + assert_eq!(date(datetime!(2026-12-15 12:00 UTC), 1), ymd(2027, 1, 15)); + assert_eq!(date(datetime!(2026-01-15 12:00 UTC), -1), ymd(2025, 12, 15)); + assert_eq!(date(datetime!(2026-10-14 12:00 UTC), 0), ymd(2026, 10, 14)); + // A shift past year 9999 or before year 1 fails closed. + assert_eq!(date(datetime!(9999-12-15 12:00 UTC), 1), None); + assert_eq!(date(datetime!(9999-11-15 12:00 UTC), 1), ymd(9999, 12, 15)); + assert_eq!(date(datetime!(0001-01-15 12:00 UTC), -1), None); + } + + #[test] + fn the_guard_and_the_planner_helper_agree_on_month_arithmetic() { + let starts = [ + (2026, 1, 31), + (2028, 1, 31), + (2026, 3, 31), + (2028, 2, 29), + (2026, 12, 15), + (2026, 1, 1), + (2024, 2, 29), + (2026, 5, 31), + (2026, 10, 14), + (1, 1, 31), + (9999, 12, 31), + ]; + let months = [ + -25, -13, -12, -2, -1, 0, 1, 2, 12, 13, 24, 100, -100, 12_000, -12_000, + ]; + for (year, month, day) in starts { + let start = chrono::NaiveDate::from_ymd_opt(year, month, day).unwrap(); + for offset in months { + let guard = shift_date(start, 0, offset).map(|date| date.to_string()); + let planner = + crate::rhai_planner::add_months(start.to_string().into(), offset.into()) + .ok() + .map(|date| date.to_string()); + assert_eq!(guard, planner, "{start} plus {offset} months"); + } + } + } + + #[test] + fn a_current_date_guard_applies_its_signed_month_offset() { + let inputs = Map::new(); + let mut guard = guard(); + guard.current_date = Some(CompiledCurrentDateRelation::OnOrAfter); + guard.current_date_offset_months = 1; + let at = |stored: &str, now| { + guard_matches( + &guard, + &inputs, + json!({"value": stored}).as_object().unwrap(), + ®istry(Some("UTC")), + now, + false, + ) + }; + assert!(at("2026-02-28", datetime!(2026-01-31 12:00 UTC))); + assert!(!at("2026-02-27", datetime!(2026-01-31 12:00 UTC))); + assert!(at("2026-11-14", noon())); + assert!(!at("2026-11-13", noon())); + // An offset past year 9999 fails closed. + assert!(!at("9999-12-31", datetime!(9999-12-15 12:00 UTC))); + } + #[test] fn missing_values_and_ambiguous_predicates_fail_closed() { let mut guard = guard(); diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 05695dc317..5c4a2b33f5 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -140,6 +140,17 @@ pub struct RegistryProject { schemars(schema_with = "local_id_map_schema::") )] pub value_types: BTreeMap, + /// Named lists of row boundaries, declared once and referenced as + /// `rowBoundaries: {rowBoundarySet: }` wherever a row reach is written + /// in this file. A reference expands to the set's boundaries when the file + /// is read, so each grant still states its own reach. A set holds at least + /// one boundary and is never `unrestricted`. + #[serde(default, skip_serializing, deserialize_with = "local_id_map")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "local_id_map_schema::") + )] + pub row_boundary_sets: BTreeMap, /// Written as a mapping from each function id to the rest of the function /// (CFG-ID-5) and held sorted by id. #[serde( @@ -426,8 +437,33 @@ pub struct ReviewAuthoritySource { // Authored once per bounded package, rather than allocated per Record. #[allow(clippy::large_enum_variant)] pub enum ActionExecutionSource { - Immediate {}, - Proposal { proposal: ProposalPolicySource }, + Immediate { + #[serde( + default, + skip_serializing_if = "ActionConcurrency::is_condition_required" + )] + concurrency: ActionConcurrency, + }, + Proposal { + proposal: ProposalPolicySource, + }, +} +/// How an immediate Action guards its patches against a concurrent write. +/// `condition-required` asks the caller to prove the revision it saw. +/// `current-revision` evaluates the Action's commit guards against the locked +/// current row instead, so the caller sends no condition. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ActionConcurrency { + #[default] + ConditionRequired, + CurrentRevision, +} +impl ActionConcurrency { + pub fn is_condition_required(&self) -> bool { + matches!(self, Self::ConditionRequired) + } } registry_platform_yaml::tagged_union!(ActionExecutionSource, tag = "mode"); serialize_tagged_union!(ActionExecutionSource, tag = "mode"); @@ -859,6 +895,168 @@ pub struct ProposalTargetPermissionSource { pub row_boundaries: Vec, } +/// A reusable list of row boundaries, written under `rowBoundarySets`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RowBoundarySetSource(pub Vec); + +impl<'de> Deserialize<'de> for RowBoundarySetSource { + fn deserialize>(deserializer: D) -> Result { + sentinel::row_boundary_set_rows(deserializer).map(Self) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RowBoundarySetSource { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "RowBoundarySetSource".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + generator.subschema_for::, sentinel::RowBoundarySetRows>>() + } +} + +/// Replaces every `rowBoundaries: {rowBoundarySet: }` written where a row +/// reach is authored with the boundaries the file's set lists, and reports +/// whether it replaced any. Those places are a profile's record permissions, +/// its Action and Proposal targets, a Record type's access requirements, and +/// a module profile. A mapping of that shape anywhere else, such as inside a +/// structured field schema, is ordinary data and stays as written. A reference +/// to a set the file does not declare, or one that carries another member, is +/// refused: an empty list means every row, so no reference may fall through +/// to one. Sets are read before this runs, so each holds at least one +/// boundary. +fn resolve_row_boundary_sets(value: &mut Value) -> Result { + let sets = value + .get("rowBoundarySets") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let mut replaced = false; + for (pointer, profile) in entries_mut(value, "accessProfiles", "") { + replaced |= resolve_in_project_profile(profile, &pointer, &sets)?; + } + for collection in ["recordTypes", "extendRecordTypes"] { + for (pointer, record_type) in entries_mut(value, collection, "") { + replaced |= resolve_at(record_type, "accessRequirements", &pointer, &sets)?; + for (pointer, profile) in entries_mut(record_type, "accessProfiles", &pointer) { + replaced |= resolve_at(profile, "rowBoundaries", &pointer, &sets)?; + } + } + } + Ok(replaced) +} + +/// The members of `parent[member]`, a mapping keyed by id or a list, with the +/// JSON pointer of each. +fn entries_mut<'a>( + parent: &'a mut Value, + member: &str, + parent_pointer: &str, +) -> Vec<(String, &'a mut Value)> { + let base = format!("{parent_pointer}/{member}"); + match parent.get_mut(member) { + Some(Value::Object(items)) => items + .iter_mut() + .map(|(key, item)| { + ( + format!("{base}/{}", key.replace('~', "~0").replace('/', "~1")), + item, + ) + }) + .collect(), + Some(Value::Array(items)) => items + .iter_mut() + .enumerate() + .map(|(index, item)| (format!("{base}/{index}"), item)) + .collect(), + _ => Vec::new(), + } +} + +fn resolve_in_project_profile( + profile: &mut Value, + pointer: &str, + sets: &serde_json::Map, +) -> Result { + let Some(permissions) = profile.get_mut("permissions") else { + return Ok(false); + }; + let permissions_pointer = format!("{pointer}/permissions"); + let mut replaced = false; + for (pointer, permission) in entries_mut(permissions, "records", &permissions_pointer) { + replaced |= resolve_at(permission, "rowBoundaries", &pointer, sets)?; + } + for kind in ["actions", "proposals"] { + for (pointer, permission) in entries_mut(permissions, kind, &permissions_pointer) { + for (pointer, target) in entries_mut(permission, "targets", &pointer) { + replaced |= resolve_at(target, "rowBoundaries", &pointer, sets)?; + } + } + } + Ok(replaced) +} + +/// Resolves a reference at `owner[member]`, where `member` is `rowBoundaries`, +/// or inside `owner[accessRequirements]`. +fn resolve_at( + owner: &mut Value, + member: &str, + pointer: &str, + sets: &serde_json::Map, +) -> Result { + let (owner, member, pointer) = if member == "accessRequirements" { + match owner.get_mut(member) { + Some(requirements) => ( + requirements, + "rowBoundaries", + format!("{pointer}/accessRequirements"), + ), + None => return Ok(false), + } + } else { + (owner, member, pointer.to_owned()) + }; + let Some(child) = owner.get_mut(member) else { + return Ok(false); + }; + let is_reference = child + .as_object() + .is_some_and(|object| object.contains_key("rowBoundarySet")); + if !is_reference { + return Ok(false); + } + let site = format!("{pointer}/{member}/rowBoundarySet"); + let Some(object) = child.as_object().filter(|object| object.len() == 1) else { + return Err(( + site, + "a row boundary set reference is a mapping with only a rowBoundarySet member", + )); + }; + let Some(name) = object.get("rowBoundarySet").and_then(Value::as_str) else { + return Err(( + site, + "rowBoundarySet must be a local row boundary set identifier", + )); + }; + let Some(boundaries) = sets + .get(name) + .and_then(Value::as_array) + .filter(|boundaries| !boundaries.is_empty()) + else { + return Err(( + site, + "rowBoundarySet must name a row boundary set declared in this file", + )); + }; + *child = Value::Array(boundaries.clone()); + Ok(true) +} + fn resolve_local_value_types(value: &mut Value) -> Result<(), (String, &'static str)> { let types = value .get("valueTypes") @@ -1728,6 +1926,17 @@ pub struct RegistryModule { schemars(schema_with = "local_id_map_schema::") )] pub value_types: BTreeMap, + /// Named lists of row boundaries, declared once and referenced as + /// `rowBoundaries: {rowBoundarySet: }` wherever a row reach is written + /// in this file. A reference expands to the set's boundaries when the file + /// is read, so each grant still states its own reach. A set holds at least + /// one boundary and is never `unrestricted`. + #[serde(default, skip_serializing, deserialize_with = "local_id_map")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "local_id_map_schema::") + )] + pub row_boundary_sets: BTreeMap, /// Written as a mapping from each function id to the rest of the function /// (CFG-ID-5) and held sorted by id. #[serde( @@ -2698,6 +2907,12 @@ impl ActionSource { pub fn is_proposal(&self) -> bool { matches!(self.execution, ActionExecutionSource::Proposal { .. }) } + pub fn concurrency(&self) -> ActionConcurrency { + match &self.execution { + ActionExecutionSource::Immediate { concurrency } => *concurrency, + ActionExecutionSource::Proposal { .. } => ActionConcurrency::ConditionRequired, + } + } } pub const ACTION_PLAN_ABI_V1: &str = "registry.action-plan/v1"; @@ -2792,6 +3007,21 @@ pub struct ActionRequirementSource { )] #[cfg_attr(feature = "schema", schemars(with = "Option"))] pub reason: Option, + /// Authored refusal text, a constant of at most 256 bytes that requires + /// `reason`. It is returned as the Problem `detail` and as the availability + /// `guardLabel` exactly where `reason` is returned, so it is disclosed only + /// when every guard and boundary fact is readable. It never replaces the + /// generic precondition refusal. + #[serde( + default, + deserialize_with = "registry_platform_yaml::optional_display_text", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr( + feature = "schema", + schemars(with = "Option") + )] + pub label: Option, #[serde(default)] pub field: String, #[serde( @@ -2827,6 +3057,14 @@ pub struct ActionRequirementSource { #[serde(default, skip_serializing_if = "crate::model::is_zero_i32")] #[cfg_attr(feature = "schema", schemars(range(min = -365000, max = 365000)))] pub current_date_offset_days: i32, + /// Whole calendar months added to the registry-local date before applying + /// `currentDate`, clamping to the last day of a shorter month (January 31 + /// plus one month is February 28 or 29). Requires `currentDate`, is + /// exclusive with `currentDateOffsetDays`, and zero preserves the + /// unshifted comparison. + #[serde(default, skip_serializing_if = "crate::model::is_zero_i32")] + #[cfg_attr(feature = "schema", schemars(range(min = -12000, max = 12000)))] + pub current_date_offset_months: i32, /// Requires the stored value to be at or above the named required action /// input of the same date, instant, or integer type. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5320,7 +5558,7 @@ pub enum BoundaryOperator { #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct HookSource { - /// Stable hook contract identifier, sent as `ce-type`. Use a new identifier for a breaking payload change. + /// Stable hook contract identifier, sent as the envelope `type`. Use a new identifier for a breaking payload change. #[serde(deserialize_with = "local_id")] #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub id: String, @@ -6398,21 +6636,42 @@ fn read_with_value_types( if !option_errors.is_empty() { return Err(document.report_with(option_errors)); } - if value.get("valueTypes").is_none() { - return document.decode().map(|value| Decoded { value, document }); + let has_value_types = value.get("valueTypes").is_some(); + let has_row_boundary_sets = value.get("rowBoundarySets").is_some(); + // Validate declarations at their authored sites before copying them into + // use sites. A bad named set or type must point to its declaration. + if value.get("rowBoundarySets").is_some() { + let _: BTreeMap = document.decode_at("/rowBoundarySets")?; } - // Validate declarations at their authored sites before copying constraints - // into use sites. A bad named type must point to its declaration. - let _: BTreeMap = document.decode_at("/valueTypes")?; - resolve_local_value_types(&mut value).map_err(|(path, message)| { + let resolved_sets = resolve_row_boundary_sets(&mut value).map_err(|(path, message)| { Report::new(vec![document.diagnostic_at_value( Severity::Error, - "breg.value-type.reference-invalid", + "breg.row-boundary-set.reference-invalid", &path, message, - "Name a declared value type and keep its constraints at that declaration.", + "Declare the set under rowBoundarySets in this file and reference it by its identifier, with no other member.", )]) })?; + if !has_value_types && !resolved_sets && !has_row_boundary_sets { + return document.decode().map(|value| Decoded { value, document }); + } + // Every reference is expanded, so the read file holds the boundaries + // inline and no set: it serializes to source that reads back the same. + if let Some(root) = value.as_object_mut() { + root.remove("rowBoundarySets"); + } + if has_value_types { + let _: BTreeMap = document.decode_at("/valueTypes")?; + resolve_local_value_types(&mut value).map_err(|(path, message)| { + Report::new(vec![document.diagnostic_at_value( + Severity::Error, + "breg.value-type.reference-invalid", + &path, + message, + "Name a declared value type and keep its constraints at that declaration.", + )]) + })?; + } let normalized = serde_json::to_vec(&value).expect("normalized authoring value serializes"); match read_authored::(file, &normalized, format) { Ok(decoded) => Ok(Decoded { diff --git a/crates/registry-breg/src/contract/sentinel.rs b/crates/registry-breg/src/contract/sentinel.rs index e06f906f69..b984d78c60 100644 --- a/crates/registry-breg/src/contract/sentinel.rs +++ b/crates/registry-breg/src/contract/sentinel.rs @@ -15,7 +15,7 @@ use std::convert::Infallible; use std::marker::PhantomData; -use registry_platform_yaml::{shape_union, Invalid}; +use registry_platform_yaml::{shape_union, Invalid, LocalId}; use serde::{de::IgnoredAny, Deserialize, Deserializer, Serialize, Serializer}; use super::{ @@ -167,8 +167,20 @@ pub(super) enum RequiredScopes { shape_union!(RequiredScopes { scalar => Unrestricted, list => Listed }); -/// The rows a permission reaches: the keyword `unrestricted`, or a list of at -/// least one row boundary. +/// A reference to a named list of row boundaries the file declares under +/// `rowBoundarySets`. The reader expands a reference into the set's boundaries +/// before the typed model is decoded, so the compiler never holds one. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(super) struct RowBoundarySetReference { + /// The identifier of a set declared under `rowBoundarySets` in the same file. + #[allow(dead_code)] + row_boundary_set: LocalId, +} + +/// The rows a permission reaches: the keyword `unrestricted`, a list of at +/// least one row boundary, or a reference to a named list of them. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(untagged))] pub(super) enum RowBoundaries { @@ -176,9 +188,19 @@ pub(super) enum RowBoundaries { Unrestricted(Unrestricted), /// Reach the rows every listed boundary binds to the caller's claims. Listed(Listed, Rows>), + /// Reach the rows every boundary of a named set binds to the caller's claims. + // The reader expands the reference before decoding, so the typed model + // only refuses it and never reads the identifier. + Reference(#[allow(dead_code)] RowBoundarySetReference), } -shape_union!(RowBoundaries { scalar => Unrestricted, list => Listed }); +shape_union!(RowBoundaries { scalar => Unrestricted, list => Listed, mapping => Reference }); + +/// What an unexpanded reference means to the typed model: nothing it may +/// read. An empty list means every row, so a reference that reaches typed +/// decoding is refused and never read as one. +const UNRESOLVED_REFERENCE: &str = "a row boundary set reference that the reader expanded"; +const UNRESOLVED_REFERENCE_ACTION: &str = "Declare the set under rowBoundarySets in the same file and read the file through the project reader."; /// The OAuth clients a runtime accepts tokens from. #[cfg(feature = "runtime")] @@ -238,11 +260,16 @@ pub(super) fn serialize_required_scopes( } impl RowBoundaries { - /// The boundaries the compiler holds, where `unrestricted` is none. - fn into_boundaries(self) -> Vec { + /// The boundaries the compiler holds, where `unrestricted` is none. An + /// unexpanded reference is refused rather than read as none. + fn into_boundaries(self) -> Result, Invalid> { match self { - Self::Unrestricted(_) => Vec::new(), - Self::Listed(Listed(boundaries, _)) => boundaries, + Self::Unrestricted(_) => Ok(Vec::new()), + Self::Listed(Listed(boundaries, _)) => Ok(boundaries), + Self::Reference(_) => Err(Invalid::expected( + UNRESOLVED_REFERENCE, + UNRESOLVED_REFERENCE_ACTION, + )), } } } @@ -250,7 +277,9 @@ impl RowBoundaries { pub(super) fn row_boundaries<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - RowBoundaries::deserialize(deserializer).map(RowBoundaries::into_boundaries) + RowBoundaries::deserialize(deserializer)? + .into_boundaries() + .map_err(Invalid::into_error) } pub(super) fn serialize_row_boundaries( @@ -347,6 +376,37 @@ narrowing_member!( "Omit rowBoundaries when the entity demands no row boundary of its profiles; an access requirement only narrows what a profile may grant." ); +narrowing_member!( + RowBoundarySetRows, + RowBoundarySetRowsShapes, + row_boundary_set_rows, + Vec, + "a list of at least one row boundary", + "List the row boundaries the set holds. A set is a reusable list, so it is never empty and never unrestricted: write unrestricted on the grant that reaches every row." +); + +/// The schema of a record type's required row boundaries: a list of at least +/// one boundary, or a reference to a named set of them. +#[cfg(feature = "schema")] +struct RequirementRowBoundaries; + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RequirementRowBoundaries { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "RequirementRowBoundaries".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let listed = generator.subschema_for::, RequirementRows>>(); + let reference = generator.subschema_for::(); + schemars::json_schema!({"anyOf": [listed, reference]}) + } +} + // The authored form of `AccessRequirementsSource`. /// Compile-time requirements, not grants. Profiles must explicitly satisfy them. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -382,10 +442,7 @@ pub(super) struct AuthoredAccessRequirements { deserialize_with = "requirement_rows", skip_serializing_if = "Vec::is_empty" )] - #[cfg_attr( - feature = "schema", - schemars(with = "Listed, RequirementRows>") - )] + #[cfg_attr(feature = "schema", schemars(with = "RequirementRowBoundaries"))] row_boundaries: Vec, } @@ -750,7 +807,7 @@ impl TryFrom for EntityPermissionSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: row_boundaries.into_boundaries(), + row_boundaries: row_boundaries.into_boundaries()?, membership_boundaries: authored.membership_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, diff --git a/crates/registry-breg/src/correlation.rs b/crates/registry-breg/src/correlation.rs index 470e37782b..6a2ab004d4 100644 --- a/crates/registry-breg/src/correlation.rs +++ b/crates/registry-breg/src/correlation.rs @@ -9,6 +9,9 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE}; use axum::http::{HeaderMap, Request, StatusCode}; use axum::middleware::Next; use axum::response::Response; +use std::sync::{Arc, Mutex, PoisonError}; + +use registry_platform_authcommon::{record_refusal, DeclaredScope, FailedCheck, RefusalNote}; use registry_platform_httpsec::{Problem, ProblemBody, TraceContext, TraceId}; use serde_json::Value; use uuid::Uuid; @@ -22,14 +25,46 @@ use uuid::Uuid; pub struct RequestCorrelation { request_id: Uuid, trace: TraceContext, + declared_scope: DeclaredScopeSlot, +} + +/// The operator-declared values of the scope check a request failed. A scope +/// refusal fills it, the recording layer reads it, and nothing in it is +/// written to the response. Every clone of one request's correlation shares +/// the slot. +#[derive(Clone, Debug, Default)] +pub(crate) struct DeclaredScopeSlot(Arc>>); + +impl DeclaredScopeSlot { + pub(crate) fn set(&self, declared: DeclaredScope) { + *self.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(declared); + } + + fn get(&self) -> Option { + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } } +// The slot is bookkeeping for the recording layer, not part of a +// correlation's identity. +impl PartialEq for DeclaredScopeSlot { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for DeclaredScopeSlot {} + impl RequestCorrelation { #[must_use] pub fn from_headers(headers: &HeaderMap) -> Self { Self { request_id: Uuid::new_v4(), trace: TraceContext::from_headers(headers), + declared_scope: DeclaredScopeSlot::default(), } } @@ -38,6 +73,7 @@ impl RequestCorrelation { Self { request_id: Uuid::new_v4(), trace: TraceContext::server_created(), + declared_scope: DeclaredScopeSlot::default(), } } @@ -51,6 +87,10 @@ impl RequestCorrelation { &self.trace.trace_id } + pub(crate) fn declared_scope_slot(&self) -> DeclaredScopeSlot { + self.declared_scope.clone() + } + fn apply_trace(&self, headers: &mut HeaderMap) { self.trace.apply(headers); } @@ -75,6 +115,7 @@ pub(crate) struct PublicProblem { field_path: Option, declared_refusal: Option<(String, String)>, guard_reason: Option, + guard_label: Option, declared_field: Option<(String, String)>, declared_constraint: Option>, timer_window_fields: Option<(String, String)>, @@ -104,6 +145,7 @@ pub(crate) fn problem_response( field_path: None, declared_refusal: None, guard_reason: None, + guard_label: None, declared_field: None, declared_constraint: None, timer_window_fields: None, @@ -118,6 +160,15 @@ pub(crate) fn problem_response( response } +/// Name the check a refusal failed. The member rides in the response +/// extensions to [`finish_response`], which counts it and writes the one +/// bounded log line. It is never serialized, so the answer's bytes do not +/// change. +pub(crate) fn note_refusal(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + /// Build one public problem with a safe action field path. /// /// The field path is produced only from fixed envelope members or compiled @@ -140,6 +191,7 @@ pub(crate) fn problem_response_with_field_path( field_path: Some(field_path.clone()), declared_refusal: None, guard_reason: None, + guard_label: None, declared_field: None, declared_constraint: None, timer_window_fields: None, @@ -194,8 +246,12 @@ pub(crate) fn action_refusal_response( response } -/// Called only after the ordinary guard and boundary disclosure recheck. -pub(crate) fn action_guard_failure_response(reason: Option) -> Response { +/// Called only after the ordinary guard and boundary disclosure recheck. The +/// authored label, when the guard has one, replaces the generic `detail`. +pub(crate) fn action_guard_failure_response( + reason: Option, + label: Option, +) -> Response { let code = crate::problem::ProblemCode::ActionGuardFailed; let mut response = problem_response( StatusCode::PRECONDITION_FAILED, @@ -203,11 +259,12 @@ pub(crate) fn action_guard_failure_response(reason: Option) -> Response code.description(), code.code(), ); - response + let problem = response .extensions_mut() .get_mut::() - .expect("problem metadata") - .guard_reason = reason; + .expect("problem metadata"); + problem.guard_reason = reason; + problem.guard_label = label; response } @@ -359,6 +416,11 @@ pub(crate) fn finish_response( } if let Some(reason) = &problem.guard_reason { object.insert("guardReason".to_owned(), Value::String(reason.clone())); + // A label is authored beside its reason, so it rides only where the + // reason does. + if let Some(label) = &problem.guard_label { + object.insert("detail".to_owned(), Value::String(label.clone())); + } } if let Some((name, value)) = problem.statistical_detail { object.insert(name.to_owned(), Value::String(value.to_owned())); @@ -435,6 +497,18 @@ pub(crate) fn finish_response( ); } correlation.apply_trace(response.headers_mut()); + if let Some(problem) = &problem { + if matches!(problem.status.as_u16(), 401 | 403) + && response.extensions().get::().is_none() + { + debug_assert!(false, "a refusal was answered without its failed check"); + tracing::error!( + code = problem.code, + "a refusal was answered without its failed check" + ); + } + } + record_noted_refusal(&response, correlation); let status = status_class(response.status()); let problem_code = problem.as_ref().map_or("none", |problem| problem.code); @@ -451,6 +525,21 @@ pub(crate) fn finish_response( response } +/// Count and log the refusal a response carries, if any. A handler that folds +/// several refused items into one answer calls this for each item, because the +/// folded answer is not itself a refusal. +pub(crate) fn record_noted_refusal(response: &Response, correlation: &RequestCorrelation) { + if let Some(note) = response.extensions().get::().copied() { + let declared = correlation.declared_scope.get(); + record_refusal!( + crate::metrics::process_refusal_recorder(), + note, + trace_id = correlation.trace_id(), + declared = declared.as_ref() + ); + } +} + pub(crate) fn method_name(method: &axum::http::Method) -> &'static str { match *method { axum::http::Method::GET => "GET", @@ -476,3 +565,95 @@ pub(crate) fn status_class(status: StatusCode) -> &'static str { fn duration_milliseconds(elapsed: std::time::Duration) -> u64 { u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) } + +#[cfg(test)] +mod refusal_guard_tests { + use super::*; + + fn refusal_statuses() -> [StatusCode; 2] { + [ + StatusCode::from_u16(401).expect("401 is a status"), + StatusCode::FORBIDDEN, + ] + } + + fn finish(response: Response) -> Response { + let correlation = RequestCorrelation::from_headers(&HeaderMap::new()); + finish_response(response, &correlation, "GET", Instant::now()) + } + + #[test] + fn a_401_or_403_with_its_check_is_answered_unchanged() { + for status in refusal_statuses() { + let response = note_refusal( + problem_response(status, "Refused", "Refused.", "authentication.refused"), + FailedCheck::CredentialMissing, + ); + assert_eq!(finish(response).status(), status); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_401_or_403_without_a_check_stops_a_debug_build() { + for status in refusal_statuses() { + let outcome = std::panic::catch_unwind(|| { + finish(problem_response( + status, + "Refused", + "Refused.", + "authentication.refused", + )) + }); + assert!(outcome.is_err(), "{status} was answered without a check"); + } + } + + #[test] + fn a_404_without_a_check_is_an_unknown_route() { + let response = finish(problem_response( + StatusCode::NOT_FOUND, + "Not Found", + "The requested resource was not found.", + "resource.not_found", + )); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + + async fn body_of(response: Response) -> Value { + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("the problem body reads"); + serde_json::from_slice(&bytes).expect("the problem body is JSON") + } + + #[tokio::test] + async fn a_guard_label_replaces_the_detail_only_beside_its_reason() { + let label = "Only a submitted application can be approved."; + let labelled = body_of(finish(note_refusal( + action_guard_failure_response(Some("not-submitted".into()), Some(label.into())), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(labelled["code"], "action.guard_failed"); + assert_eq!(labelled["guardReason"], "not-submitted"); + assert_eq!(labelled["detail"], label); + + let plain = body_of(finish(note_refusal( + action_guard_failure_response(Some("not-submitted".into()), None), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(plain["detail"], "The action guard was not satisfied."); + + // A label never rides without the reason it is authored beside. + let orphan = body_of(finish(note_refusal( + action_guard_failure_response(None, Some(label.into())), + FailedCheck::ActionGuard, + ))) + .await; + assert_eq!(orphan["detail"], "The action guard was not satisfied."); + assert!(orphan.get("guardReason").is_none()); + assert!(!orphan.to_string().contains(label)); + } +} diff --git a/crates/registry-breg/src/event_destination.rs b/crates/registry-breg/src/event_destination.rs index 979bcb9b58..2f66cae3c2 100644 --- a/crates/registry-breg/src/event_destination.rs +++ b/crates/registry-breg/src/event_destination.rs @@ -11,7 +11,10 @@ use std::{ use ipnet::IpNet; use registry_platform_canonical_json::canonicalize_json; use registry_platform_config::{ProtectedSecret, SecretError, SecretReference, SecretResolver}; -use registry_platform_hooks::delivery::{UrlDestination, UrlDestinationError, UrlDestinationParts}; +use registry_platform_crypto::delivery_signature::{ + distinct_delivery_keys, DeliveryKey, DeliveryKeyError, DeliveryKeys, +}; +use registry_platform_hooks::delivery::{UrlDestination, UrlDestinationParts}; use registry_platform_httputil::destination::{ DestinationDnsFamily, DestinationProfile, DestinationTlsMaterial, EventDestinationPolicy, EventDestinationRequestTemplate, MAX_DESTINATION_PRIVATE_CIDRS, @@ -40,7 +43,7 @@ const MAX_EVENT_REQUEST_BYTES: usize = MAX_DESTINATION_TARGET_BYTES const _: () = assert!(MAX_HOOK_PAYLOAD_BYTES as usize == MAX_DESTINATION_REQUEST_BODY_BYTES); /// Value-free refusal while activating deployed event destinations. -#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)] +#[derive(Clone, Debug, Eq, Error, PartialEq)] pub enum EventDestinationActivationError { #[error("event destination activation found an invalid deployment binding")] InvalidBinding, @@ -50,12 +53,107 @@ pub enum EventDestinationActivationError { DeliveryCeilingWidening, #[error("event destination secret resolution failed")] Secret, - #[error("event destination signing material is invalid")] - InvalidSigningMaterial, + #[error("{path} could not be resolved: {reason}. {action}")] + SigningKeyUnavailable { + path: String, + reason: String, + action: &'static str, + }, + #[error("{path} has {length} bytes (trailing newline: {trailing_newline}). {}", signing_key_action(.reason))] + InvalidSigningKey { + path: String, + length: usize, + trailing_newline: bool, + reason: DeliveryKeyError, + }, + #[error("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there.")] + RepeatedSigningKey { first: String, second: String }, + #[error("{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}.")] + PreviousEqualsCurrent { current: String, previous: String }, #[error("event destination TLS material is invalid")] InvalidTlsMaterial, } +pub(crate) const CURRENT_KEY_MEMBER: &str = "hmacSha256KeyRef"; +pub(crate) const PREVIOUS_KEY_MEMBER: &str = "previousHmacSha256KeyRef"; + +pub(crate) fn present_hook_key_reference<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + SecretReference::deserialize(deserializer).map(Some) +} + +pub(crate) fn signing_key_action(reason: &DeliveryKeyError) -> &'static str { + match reason { + DeliveryKeyError::TooShort { .. } | DeliveryKeyError::TooLong { .. } => { + "Supply 32 to 64 exact key bytes." + } + DeliveryKeyError::SecretText => "Supply the exact key bytes without the whsec_ encoding.", + DeliveryKeyError::PreviousEqualsCurrent => unreachable!("key equality has both paths"), + } +} + +fn resolve_delivery_key( + secrets: &SecretResolver, + path: &str, + reference: &SecretReference, +) -> Result { + let secret = secrets + .resolve_binary_reference(reference) + .map_err( + |error| EventDestinationActivationError::SigningKeyUnavailable { + path: path.to_owned(), + reason: error.to_string(), + action: error.suggested_action(), + }, + )?; + let bytes = secret.expose_secret(); + let length = bytes.len(); + let trailing_newline = bytes.ends_with(b"\n"); + let key = DeliveryKey::new(bytes).map_err(|reason| { + EventDestinationActivationError::InvalidSigningKey { + path: path.to_owned(), + length, + trailing_newline, + reason, + } + })?; + Ok(key) +} + +pub(crate) fn resolve_delivery_keys( + secrets: &SecretResolver, + block: &str, + current: &SecretReference, + previous: Option<&SecretReference>, +) -> Result { + let current = resolve_delivery_key(secrets, &format!("{block}.{CURRENT_KEY_MEMBER}"), current)?; + let Some(previous) = previous else { + return Ok(DeliveryKeys::new(current, None).expect("one validated key")); + }; + let path = format!("{block}.{PREVIOUS_KEY_MEMBER}"); + let previous = resolve_delivery_key(secrets, &path, previous)?; + DeliveryKeys::new(current, Some(previous)).map_err(|_| { + EventDestinationActivationError::PreviousEqualsCurrent { + current: format!("{block}.{CURRENT_KEY_MEMBER}"), + previous: path, + } + }) +} + +pub(crate) fn labeled_delivery_keys<'a>( + block: &str, + keys: &'a DeliveryKeys, +) -> impl Iterator + use<'a> { + std::iter::once((format!("{block}.{CURRENT_KEY_MEMBER}"), keys.current())).chain( + keys.previous() + .map(|key| (format!("{block}.{PREVIOUS_KEY_MEMBER}"), key)), + ) +} + impl From for EventDestinationActivationError { fn from(_error: SecretError) -> Self { Self::Secret @@ -114,6 +212,7 @@ impl ActivatedEventDestinationRegistry { compiled: &CompiledRegistry, configured: &EventDestinationConfigs, secrets: &SecretResolver, + other_keys: Vec<(String, &DeliveryKey)>, ) -> Result { let compiled_ids = compiled .event_deliveries() @@ -126,6 +225,33 @@ impl ActivatedEventDestinationRegistry { return Err(EventDestinationActivationError::InventoryMismatch); } + let mut keys = configured + .bindings + .iter() + .map(|(id, config)| { + let block = format!("destinations.hooks.{id}"); + resolve_delivery_keys( + secrets, + &block, + &config.hmac_sha256_key_ref, + config.previous_hmac_sha256_key_ref.as_ref(), + ) + .map(|keys| (id, keys)) + }) + .collect::>>()?; + let labeled_keys = keys + .iter() + .flat_map(|(id, keys)| labeled_delivery_keys(&format!("destinations.hooks.{id}"), keys)) + .chain(other_keys) + .collect::>(); + distinct_delivery_keys(labeled_keys.iter().map(|(path, key)| (path.as_str(), *key))) + .map_err( + |error| EventDestinationActivationError::RepeatedSigningKey { + first: error.first().to_owned(), + second: error.second().to_owned(), + }, + )?; + let mut bindings = BTreeMap::new(); for (logical_id, config) in &configured.bindings { let deliveries = compiled @@ -149,7 +275,11 @@ impl ActivatedEventDestinationRegistry { .map(|delivery| delivery.maximum_payload_bytes) .max() .ok_or(EventDestinationActivationError::InventoryMismatch)?; - let activated = config.activate(logical_id, maximum_payload_bytes, secrets)?; + let resolved_keys = keys + .remove(logical_id) + .expect("one resolved key set per destination"); + let activated = + config.activate(logical_id, maximum_payload_bytes, secrets, resolved_keys)?; if bindings .insert(logical_id.clone(), Arc::new(activated)) .is_some() @@ -276,6 +406,7 @@ struct EventDestinationConfig { dns_family: EventDestinationDnsFamily, allowed_private_cidrs: Vec, hmac_sha256_key_ref: SecretReference, + previous_hmac_sha256_key_ref: Option, classification_ceiling: Classification, tls: Option, delivery_ceilings: EventDestinationDeliveryCeilings, @@ -297,6 +428,7 @@ impl EventDestinationConfig { dns_family: raw.dns_family, allowed_private_cidrs, hmac_sha256_key_ref, + previous_hmac_sha256_key_ref: raw.previous_hmac_sha256_key_ref, classification_ceiling: raw.classification_ceiling, tls, delivery_ceilings, @@ -314,7 +446,7 @@ impl EventDestinationConfig { self.dns_family.platform(), ) .map_err(|_| EventDestinationConfigError)?; - EventDestinationRequestTemplate::event_delivery( + EventDestinationRequestTemplate::signed_event_delivery( &self.path, MAX_DESTINATION_REQUEST_BODY_BYTES, MAX_EVENT_REQUEST_BYTES, @@ -328,9 +460,8 @@ impl EventDestinationConfig { logical_id: &str, maximum_payload_bytes: u32, secrets: &SecretResolver, + keys: DeliveryKeys, ) -> Result { - let hmac_sha256_key = secrets.resolve_reference(&self.hmac_sha256_key_ref)?; - let mut policy = EventDestinationPolicy::new_with_dns_family( logical_id, &self.origin, @@ -368,18 +499,13 @@ impl EventDestinationConfig { request_target: self.path.clone(), policy, maximum_payload_bytes, - hmac_sha256_key, + keys, attempt_timeout: Duration::from_millis(u64::from( self.delivery_ceilings.attempt_timeout_milliseconds, )), maximum_attempts: self.delivery_ceilings.maximum_attempts, }) - .map_err(|error| match error { - UrlDestinationError::InvalidBinding => EventDestinationActivationError::InvalidBinding, - UrlDestinationError::InvalidSigningMaterial => { - EventDestinationActivationError::InvalidSigningMaterial - } - }) + .map_err(|_| EventDestinationActivationError::InvalidBinding) } fn digest_value(&self, logical_id: &str) -> Value { @@ -464,7 +590,7 @@ impl EventDestinationNetworkProfile { fn platform(self) -> DestinationProfile { match self { Self::ProductionHttps => DestinationProfile::ProductionHttps, - Self::LoopbackDevelopmentHttp => DestinationProfile::LoopbackDevelopmentHttp, + Self::LoopbackDevelopmentHttp => DestinationProfile::LoopbackHttp, #[cfg(feature = "postgres-test")] Self::PinnedLoopbackHttpsTest => DestinationProfile::PinnedLoopbackHttpsTest, } @@ -531,8 +657,16 @@ pub(crate) struct RawEventDestinationConfig { dns_family: EventDestinationDnsFamily, /// Explicitly allowed private network ranges in canonical CIDR notation. allowed_private_cidrs: Vec, - /// Runtime secret reference for the receiver's shared HMAC-SHA-256 key. + /// Runtime secret reference for the receiver's 32 to 64 exact HMAC-SHA-256 key bytes. hmac_sha256_key_ref: SecretReference, + /// Optional previous signing key during rotation. + #[serde( + default, + deserialize_with = "present_hook_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + previous_hmac_sha256_key_ref: Option, /// Highest permitted classification, including fields used only in event conditions. classification_ceiling: Classification, /// Optional private CA and client identity secret references for HTTPS. diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index 69227224e2..732869bf67 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -62,7 +62,7 @@ use crate::postgres::{ PostgresRecordMutationService, PostgresRecordReadService, PostgresRevisionReadService, PreparedSchemaTestCatalogVerifier, PreparedSchemaTestDatabase, RuntimePool, }; -use crate::runtime_config::RuntimeConfig; +use crate::runtime_config::{RuntimeConfig, RuntimeConfigError}; #[cfg(feature = "postgres-test")] use crate::startup::PreparedServer; @@ -153,6 +153,7 @@ pub enum SchemaTestRuntimeSetupError { EventDestinations(EventDestinationActivationError), Evidence, ReviewAuthorities, + ReviewAuthorityKey(String), WasmExecution, } @@ -169,6 +170,7 @@ impl fmt::Display for SchemaTestRuntimeSetupError { Self::ReviewAuthorities => { formatter.write_str("schema-test review authority activation failed") } + Self::ReviewAuthorityKey(message) => formatter.write_str(message), Self::WasmExecution => formatter.write_str("schema-test WASM execution setup failed"), } } @@ -1106,6 +1108,9 @@ struct ValidatedStep { #[derive(Clone, Default)] struct FixtureProblemBindings { refusal_label: Option, + /// The `(reason, label)` pairs of the Action's guards, so a refusal may + /// carry a guard's authored label as its `detail`. + guard_labels: BTreeSet<(String, String)>, refusal_field_paths: BTreeSet, request_field_paths: BTreeSet, /// A record step's refusal may name one closed record location instead @@ -3034,6 +3039,15 @@ fn compile_problem_bindings( } } } + if expectation.problem_code.as_deref() == Some("action.guard_failed") { + if let Some(action) = action { + bindings.guard_labels = action + .requires + .iter() + .filter_map(|guard| Some((guard.reason.clone()?, guard.label.clone()?))) + .collect(); + } + } if matches!( expectation.problem_code.as_deref(), Some("action.refused" | "action.handler_failed" | "action.evidence_failed") @@ -3782,11 +3796,33 @@ impl SchemaTestRuntime { .cursor_codec() .map_err(|_| FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::Cursor))?, ); - let event_destinations = Arc::new(config.activate_event_destinations(®istry).map_err( - |error| { - FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::EventDestinations(error)) - }, - )?); + // A reviewed submission records its pending authority delivery in the + // same transaction, so the rehearsal activates the operator's review + // authority bindings exactly as the server does. No review worker runs + // here: the rehearsal never contacts the authority. + let review_authorities = + config + .activate_review_authorities(®istry) + .map_err(|error| { + FixtureError::RuntimeSetup(match error { + RuntimeConfigError::InvalidDeliveryKey { .. } => { + SchemaTestRuntimeSetupError::ReviewAuthorityKey(error.to_string()) + } + _ => SchemaTestRuntimeSetupError::ReviewAuthorities, + }) + })?; + let event_destinations = Arc::new( + config + .activate_event_destinations_with_review_authorities( + ®istry, + review_authorities.as_deref(), + ) + .map_err(|error| { + FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::EventDestinations( + error, + )) + })?, + ); let authenticator = Arc::new( RegistryAuthenticator::new( ®istry, @@ -3847,13 +3883,6 @@ impl SchemaTestRuntime { let evidence = config .activate_evidence(®istry) .map_err(|_| FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::Evidence))?; - // A reviewed submission records its pending authority delivery in the - // same transaction, so the rehearsal activates the operator's review - // authority bindings exactly as the server does. No review worker runs - // here: the rehearsal never contacts the authority. - let review_authorities = config.activate_review_authorities(®istry).map_err(|_| { - FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::ReviewAuthorities) - })?; #[cfg(feature = "wasm")] let wasm_runtime = crate::wasm_runtime::install_configured(*config.wasm_execution()) .map_err(|_| FixtureError::RuntimeSetup(SchemaTestRuntimeSetupError::WasmExecution))?; @@ -4723,14 +4752,22 @@ fn assert_response_with_observations( ) } else if code == "action.guard_failed" && document.get("guardReason").is_some() { keys.push("guardReason"); - if document + let Some(reason) = document .get("guardReason") .and_then(Value::as_str) - .is_none_or(|reason| registry_platform_yaml::LocalId::new(reason).is_err()) - { + .filter(|reason| registry_platform_yaml::LocalId::new(*reason).is_ok()) + else { return Err(FixtureError::ResponseShapeRefused); - } - None + }; + // A guard that authors a label answers with it as the detail. + document + .get("detail") + .and_then(Value::as_str) + .filter(|detail| { + step.problem_bindings + .guard_labels + .contains(&(reason.to_owned(), (*detail).to_owned())) + }) } else if let Some((entity, field)) = &step.problem_bindings.pattern_field { keys.extend(["recordType", "fieldId"]); if document.get("recordType").and_then(Value::as_str) != Some(entity.as_str()) @@ -6386,7 +6423,7 @@ mod tests { }; #[test] - fn fixture_authentication_diagnostics_distinguish_missing_claim_from_refused_credential() { + fn fixture_refusals_distinguish_missing_claim_from_refused_credential() { assert_eq!( fixture_authentication_error(crate::auth::AuthenticationError::MissingActorKind), FixtureError::AuthenticationActorKindMissing @@ -8615,6 +8652,59 @@ journeys: .expect("constraint journeys validate") } + #[test] + fn guard_failed_problem_accepts_a_bound_guard_label_as_its_detail() { + let suite = row_local_constraint_suite( + "jurisdiction, label, note, quantity, valid-from, valid-to", + "validFrom: 2, validTo: 1", + ); + let label = "Only an active parent takes a child."; + let mut guard_step = suite.journeys[0].steps[0].clone(); + guard_step.expect.status = 412; + guard_step.expect.problem_code = Some("action.guard_failed".to_owned()); + guard_step + .problem_bindings + .guard_labels + .insert(("parent-inactive".to_owned(), label.to_owned())); + let problem = |reason: &str, detail: &str| { + json!({ + "type": crate::problem::type_uri("action.guard_failed"), + "title": "Precondition Failed", + "status": 412, + "detail": detail, + "code": "action.guard_failed", + "traceId": "11111111111111111111111111111111", + "guardReason": reason + }) + }; + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem("parent-inactive", label), + ) + .expect("a bound label is the detail of the refusal that names its reason"); + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem("parent-inactive", "The action guard was not satisfied."), + ) + .expect("the generic detail stays admitted"); + for (reason, detail) in [ + ("other-reason", label), + ("parent-inactive", "Some other text."), + ] { + assert!( + assert_response( + &guard_step, + StatusCode::PRECONDITION_FAILED, + &problem(reason, detail), + ) + .is_err(), + "a detail that is no bound label for its reason is refused" + ); + } + } + #[test] fn guard_failed_problem_accepts_only_a_local_id_guard_reason() { let suite = row_local_constraint_suite( diff --git a/crates/registry-breg/src/generated_ddl.rs b/crates/registry-breg/src/generated_ddl.rs index 40efe47493..f1b5ac18c3 100644 --- a/crates/registry-breg/src/generated_ddl.rs +++ b/crates/registry-breg/src/generated_ddl.rs @@ -27,7 +27,8 @@ use crate::physical_names::{ const RECORD_ID_COLUMN: &str = "record_id"; const GENERATED_TEXT_COLLATION: &str = "pg_catalog.pg_c_utf8"; pub(crate) const REFERENCE_LIFECYCLE_COLUMN: &str = "record_reference_lifecycle"; -pub(crate) const POSTGIS_EXTENSION_SCHEMA: &str = "registry_spatial_ext"; +/// The schema the generated spatial SQL reads PostGIS from. +pub const POSTGIS_EXTENSION_SCHEMA: &str = "registry_spatial_ext"; pub(crate) const SPATIAL_BBOX_FUNCTION_NAME: &str = "spatial_bbox_geometry"; pub(crate) const SPATIAL_POLYGON_CONTRACT_FUNCTION_NAME: &str = "valid_crs84_polygon"; const SPATIAL_POLYGON_CONTRACT_ARGUMENTS: &str = diff --git a/crates/registry-breg/src/hooks.rs b/crates/registry-breg/src/hooks.rs index 9699a5c749..35167d81d5 100644 --- a/crates/registry-breg/src/hooks.rs +++ b/crates/registry-breg/src/hooks.rs @@ -10,9 +10,7 @@ //! operational vocabulary, the activated destinations, the local programs the //! running package holds, and proposal application with its completion //! barrier. The signed bytes on the wire are produced by the shared URL -//! destination from the same field values and key material, and the -//! idempotency domain and delivery source identity are passed through -//! unchanged. +//! destination from the event identity, timestamp, exact body and key material. use std::path::Path; #[cfg(feature = "postgres-test")] @@ -55,7 +53,6 @@ pub use registry_platform_hooks::delivery::{ MAX_DELIVERY_STATUS_RESULTS as MAX_HOOK_STATUS_RESULTS, }; -const IDEMPOTENCY_DOMAIN: &[u8] = b"breg-webhook-idempotency-v1"; /// The schema Base Registry Engine installs the platform delivery tables /// into, and the one the worker and the capture INSERT read and write. pub(crate) const DELIVERY_SCHEMA: &str = "registry_internal"; @@ -157,6 +154,8 @@ pub enum HookOperatorError { /// not secrets, so the refusal names them. #[error("{0}")] PackagePinMismatch(registry_platform_config::blocks::PackageDigestMismatch), + #[error("{0}")] + EventDestinations(crate::event_destination::EventDestinationActivationError), #[error("hook operator request is unavailable")] Unavailable, } @@ -203,6 +202,11 @@ impl HookOperatorService { } _ => HookOperatorError::Unavailable, })?; + let destinations = Arc::new( + config + .activate_event_destinations(package.registry()) + .map_err(HookOperatorError::EventDestinations)?, + ); let connection = config .runtime_database_connection_config() .map_err(|_| HookOperatorError::Unavailable)?; @@ -223,11 +227,6 @@ impl HookOperatorService { .await .map_err(|_| HookOperatorError::Unavailable)?; drop(client); - let destinations = Arc::new( - config - .activate_event_destinations(startup.package().registry()) - .map_err(|_| HookOperatorError::Unavailable)?, - ); let audit = RegistryAudit::open_companion(&config) .await .map_err(|_| HookOperatorError::Unavailable)?; @@ -1011,7 +1010,6 @@ impl HookDeliveryService { ) -> Self { let config = DeliveryConfig { schema: DELIVERY_SCHEMA.to_owned(), - idempotency_domain: IDEMPOTENCY_DOMAIN.to_vec(), delivery_source: delivery_source(&expected.package_id, instance_id), }; let last_success = Arc::::default(); diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index fa628b7e3b..6e02a461c6 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -24,6 +24,9 @@ use crate::model::{ }; use crate::plan::{MAX_PLAN_FIELD_MUTATIONS, MAX_PLAN_SNAPSHOT_BYTES, MAX_PLAN_TARGETS}; +/// The longest authored guard label, matching the longest Function refusal label. +const MAXIMUM_GUARD_LABEL_BYTES: usize = 256; + type CompiledEffectSet = ( Vec, Vec, @@ -321,6 +324,15 @@ fn compile_action( } } let requires = compile_requirements(action, &input_map, entities, &target_uses, errors); + let concurrency = action.concurrency(); + if concurrency == crate::contract::ActionConcurrency::CurrentRevision { + validate_current_revision(action, &requires, &effects, handler.is_some(), errors); + // The caller proves no revision: the guards run against the locked + // current row instead, so no target use asks for a condition. + for use_ in &mut target_uses { + use_.condition_required = false; + } + } let attachments = compile_action_attachments(action, &inputs, entities, timer_actions, errors); let writes_path = if handler.is_some() { "actions[].plan.writes" @@ -378,6 +390,7 @@ fn compile_action( display: action.display.display(), grouping: action.display.grouping(), execution, + concurrency, definition_revision: String::new(), evidence: Vec::new(), commit_evidence, @@ -1083,6 +1096,25 @@ fn compile_requirements( if let Some(reason) = &requirement.reason { validate_id(reason, "actions[].commitGuards.targets[].reason", errors); } + if let Some(label) = &requirement.label { + if requirement.reason.is_none() { + errors.push(Diagnostic::error( + "breg.action.commit_guards.label-requires-reason", + "actions[].commitGuards.targets[].label", + "a guard label is the text of the refusal that names the guard's reason, so it requires a reason", + )); + } + if label.trim().is_empty() + || label.len() > MAXIMUM_GUARD_LABEL_BYTES + || label.chars().any(char::is_control) + { + errors.push(Diagnostic::error( + "breg.action.commit_guards.label-invalid", + "actions[].commitGuards.targets[].label", + "a guard label must be non-empty display text of at most 256 bytes without control characters", + )); + } + } if !seen.insert((&requirement.input, &requirement.field)) { errors.push(Diagnostic::error( "breg.action.commit_guards.targets-duplicate", @@ -1127,6 +1159,7 @@ fn compile_requirements( }); if !revision_is_bound || requirement.reason.is_some() + || requirement.label.is_some() || !requirement.field.is_empty() || requirement.equals.is_some() || requirement.equals_input.is_some() @@ -1135,6 +1168,7 @@ fn compile_requirements( || requirement.at_most.is_some() || requirement.current_date.is_some() || requirement.current_date_offset_days != 0 + || requirement.current_date_offset_months != 0 || requirement.at_least_from_input.is_some() || requirement.at_most_from_input.is_some() { @@ -1155,7 +1189,9 @@ fn compile_requirements( at_least: None, at_most: None, current_date: None, + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }); @@ -1200,6 +1236,18 @@ fn compile_requirements( )); continue; } + if requirement.current_date_offset_months != 0 + && (requirement.current_date.is_none() + || requirement.current_date_offset_days != 0 + || !(-12_000..=12_000).contains(&requirement.current_date_offset_months)) + { + errors.push(Diagnostic::error( + "breg.action.commit_guards.current-date-offset-invalid", + "actions[].commitGuards.targets[].currentDateOffsetMonths", + "currentDateOffsetMonths requires currentDate, cannot be combined with currentDateOffsetDays, and must be from -12000 through 12000 whole months", + )); + continue; + } let literal = requirement.literal(); let literal_invalid = literal.as_ref().is_some_and(|equals| { equals.is_array() @@ -1276,7 +1324,9 @@ fn compile_requirements( crate::model::CompiledCurrentDateRelation::OnOrBefore } }), + label: requirement.label.clone(), current_date_offset_days: requirement.current_date_offset_days, + current_date_offset_months: requirement.current_date_offset_months, at_least_input: requirement.at_least_from_input.clone(), at_most_input: requirement.at_most_from_input.clone(), }); @@ -1285,6 +1335,94 @@ fn compile_requirements( compiled } +/// The rules that make a write without a caller condition safe. A guard is +/// evaluated against the locked current row, so a second, stale write fails +/// exactly when the first write falsified a guard. Every record the Action +/// patches therefore needs a guard its own write makes false, and the write +/// may carry no value the caller chose, because a caller value read from a +/// stale view would silently overwrite a concurrent update. +fn validate_current_revision( + action: &ActionSource, + requires: &[CompiledCommitGuard], + effects: &[CompiledPlanEffect], + function_plan: bool, + errors: &mut Vec, +) { + if requires.iter().any(|guard| guard.revision_unchanged) { + errors.push(Diagnostic::error( + "breg.action.concurrency-revision-guard", + "actions[].commitGuards.targets[].revision", + &format!( + "Action `{}` uses concurrency: current-revision, which sends no condition, so it cannot require revision: unchanged", + action.id + ), + )); + } + // Final value each patched record's fields take, keyed by reference input. + let mut patched = BTreeMap::<&str, BTreeMap<&str, Option<&serde_json::Value>>>::new(); + for effect in effects { + let CompiledPlanTargetBinding::Existing { input } = &effect.target.binding else { + continue; + }; + if function_plan { + errors.push(Diagnostic::error( + "breg.action.concurrency-caller-value", + "actions[].plan", + &format!( + "Action `{}` uses concurrency: current-revision, and a function plan writes values computed from the caller's inputs into an existing record", + action.id + ), + )); + continue; + } + let fields = patched.entry(input.as_str()).or_default(); + for mutation in &effect.mutations { + match mutation { + CompiledPlanMutation::Set { + field, + value: CompiledPlanValue::Literal { value }, + } => { + fields.insert(field.as_str(), Some(value)); + } + CompiledPlanMutation::Clear { field } => { + fields.insert(field.as_str(), None); + } + CompiledPlanMutation::Set { field, .. } => errors.push(Diagnostic::error( + "breg.action.concurrency-caller-value", + "actions[].plan.effects[].set", + &format!( + "effect `{}` sets field `{field}` of an existing record from a caller value, which concurrency: current-revision does not allow. Set a constant with `value`, or use the default concurrency", + effect.id + ), + )), + } + } + } + for (input, fields) in patched { + let falsified = requires.iter().any(|guard| { + guard.input == input + && guard.equals_input.is_none() + && guard.equals.as_ref().is_some_and(|expected| { + match fields.get(guard.field.as_str()) { + Some(Some(value)) => *value != expected, + Some(None) => !expected.is_null(), + None => false, + } + }) + }); + if !falsified { + errors.push(Diagnostic::error( + "breg.action.concurrency-guard-missing", + "actions[].commitGuards.targets", + &format!( + "Action `{}` uses concurrency: current-revision and patches the record of input `{input}`, so it needs an `equals` or `isNull` guard on that input that its own write makes false", + action.id + ), + )); + } + } +} + fn compile_inputs( action: &ActionSource, entities: &BTreeMap, @@ -3338,6 +3476,9 @@ pub fn migration_review_revision(action: &CompiledAction) -> String { label.clear(); } } + for guard in &mut action.requires { + guard.label = None; + } if let crate::model::CompiledActionExecution::Proposal { proposal } = &mut action.execution { proposal .permissions @@ -3611,7 +3752,13 @@ pub(crate) fn definition_revision( Some((id,json!({"fields":fields,"constraints":target.constraints,"mutationMode":target.mutation_mode,"changeControl":target.change_control}))) }).collect::>(); let policy = match &action.execution { - crate::model::CompiledActionExecution::Immediate => json!({"mode":"immediate"}), + crate::model::CompiledActionExecution::Immediate => { + let mut policy = json!({"mode":"immediate"}); + if !action.concurrency.is_condition_required() { + policy["concurrency"] = json!(action.concurrency); + } + policy + } crate::model::CompiledActionExecution::Proposal { proposal } => { let mut policy = json!({"mode":"proposal","review":proposal.review,"application":proposal.application,"retention":proposal.retention,"reviewContext":proposal.review_context,"attachments":proposal.attachments}); // Promotions change what an approved Proposal writes, so they are @@ -3638,7 +3785,10 @@ pub(crate) fn definition_revision( value["refusals"] = json!(function.refusals.keys().collect::>()); value }); - let mut payload = json!({"id":action.id,"apiName":action.api_name,"inputs":inputs,"plan":{"effects":action.effects,"function":function},"commitGuards":{"targets":action.requires,"evidence":action.commit_evidence},"planEvidence":action.evidence,"targets":targets,"execution":policy,"consentIssuer":action.consent_issuer}); + // Guard labels are presentation copy, so rewording one leaves the Action's + // identity, and every Proposal frozen against it, unchanged. + let requires = crate::model::without_labels(&action.requires); + let mut payload = json!({"id":action.id,"apiName":action.api_name,"inputs":inputs,"plan":{"effects":action.effects,"function":function},"commitGuards":{"targets":requires,"evidence":action.commit_evidence},"planEvidence":action.evidence,"targets":targets,"execution":policy,"consentIssuer":action.consent_issuer}); // Request-file bindings decide which request part fills which record // slot, so they are part of the Action's identity. Omitting an empty map // keeps the revision of every Action without request files unchanged. diff --git a/crates/registry-breg/src/metrics.rs b/crates/registry-breg/src/metrics.rs index 21b50966c3..a3473f8262 100644 --- a/crates/registry-breg/src/metrics.rs +++ b/crates/registry-breg/src/metrics.rs @@ -13,7 +13,9 @@ //! status label is one of three coarse classes. Request paths, query values, //! principals, record identifiers, and problem codes never become labels, so //! a caller cannot write arbitrary text into a series and the series count is -//! bounded by the route table regardless of traffic. The pool gauges are +//! bounded by the route table regardless of traffic. The refusal counter +//! `breg_request_refusals_total` carries one `check` label from the closed +//! `FailedCheck` set. The pool gauges are //! republished from the live pool at scrape time and carry only a fixed state //! label. //! @@ -38,7 +40,7 @@ use std::{ collections::BTreeMap, sync::{ atomic::{AtomicU64, Ordering}, - Arc, Mutex, + Arc, Mutex, OnceLock, }, time::{Duration, Instant}, }; @@ -52,6 +54,7 @@ use axum::{ Router, }; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ sample_error_class, Exposition, HistogramSnapshot, MetricKind, ScrapeDeadline, SumCountOrder, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_MEDIA_TYPE, @@ -156,9 +159,12 @@ const DURATION_BUCKETS: [f64; 9] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1. /// Series are keyed only by the closed label set described on this module, so /// the registry is bounded by the route table regardless of traffic and needs /// no eviction. -#[derive(Default)] pub struct Metrics { series: Mutex>, + /// The refusal counter this registry publishes as + /// `breg_request_refusals_total`. A served registry shares the process + /// recorder that the request boundary counts into. + refusals: Arc, /// The pool the metrics scrape handler samples immediately before each /// render. `None` for registries that are never served on the metrics /// listener (for example, a focused unit test). @@ -177,6 +183,36 @@ pub struct Metrics { sample_failures: [AtomicU64; SampleKind::ALL.len()], } +/// The process-wide refusal recorder: the one counter family and the one log +/// budget that every refused request in this process shares, whichever router +/// served it. It is built once, from a closed label space the enum owns, so +/// construction cannot fail. +pub(crate) fn process_refusal_recorder() -> &'static Arc { + static RECORDER: OnceLock> = OnceLock::new(); + RECORDER.get_or_init(|| Arc::new(new_refusal_recorder())) +} + +fn new_refusal_recorder() -> RefusalRecorder { + RefusalRecorder::new("breg").expect("the refusal counter's closed label space is valid") +} + +impl Default for Metrics { + /// A registry with a private refusal counter, for tests that read a + /// deterministic exposition. A served registry is built by + /// [`Metrics::new`]. + fn default() -> Self { + Self { + series: Mutex::default(), + refusals: Arc::new(new_refusal_recorder()), + pool: None, + workers: Vec::new(), + queue_sample: tokio::sync::Mutex::new(()), + active_package_digest: None, + sample_failures: Default::default(), + } + } +} + /// A background worker reported by `breg_worker_last_success_age_seconds`. /// /// The worker label is one of these fixed values, so the series count is @@ -289,14 +325,20 @@ impl Metrics { pub(crate) fn new(pool: RuntimePool) -> Self { Self { pool: Some(pool), + refusals: Arc::clone(process_refusal_recorder()), ..Self::default() } } + /// A registry without a pool that publishes the process refusal counter, + /// so a test can read what the request boundary counted. #[doc(hidden)] #[must_use] pub fn without_pool_for_test() -> Self { - Self::default() + Self { + refusals: Arc::clone(process_refusal_recorder()), + ..Self::default() + } } #[cfg(feature = "postgres-test")] @@ -631,6 +673,7 @@ impl Metrics { 1_u8, ); } + self.refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } @@ -1288,6 +1331,27 @@ mod tests { use std::collections::BTreeSet; use tower::util::ServiceExt; + #[test] + fn the_refusal_counter_declares_every_check_and_publishes_it_at_zero() { + use registry_platform_authcommon::FailedCheck; + let rendered = Metrics::default().render(None); + for check in FailedCheck::ALL { + assert!( + rendered.contains(&format!( + "breg_request_refusals_total{{check=\"{}\"}} 0\n", + check.as_str() + )), + "{} is declared", + check.as_str() + ); + } + let recorder = new_refusal_recorder(); + for check in FailedCheck::ALL { + let _ = recorder.record(check); + assert_eq!(recorder.counter().get(&[check.as_str()]), Some(1)); + } + } + #[test] fn duration_buckets_are_cumulative_and_carry_an_infinite_bound() { let metrics = Metrics::default(); diff --git a/crates/registry-breg/src/migration_plan.rs b/crates/registry-breg/src/migration_plan.rs index 56bc3c2b6e..ef0077bdf6 100644 --- a/crates/registry-breg/src/migration_plan.rs +++ b/crates/registry-breg/src/migration_plan.rs @@ -3249,8 +3249,10 @@ fn encryption_cover_matches_implicit_lookup_index( == cover.target.member_id.as_deref() } +/// Whether every cover names a change that alters no table, column, or index, +/// so a descriptor with no steps and no assertions can review it. #[cfg(feature = "tooling")] -fn covers_are_metadata_only(covers: &[ReviewedChangeCover]) -> bool { +pub fn covers_are_metadata_only(covers: &[ReviewedChangeCover]) -> bool { covers.iter().all(|cover| { matches!( cover.code, diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index fa4dfc4c68..60771d351c 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -492,6 +492,13 @@ pub struct CompiledAction { #[serde(default, skip_serializing_if = "Option::is_none")] pub grouping: Option, pub execution: CompiledActionExecution, + /// How an immediate Action guards its patches. Absent on every Action + /// that asks the caller for a condition. + #[serde( + default, + skip_serializing_if = "crate::contract::ActionConcurrency::is_condition_required" + )] + pub concurrency: crate::contract::ActionConcurrency, pub definition_revision: String, } @@ -637,6 +644,9 @@ pub struct CompiledCommitGuard { pub input: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option, + /// Authored text for the refusal that names `reason`. Presentation only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, #[serde(rename = "recordType")] pub entity_id: String, pub field: String, @@ -654,6 +664,8 @@ pub struct CompiledCommitGuard { pub current_date: Option, #[serde(default, skip_serializing_if = "is_zero_i32")] pub current_date_offset_days: i32, + #[serde(default, skip_serializing_if = "is_zero_i32")] + pub current_date_offset_months: i32, /// Keeps the stored field at or above the named action input. #[serde(default, skip_serializing_if = "Option::is_none")] pub at_least_input: Option, @@ -662,6 +674,18 @@ pub struct CompiledCommitGuard { pub at_most_input: Option, } +/// The guards without their authored labels. A label is presentation copy, so +/// a frozen Proposal binds and compares the guards without it. +pub(crate) fn without_labels(guards: &[CompiledCommitGuard]) -> Vec { + guards + .iter() + .map(|guard| CompiledCommitGuard { + label: None, + ..guard.clone() + }) + .collect() +} + impl CompiledCommitGuard { /// The action input this guard compares the stored field with, if any. pub fn compared_input(&self) -> Option<&str> { diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index cae653bef2..cfc932da6e 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -2397,7 +2397,7 @@ pub enum MutationError { not_after_field: String, }, #[error("mutation is outside the caller's authorized record boundary")] - AuthorizationRefused, + AuthorizationRefused(registry_platform_authcommon::FailedCheck), /// A direct create or patch produced a row outside the selected access /// profile's row boundary. This is distinct from concealed target and /// stale-condition failures, which remain generic precondition refusals. @@ -2493,6 +2493,50 @@ pub enum MutationError { PackagePinMismatch(registry_platform_config::blocks::PackageDigestMismatch), } +impl MutationError { + /// The check a refused caller failed, for the operator only. `None` for an + /// error that does not refuse the caller. The match names every variant, + /// so a new one must decide. + #[deny(clippy::wildcard_enum_match_arm)] + pub(crate) fn failed_check(&self) -> Option { + use registry_platform_authcommon::FailedCheck; + match self { + Self::AuthorizationRefused(check) => Some(*check), + Self::WriteOutsideBoundary => Some(FailedCheck::RowBoundary), + Self::FieldGuardFailed { .. } | Self::ProposalGuardFailed(_) => { + Some(FailedCheck::ActionGuard) + } + Self::InvalidRequest + | Self::InvalidRequestAt(_) + | Self::InvalidTimerWindow { .. } + | Self::PreconditionFailed + | Self::ProposalReviewResultMismatch + | Self::Conflict + | Self::ProposalUniqueConflict + | Self::ProposalRejected + | Self::AttachmentSlotWriteOnce + | Self::AttachmentTooLarge + | Self::AttachmentContentType + | Self::AttachmentDigestMismatch + | Self::IdempotencyConflict + | Self::IdempotencyExpired + | Self::Unavailable + | Self::RetryableConflict + | Self::CommitUnresolved + | Self::ActionHandlerFailure(_) + | Self::ActionEvidenceFailure { .. } + | Self::ActionRefusal(_) + | Self::TimerGenerationUnsupported + | Self::FieldPatternViolation { .. } + | Self::RowLocalConstraintViolation(_) + | Self::FieldEncryptionUnavailable + | Self::IngestionRefusal(_) + | Self::MigrationLockHeld + | Self::PackagePinMismatch(_) => None, + } + } +} + /// PostgreSQL allocation schema entry point exposed only to the real-database /// test target. Production installation is conditional on the compiled /// registry using generated identifiers. diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index d105ffb49c..4bca79cdc4 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -2636,7 +2636,9 @@ impl MutationTransaction { .await .map_err(map_database_error)?; let current = load_action_row(transaction, entity, &target_effects[0].2, true).await?; - if timer_authority.is_none() { + // A `current-revision` Action sends no condition: its commit guards + // were evaluated against this same locked row. + if timer_authority.is_none() && action.concurrency.is_condition_required() { for (input_id, effect, _) in &target_effects { let token = action_condition_token( self.audit.profile(), diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 721039b79c..3107d49bc1 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -732,16 +732,16 @@ impl MutationTransaction { authority: &ProposalAuthority, ) -> Result<(), MutationError> { let action = proposal_action(registry, &document.action_id)?; - if document.action_id != authority.common.action_id() - || authority - .proposal_scope - .as_ref() - .is_some_and(|scope| !scope.contains(&document.proposal_id)) - || (authority.ownership == Some(ProposalOwnership::Caller) - && document.header.owner_reference - != self.proposal_owner_reference(authority.common.principal())) - { - return Err(MutationError::AuthorizationRefused); + if let Some(check) = proposal_document_refusal( + &document.action_id, + authority.common.action_id(), + authority.proposal_scope.as_ref(), + document.proposal_id, + authority.ownership, + &document.header.owner_reference, + || self.proposal_owner_reference(authority.common.principal()), + ) { + return Err(MutationError::AuthorizationRefused(check)); } for (entity_id, id) in &document.input_targets { let entity = registry @@ -2384,7 +2384,7 @@ impl MutationTransaction { Err(MutationError::PreconditionFailed) }; }; - if preconditions.contract != action.requires { + if preconditions.contract != crate::model::without_labels(&action.requires) { return Err(MutationError::PreconditionFailed); } preconditions.validate().map_err(workflow_error)?; @@ -2443,7 +2443,8 @@ impl MutationTransaction { Some(target.expected_revision), registry, trusted_now, - )?; + ) + .map_err(|error| restore_guard_label(error, action))?; } if let Some(fields) = crate::commit_evidence::target_fields(&preconditions.evidence).get(&target.id) @@ -4368,6 +4369,20 @@ fn verify_guard( } } +/// A frozen Proposal holds its guards without labels, so a refusal at Apply +/// takes the label from the Action as it is compiled now. +fn restore_guard_label(error: MutationError, action: &CompiledAction) -> MutationError { + let MutationError::ProposalGuardFailed(mut failure) = error else { + return error; + }; + failure.guard.label = action + .requires + .iter() + .find(|guard| guard.input == failure.guard.input && guard.field == failure.guard.field) + .and_then(|guard| guard.label.clone()); + MutationError::ProposalGuardFailed(failure) +} + fn proposal_read_fields(action: &CompiledAction, entity_id: &str) -> BTreeSet { action .target_uses @@ -4547,6 +4562,86 @@ mod disclosure_tests { } } +/// The check a Proposal document fails against the caller's authority, if +/// any: another action, a Proposal outside the grant's bound scope, or a +/// Proposal another caller owns. +fn proposal_document_refusal( + document_action_id: &str, + authority_action_id: &str, + scope: Option<&BTreeSet>, + proposal_id: Uuid, + ownership: Option, + document_owner: &str, + caller_owner: impl FnOnce() -> String, +) -> Option { + use registry_platform_authcommon::FailedCheck; + if document_action_id != authority_action_id { + return Some(FailedCheck::Operation); + } + if scope.is_some_and(|scope| !scope.contains(&proposal_id)) { + return Some(FailedCheck::TaskGrantScope); + } + if ownership == Some(ProposalOwnership::Caller) && document_owner != caller_owner() { + return Some(FailedCheck::Ownership); + } + None +} + +#[cfg(test)] +mod document_refusal_tests { + use super::*; + use registry_platform_authcommon::FailedCheck; + + #[test] + fn each_refusing_condition_names_its_own_check() { + let id = Uuid::from_u128(1); + let scope = BTreeSet::from([id]); + let owner = || "owner-a".to_owned(); + let check = + |action: &str, scope: Option<&BTreeSet>, proposal: Uuid, ownership, who: &str| { + proposal_document_refusal( + action, "action-a", scope, proposal, ownership, who, owner, + ) + }; + assert_eq!( + check("action-b", None, id, None, "owner-a"), + Some(FailedCheck::Operation) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + Uuid::from_u128(2), + None, + "owner-a" + ), + Some(FailedCheck::TaskGrantScope) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + id, + Some(ProposalOwnership::Caller), + "owner-b" + ), + Some(FailedCheck::Ownership) + ); + assert_eq!( + check( + "action-a", + Some(&scope), + id, + Some(ProposalOwnership::Caller), + "owner-a" + ), + None + ); + // Another owner's Proposal is admitted when ownership is not the caller's. + assert_eq!(check("action-a", None, id, None, "owner-b"), None); + } +} + #[cfg(test)] mod turn_tests { use super::*; @@ -4726,7 +4821,9 @@ mod commit_guard_date_tests { at_least: None, at_most: None, current_date: Some(crate::model::CompiledCurrentDateRelation::OnOrAfter), + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }; diff --git a/crates/registry-breg/src/outbox.rs b/crates/registry-breg/src/outbox.rs index 90f14b0257..1b6f87a92d 100644 --- a/crates/registry-breg/src/outbox.rs +++ b/crates/registry-breg/src/outbox.rs @@ -44,8 +44,7 @@ pub enum OutboxError { /// The deployment identity and chain position every captured envelope carries. #[doc(hidden)] pub struct EnvelopeBinding<'a> { - /// The producing deployment, the same source the delivery worker renders - /// as the `ce-source` header. + /// The producing deployment in the envelope's `source` field. pub source: &'a str, /// The data contract id for each hook's `data`, by hook id. pub data_schemas: &'a BTreeMap, @@ -172,9 +171,7 @@ pub(crate) fn event_data_schemas( /// The commit instant every envelope of one transaction carries. /// -/// Truncated to the millisecond the envelope's wire form spells, and written to -/// the outbox row so the delivery worker's `ce-time` header repeats the -/// envelope's own `time` byte for byte. +/// Truncated to milliseconds for the envelope's `time` field and the outbox row. pub(crate) async fn capture_time(transaction: &Transaction<'_>) -> Result { transaction .query_one( diff --git a/crates/registry-breg/src/postgres/catalog.rs b/crates/registry-breg/src/postgres/catalog.rs index 58c822a535..147f822d83 100644 --- a/crates/registry-breg/src/postgres/catalog.rs +++ b/crates/registry-breg/src/postgres/catalog.rs @@ -22,7 +22,9 @@ use super::{ RuntimeRevoke, SqlIdentifier, }; -pub(super) const MANAGED_SCHEMAS: &[&str] = &[ +/// The schemas a package creates its tables, functions and policies in. The +/// migration role owns them. +pub const MANAGED_SCHEMAS: &[&str] = &[ "registry_internal", "registry_data", "registry_source", diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index 6d946e771e..b55ce3d595 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -36,7 +36,7 @@ pub use baseline::{ }; pub use catalog::{ catalog_drift_objects, managed_schema_fingerprint, verify_catalog_identity_for_catalog, - CatalogIdentity, ExpectedManagedCatalog, ExpectedRegistryIdentity, + CatalogIdentity, ExpectedManagedCatalog, ExpectedRegistryIdentity, MANAGED_SCHEMAS, }; #[cfg(feature = "postgres-test")] #[doc(hidden)] @@ -226,7 +226,7 @@ pub fn strong_record_etag_for_test( pub use roles::{ provision_managed_schemas, provision_postgis_prerequisites, provision_spatial_bbox_role, spatial_bbox_role, verify_btree_gist, verify_migration_role, verify_postgis, - RuntimeWriteAuthority, SqlIdentifier, + RuntimeWriteAuthority, SqlIdentifier, MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR, }; pub(crate) use schema::compiled_pattern_field; pub use schema::install_compiled_schema; @@ -238,7 +238,7 @@ pub(crate) use schema::verify_postgres_17_or_newer; pub(crate) use schema::PreparedSchemaTestCatalogVerifier; #[cfg(all(feature = "runtime", feature = "tooling"))] pub use schema::{ - prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, + prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, SchemaMeasurement, SchemaTestDatabaseIdentity, }; #[cfg(all(feature = "runtime", feature = "tooling"))] diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index db04f8c041..11b4e1692a 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -2049,7 +2049,7 @@ impl PostgresRecordMutationService { | MutationError::Conflict | MutationError::ProposalUniqueConflict | MutationError::ProposalRejected - | MutationError::AuthorizationRefused + | MutationError::AuthorizationRefused(_) // Ingestion consumes the batch mutation outcome through // its run protocol. Its item refusal remains the generic // 412 instead of the direct write route's 403. diff --git a/crates/registry-breg/src/postgres/proposal.rs b/crates/registry-breg/src/postgres/proposal.rs index 2aaa8ec348..3d991c0705 100644 --- a/crates/registry-breg/src/postgres/proposal.rs +++ b/crates/registry-breg/src/postgres/proposal.rs @@ -1471,7 +1471,7 @@ impl PostgresRecordMutationService { { Ok(()) => {} Err( - MutationError::AuthorizationRefused | MutationError::PreconditionFailed, + MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed, ) => { guarded .rollback() @@ -1641,7 +1641,9 @@ impl PostgresRecordMutationService { fn link_readable(outcome: Result<(), MutationError>) -> Result { match outcome { Ok(()) => Ok(true), - Err(MutationError::AuthorizationRefused | MutationError::PreconditionFailed) => Ok(false), + Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { + Ok(false) + } Err(error) => Err(error), } } @@ -1654,7 +1656,9 @@ mod tests { fn a_link_check_omits_only_a_refusal_and_fails_on_anything_else() { assert_eq!(link_readable(Ok(())), Ok(true)); for refusal in [ - MutationError::AuthorizationRefused, + MutationError::AuthorizationRefused( + registry_platform_authcommon::FailedCheck::Ownership, + ), MutationError::PreconditionFailed, ] { assert_eq!(link_readable(Err(refusal)), Ok(false)); diff --git a/crates/registry-breg/src/postgres/roles.rs b/crates/registry-breg/src/postgres/roles.rs index 527e50d513..d64b948a38 100644 --- a/crates/registry-breg/src/postgres/roles.rs +++ b/crates/registry-breg/src/postgres/roles.rs @@ -12,8 +12,10 @@ use super::catalog::MANAGED_SCHEMAS; use super::schema::verify_postgres_version; use super::{PostgresKernelError, Result}; -const MIN_POSTGIS_MAJOR: u32 = 3; -const MIN_POSTGIS_MINOR: u32 = 5; +/// The major version of the oldest PostGIS the runtime accepts. +pub const MIN_POSTGIS_MAJOR: u32 = 3; +/// The minor version of the oldest PostGIS the runtime accepts. +pub const MIN_POSTGIS_MINOR: u32 = 5; /// A validated PostgreSQL identifier used only for governed provisioning. #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/registry-breg/src/postgres/schema.rs b/crates/registry-breg/src/postgres/schema.rs index 77b2d39321..53c13f5733 100644 --- a/crates/registry-breg/src/postgres/schema.rs +++ b/crates/registry-breg/src/postgres/schema.rs @@ -933,22 +933,32 @@ pub async fn prepare_schema_test_database_with_connections( }) } +/// What a fresh install of one compiled Registry measures on a disposable +/// database: the managed schema fingerprint and the server's PostgreSQL major +/// version. +#[cfg(all(feature = "runtime", feature = "tooling"))] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SchemaMeasurement { + pub fingerprint: String, + pub postgres_major: u16, +} + /// Install one compiled Registry into an empty disposable database transaction, /// verify the exact managed catalog, roll the transaction back, and return only -/// its schema fingerprint. This is a measurement path only: it never writes -/// active package identity and it never returns a pool, client, database id, -/// role, URL, or SQL. +/// its schema fingerprint and the server's PostgreSQL major version. This is a +/// measurement path only: it never writes active package identity and it never +/// returns a pool, client, database id, role, URL, or SQL. #[cfg(all(feature = "runtime", feature = "tooling"))] pub(crate) async fn rehearse_schema_fingerprint_with_connection( migration_connection: &ConnectionConfig, migration_role: &SqlIdentifier, runtime_role: &SqlIdentifier, registry: &CompiledRegistry, -) -> std::result::Result { +) -> std::result::Result { let (mut migration, migration_task) = connect_schema_test_with_cause(migration_connection) .await .map_err(SchemaRehearsalError::Connection)?; - let migration_result: Result = async { + let migration_result: Result = async { verify_migration_role(&migration, migration_role).await?; let transaction = migration.transaction().await?; transaction @@ -959,8 +969,21 @@ pub(crate) async fn rehearse_schema_fingerprint_with_connection( let expected_catalog = ExpectedManagedCatalog::compiled(registry); let fingerprint = managed_schema_fingerprint(&transaction, runtime_role, &expected_catalog).await?; + let version: i32 = transaction + .query_one( + "SELECT current_setting('server_version_num')::integer / 10000", + &[], + ) + .await? + .get(0); + let postgres_major = u16::try_from(version).map_err(|_| { + PostgresKernelError::Configuration("the PostgreSQL major version is out of range") + })?; transaction.rollback().await?; - Ok(fingerprint) + Ok(SchemaMeasurement { + fingerprint, + postgres_major, + }) } .await; migration_task.abort(); diff --git a/crates/registry-breg/src/problem.rs b/crates/registry-breg/src/problem.rs index 71ee01d356..0026ac5622 100644 --- a/crates/registry-breg/src/problem.rs +++ b/crates/registry-breg/src/problem.rs @@ -292,7 +292,7 @@ impl ProblemCode { "The record attachment slot already holds a file and is write-once." } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", - Self::AuthenticationRefused => "The bearer credential is missing or refused.", + Self::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", Self::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." } diff --git a/crates/registry-breg/src/proposal_hooks.rs b/crates/registry-breg/src/proposal_hooks.rs index 9eb2a341d0..59eb470606 100644 --- a/crates/registry-breg/src/proposal_hooks.rs +++ b/crates/registry-breg/src/proposal_hooks.rs @@ -51,7 +51,7 @@ pub fn source_hooks( actions.iter().flat_map(|action| { let hooks = match &action.execution { ActionExecutionSource::Proposal { proposal } => proposal.hooks.as_slice(), - ActionExecutionSource::Immediate {} => &[], + ActionExecutionSource::Immediate { .. } => &[], }; hooks.iter().map(move |hook| (action.id.as_str(), hook)) }) diff --git a/crates/registry-breg/src/proposal_prepare.rs b/crates/registry-breg/src/proposal_prepare.rs index db427b2c5e..de8392fccb 100644 --- a/crates/registry-breg/src/proposal_prepare.rs +++ b/crates/registry-breg/src/proposal_prepare.rs @@ -601,7 +601,7 @@ pub(crate) fn prepare_with_reserved_create_fields( } proposal = workflow(proposal.with_application_preconditions( FrozenApplicationPreconditions { - contract: action.requires.clone(), + contract: crate::model::without_labels(&action.requires), evidence: action.commit_evidence.clone(), input_values: input.clone().into_iter().collect(), targets, diff --git a/crates/registry-breg/src/proposal_workflow.rs b/crates/registry-breg/src/proposal_workflow.rs index b2c4529d1a..fd80bc3f51 100644 --- a/crates/registry-breg/src/proposal_workflow.rs +++ b/crates/registry-breg/src/proposal_workflow.rs @@ -3067,7 +3067,9 @@ mod source_owned_review_tests { at_least: None, at_most: None, current_date: Some(crate::model::CompiledCurrentDateRelation::OnOrAfter), + label: None, current_date_offset_days: 0, + current_date_offset_months: 0, at_least_input: None, at_most_input: None, }], diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index 06fc83bf88..40e05347a5 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -7,6 +7,10 @@ //! an exact proposal and submission-digest comparison. use chrono::{DateTime, Utc}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_crypto::delivery_signature::{ + self, DeliveryKey, DeliveryKeys, DeliverySignatureError, SignedContent, DELIVERY_TOLERANCE, +}; use registry_platform_httputil::client::TokenProvider; use registry_review_client::{ submission_digest, BearerToken, ReviewAuth, ReviewClient, ReviewClientError, ReviewCompletion, @@ -18,10 +22,8 @@ use serde_json::Value; use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; -use subtle::ConstantTimeEq; use tokio_postgres::{GenericClient, Transaction}; use uuid::Uuid; -use zeroize::Zeroizing; use crate::model::{CompiledProposalReview, CompiledRegistry}; use crate::mutation::MutationError; @@ -92,17 +94,12 @@ fn outbound_lease_seconds(request_timeout: Duration) -> i64 { .max(APPLICATION_LEASE_MINIMUM_SECONDS) } -pub(crate) fn valid_completion_recipient(recipient: &str) -> bool { +pub fn valid_completion_recipient(recipient: &str) -> bool { !recipient.is_empty() && recipient.len() <= MAXIMUM_COMPLETION_RECIPIENT_BYTES && recipient.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) } -fn valid_completion_token(token: &str) -> bool { - registry_platform_authcommon::parse_bearer_token(&format!("Bearer {token}")) - .is_ok_and(|parsed| parsed == token) -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ReviewConfigurationError; @@ -278,7 +275,7 @@ pub struct ReviewAuthorityClient { profile: String, producer_id: String, recovery_days: u32, - completion_token: Option>, + completion_keys: Option, completion_recipient: Option, lease_seconds: i64, progress_lookups: tokio::sync::Semaphore, @@ -293,7 +290,7 @@ impl ReviewAuthorityClient { profile: String, producer_id: String, recovery_days: u32, - completion_token: Option>, + completion_keys: Option, completion_recipient: Option, ) -> Result { if authority.trim().is_empty() @@ -307,10 +304,7 @@ impl ReviewAuthorityClient { || producer_id.len() > 128 || producer_id.chars().any(char::is_control) || !(1..=MAXIMUM_REVIEW_RECOVERY_DAYS).contains(&recovery_days) - || completion_token.is_some() != completion_recipient.is_some() - || completion_token - .as_ref() - .is_some_and(|token| token.len() > 4096 || !valid_completion_token(token)) + || completion_keys.is_some() != completion_recipient.is_some() || completion_recipient .as_ref() .is_some_and(|recipient| !valid_completion_recipient(recipient)) @@ -328,7 +322,7 @@ impl ReviewAuthorityClient { profile, producer_id, recovery_days, - completion_token, + completion_keys, completion_recipient, lease_seconds, progress_lookups: tokio::sync::Semaphore::new(MAXIMUM_PROGRESS_LOOKUPS_PER_AUTHORITY), @@ -338,6 +332,7 @@ impl ReviewAuthorityClient { pub struct ReviewAuthorityRegistry { authorities: BTreeMap>, + completion_bindings: BTreeMap, /// Result-feed backoff by authority. An authority with no entry is /// available and its feed is fetched on every worker pass. feed_backoff: std::sync::Mutex>, @@ -468,17 +463,23 @@ impl ReviewAuthorityRegistry { || authorities .iter() .any(|(id, authority)| id != &authority.authority) - || authorities.values().enumerate().any(|(index, authority)| { - authorities - .values() - .skip(index + 1) - .any(|other| same_completion_binding(authority, other)) - }) { return Err(ReviewConfigurationError); } + let mut completion_bindings = BTreeMap::new(); + for (id, authority) in &authorities { + if let Some(recipient) = &authority.completion_recipient { + if completion_bindings + .insert(recipient.clone(), id.clone()) + .is_some() + { + return Err(ReviewConfigurationError); + } + } + } Ok(Self { authorities, + completion_bindings, feed_backoff: std::sync::Mutex::new(BTreeMap::new()), feed_clock: Arc::new(tokio::time::Instant::now), }) @@ -577,37 +578,40 @@ impl ReviewAuthorityRegistry { .map(|configured| configured.recovery_days) } - /// Resolve a completion sender only when both its independently configured - /// bearer credential and logical recipient match one authority exactly. - pub fn completion_authority(&self, token: &str, recipient: &str) -> Option<&str> { - let mut matched = None; - for (authority, configured) in &self.authorities { - let Some(expected_token) = configured.completion_token.as_ref() else { - continue; - }; - let Some(expected_recipient) = configured.completion_recipient.as_ref() else { - continue; - }; - let token_matches = expected_token.len() == token.len() - && expected_token - .as_bytes() - .ct_eq(token.as_bytes()) - .unwrap_u8() - == 1; - let recipient_matches = expected_recipient.len() == recipient.len() - && expected_recipient - .as_bytes() - .ct_eq(recipient.as_bytes()) - .unwrap_u8() - == 1; - if token_matches && recipient_matches { - if matched.is_some() { - return None; - } - matched = Some(authority.as_str()); + pub(crate) fn labeled_completion_keys(&self) -> impl Iterator { + self.authorities.iter().flat_map(|(id, authority)| { + authority.completion_keys.iter().flat_map(move |keys| { + crate::event_destination::labeled_delivery_keys( + &format!("reviewAuthorities.{id}.completion"), + keys, + ) + }) + }) + } + + fn verify_completion( + &self, + recipient: &str, + content: SignedContent<'_>, + now: std::time::SystemTime, + ) -> Result<(&str, u32), FailedCheck> { + let id = self + .completion_bindings + .get(recipient) + .ok_or(FailedCheck::DeliverySignature)?; + let authority = &self.authorities[id]; + let keys = authority + .completion_keys + .as_ref() + .ok_or(FailedCheck::DeliverySignature)?; + delivery_signature::verify(keys, content, now, DELIVERY_TOLERANCE).map_err(|error| { + match error { + DeliverySignatureError::StaleDelivery + | DeliverySignatureError::InvalidTimestamp => FailedCheck::DeliveryFreshness, + _ => FailedCheck::DeliverySignature, } - } - matched + })?; + Ok((id, authority.recovery_days)) } async fn authorities_for_pending( @@ -947,31 +951,6 @@ impl ReviewAuthorityRegistry { } } -fn same_completion_binding(left: &ReviewAuthorityClient, right: &ReviewAuthorityClient) -> bool { - let (Some(left_token), Some(left_recipient)) = - (&left.completion_token, &left.completion_recipient) - else { - return false; - }; - let (Some(right_token), Some(right_recipient)) = - (&right.completion_token, &right.completion_recipient) - else { - return false; - }; - left_token.len() == right_token.len() - && left_token - .as_bytes() - .ct_eq(right_token.as_bytes()) - .unwrap_u8() - == 1 - && left_recipient.len() == right_recipient.len() - && left_recipient - .as_bytes() - .ct_eq(right_recipient.as_bytes()) - .unwrap_u8() - == 1 -} - fn terminal_submission_error(error: &ReviewClientError) -> bool { match error { ReviewClientError::Configuration { .. } | ReviewClientError::InvalidRequest { .. } => true, @@ -1148,10 +1127,17 @@ impl ReviewCompletionReceiver { Self { pool, authorities } } - pub fn authority(&self, token: &str, recipient: &str) -> Option<(String, u32)> { - let authority = self.authorities.completion_authority(token, recipient)?; - let recovery_days = self.authorities.recovery_days(authority)?; - Some((authority.to_owned(), recovery_days)) + pub(crate) fn contains_recipient(&self, recipient: &str) -> bool { + self.authorities.completion_bindings.contains_key(recipient) + } + + pub fn verify_completion( + &self, + recipient: &str, + content: SignedContent<'_>, + now: std::time::SystemTime, + ) -> Result<(&str, u32), FailedCheck> { + self.authorities.verify_completion(recipient, content, now) } pub async fn receive( @@ -3109,7 +3095,7 @@ mod tests { } } - fn authority(id: &str, completion: Option<(&str, &str)>) -> Arc { + fn authority(id: &str, completion: Option<(u8, &str)>) -> Arc { let client = ReviewClient::new(registry_review_client::ReviewClientConfig::new( "https://casework.example.test/".parse().expect("URL"), )) @@ -3125,74 +3111,72 @@ mod tests { "producer".to_owned(), format!("{id}-producer"), 30, - completion.map(|(token, _)| Zeroizing::new(token.to_owned())), + completion.map(|(key, _)| test_completion_keys(key)), completion.map(|(_, recipient)| recipient.to_owned()), ) .expect("authority"), ) } + fn test_completion_keys(byte: u8) -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(&[byte; 32]).unwrap(), None).unwrap() + } + #[test] - fn completion_sender_requires_exact_independent_token_and_recipient() { + fn a_completion_binding_selects_one_authority_and_its_keys() { let registry = ReviewAuthorityRegistry::new(BTreeMap::from([ ( "casework-a".to_owned(), - authority("casework-a", Some(("sender-a", "registry-a"))), + authority("casework-a", Some((1, "registry-a"))), ), ( "casework-b".to_owned(), - authority("casework-b", Some(("sender-b", "registry-b"))), + authority("casework-b", Some((2, "registry-b"))), ), ])) .expect("registry"); - - assert_eq!( - registry.completion_authority("sender-a", "registry-a"), - Some("casework-a") - ); + let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1000); + let signature = + delivery_signature::sign(&test_completion_keys(1), "event", 1000, b"{}").unwrap(); + let content = || SignedContent { + id: "event", + timestamp: "1000", + signature: &signature, + body: b"{}", + }; assert_eq!( - registry.completion_authority("sender-a", "registry-b"), - None + registry.verify_completion("registry-a", content(), now), + Ok(("casework-a", 30)) ); + for edge in [now - DELIVERY_TOLERANCE, now + DELIVERY_TOLERANCE] { + assert_eq!( + registry.verify_completion("registry-a", content(), edge), + Ok(("casework-a", 30)), + ); + } assert_eq!( - registry.completion_authority("sender-b", "registry-a"), - None + registry.verify_completion("registry-b", content(), now), + Err(FailedCheck::DeliverySignature) ); assert_eq!( - registry.completion_authority("outgoing-token", "registry-a"), - None + registry.verify_completion("unknown", content(), now), + Err(FailedCheck::DeliverySignature) ); } #[test] - fn completion_sender_bindings_must_be_unique_pairs() { + fn completion_recipient_bindings_must_be_unique() { assert!(ReviewAuthorityRegistry::new(BTreeMap::from([ ( "casework-a".to_owned(), - authority("casework-a", Some(("shared-sender", "registry-a"))), + authority("casework-a", Some((1, "registry-a"))) ), ( "casework-b".to_owned(), - authority("casework-b", Some(("shared-sender", "registry-a"))), + authority("casework-b", Some((2, "registry-a"))) ), ])) .is_err()); - - assert!(ReviewAuthorityRegistry::new(BTreeMap::from([ - ( - "casework-a".to_owned(), - authority("casework-a", Some(("shared-sender", "registry-a"))), - ), - ( - "casework-b".to_owned(), - authority("casework-b", Some(("shared-sender", "registry-b"))), - ), - ( - "casework-c".to_owned(), - authority("casework-c", Some(("other-sender", "registry-a"))), - ), - ])) - .is_ok()); } #[test] @@ -3241,37 +3225,10 @@ mod tests { ); } - #[test] - fn completion_sender_rejects_tokens_outside_the_inbound_bearer_grammar() { - for token in ["sender token", "sender,token"] { - let client = ReviewClient::new(registry_review_client::ReviewClientConfig::new( - "https://casework.example.test/".parse().expect("URL"), - )) - .expect("client"); - assert!( - ReviewAuthorityClient::new( - "casework-a".to_owned(), - client, - Arc::new( - registry_platform_httputil::StaticToken::new("outgoing-token".to_owned(),) - .expect("outgoing token"), - ), - "producer".to_owned(), - "registry-producer".to_owned(), - 30, - Some(Zeroizing::new(token.to_owned())), - Some("registry-a".to_owned()), - ) - .is_err(), - "completion token {token:?} cannot authenticate the inbound route" - ); - } - } - #[test] fn completion_recipient_accepts_only_bounded_visible_ascii() { let at_bound = "x".repeat(MAXIMUM_COMPLETION_RECIPIENT_BYTES); - authority("casework-a", Some(("sender-a", &at_bound))); + authority("casework-a", Some((1, &at_bound))); for recipient in ["contains space", "contains\t tab", "récepteur"] { assert!( @@ -3296,7 +3253,7 @@ mod tests { "producer".to_owned(), "registry-producer".to_owned(), 30, - Some(Zeroizing::new("sender-a".to_owned())), + Some(test_completion_keys(1)), Some(over_bound), ) .is_err(), @@ -3339,10 +3296,7 @@ mod tests { )])) .expect("registry"); - assert_eq!( - registry.completion_authority("any-token", "any-recipient"), - None - ); + assert!(registry.completion_bindings.is_empty()); assert_eq!( registry.submission_binding("casework-a"), Some(("casework-a-producer", 30)) diff --git a/crates/registry-breg/src/rhai_planner.rs b/crates/registry-breg/src/rhai_planner.rs index ad4faba2ce..4a4bf1fb5e 100644 --- a/crates/registry-breg/src/rhai_planner.rs +++ b/crates/registry-breg/src/rhai_planner.rs @@ -193,7 +193,10 @@ fn add_days(value: ImmutableString, days: INT) -> Result Result> { +pub(crate) fn add_months( + value: ImmutableString, + months: INT, +) -> Result> { if !(-12_000..=12_000).contains(&months) { return Err(helper_error()); } diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index eed81bd2d0..25cb8ad201 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -17,17 +17,18 @@ use registry_platform_audit::{AuditDestination, AuditDestinationKind, AuditProfi use registry_platform_config::{ check_metrics_bind_address, check_metrics_bind_apart, AuditKeyConfig, JwksSource, MetricsBindError, OidcIssuerConfig, PackageConfig as SharedPackageConfig, RemovedKey, - RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretReference, SecretResolver, - TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, + RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretFileCheck, SecretReference, + SecretResolver, TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, }; -use registry_platform_crypto::{parse_json_strict, PublicJwk, SigningAlgorithm}; +use registry_platform_crypto::{delivery_signature::DeliveryKeys, PublicJwk, SigningAlgorithm}; #[cfg(feature = "schema")] use registry_platform_httputil::destination::{ MAX_DESTINATION_ORIGIN_URL_BYTES, MAX_DESTINATION_PRIVATE_CIDRS, MAX_DESTINATION_TARGET_BYTES, }; use registry_platform_oidc::{ - access_token_typ_set, fetch_discovery_for_issuer, AccessTokenAlgorithm, ClaimNames, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + access_token_typ_set, fetch_discovery_for_issuer, public_jwks_document, AccessTokenAlgorithm, + ClaimNames, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, + StaticJwksError, TokenVerifierConfig, }; use registry_platform_yaml::{ lookalike_local_id_pairs, Diagnostic, Report, RetiredApiVersion, Severity, Source, Url, @@ -46,7 +47,10 @@ use crate::{ auth::{AuthenticationConfigError, AuthorityClaimConfig}, cursor::CursorCodec, event_destination::{ - ActivatedEventDestinationRegistry, EventDestinationConfigs, RawEventDestinationConfigs, + labeled_delivery_keys, present_hook_key_reference, resolve_delivery_keys, + signing_key_action, ActivatedEventDestinationRegistry, EventDestinationActivationError, + EventDestinationConfigs, RawEventDestinationConfigs, CURRENT_KEY_MEMBER, + PREVIOUS_KEY_MEMBER, }, model::CompiledRegistry, package::{ @@ -157,6 +161,14 @@ const RETIRED_RUNTIME_API_VERSIONS: &[RetiredApiVersion<'static>] = &[RetiredApi /// Keys the runtime file no longer accepts, each refused with the edit that /// replaces it. const REMOVED_KEYS: &[RemovedKey] = &[ + RemovedKey { + path: "reviewAuthorities.*.completionTokenRef", + replacement: "Replace completionTokenRef with completion.hmacSha256KeyRef. Casework signs review completions with Standard Webhooks.", + }, + RemovedKey { + path: "reviewAuthorities.*.completionRecipient", + replacement: "Move completionRecipient to completion.recipientBinding.", + }, RemovedKey { path: "database.url", replacement: "delete database.url and name the connection URL by secret reference in database.runtimeUrlRef and database.migrationUrlRef", @@ -365,6 +377,9 @@ pub enum RuntimeConfigError { UnsafePackageRoot, #[error("runtime configuration contains an invalid OIDC binding")] InvalidOidc, + // The cause is the remedy `diagnostics` reports, so the message does not repeat it. + #[error("the static OIDC key set was refused")] + InvalidStaticJwks(StaticJwksError), #[error("the OIDC leeway must be a whole number of seconds from 0 to 300000 milliseconds")] InvalidOidcLeeway, #[error("runtime configuration contains an invalid audit binding")] @@ -373,6 +388,18 @@ pub enum RuntimeConfigError { InvalidCursor, #[error("runtime configuration contains an invalid event destination binding")] InvalidEventDestination, + #[error("{reason} {action}")] + InvalidDeliveryKey { + path: String, + reason: String, + action: String, + }, + #[error("{first} and {second} select the same completion recipient.")] + DuplicateCompletionRecipient { + first: String, + second: String, + path: String, + }, #[error( "runtime configuration destinations.hooks contains identifiers that differ only by `-` versus `_`" )] @@ -408,6 +435,8 @@ pub enum RuntimeConfigError { InvalidWasmExecution, #[error("runtime configuration secret resolution failed")] Secret, + #[error("runtime configuration secret file refused: {} ({})", .0.message(), .0.code())] + SecretFile(SecretFileCheck), } /// The config path of the exposure key a wildcard metrics refusal names. @@ -435,11 +464,15 @@ impl RuntimeConfigError { Self::InvalidPackage => "breg.runtime.invalid-package", Self::PackageRootUnavailable => "breg.runtime.package-root-unavailable", Self::UnsafePackageRoot => "breg.runtime.unsafe-package-root", - Self::InvalidOidc => "breg.runtime.invalid-oidc", + Self::InvalidOidc | Self::InvalidStaticJwks(_) => "breg.runtime.invalid-oidc", Self::InvalidOidcLeeway => "breg.runtime.invalid-oidc-leeway", Self::InvalidAudit => "breg.runtime.invalid-audit", Self::InvalidCursor => "breg.runtime.invalid-cursor", Self::InvalidEventDestination => "breg.runtime.invalid-hook-destination", + Self::InvalidDeliveryKey { .. } => "breg.runtime.invalid-delivery-key", + Self::DuplicateCompletionRecipient { .. } => { + "breg.runtime.duplicate-completion-recipient" + } Self::EventDestinationIdCollision => "breg.runtime.hook-destination-id-collision", Self::EvidenceProviderIdCollision => "breg.runtime.evidence-provider-id-collision", Self::ReviewAuthorityIdCollision => "breg.runtime.review-authority-id-collision", @@ -453,7 +486,7 @@ impl RuntimeConfigError { Self::InvalidBounds => "breg.runtime.invalid-bounds", Self::PoolBudgetExceeded => "breg.runtime.pool-budget-exceeded", Self::InvalidWasmExecution => "breg.runtime.invalid-wasm-execution", - Self::Secret => "breg.runtime.secret", + Self::Secret | Self::SecretFile(_) => "breg.runtime.secret", } } @@ -462,8 +495,10 @@ impl RuntimeConfigError { fn path(&self) -> &str { match self { Self::Reader(refusal) => &refusal.deciding_diagnostic().path, - Self::InvalidBinding | Self::Secret => "", - Self::InvalidExternalSource { path, .. } => path, + Self::InvalidBinding | Self::Secret | Self::SecretFile(_) => "", + Self::InvalidExternalSource { path, .. } + | Self::InvalidDeliveryKey { path, .. } + | Self::DuplicateCompletionRecipient { path, .. } => path, Self::InvalidTaskGrantStatus => "/taskGrantStatus", Self::InvalidInstanceId => "/identity/instanceId", Self::EnvironmentIdentityConflict => "/identity/databaseInitializationEnvironment", @@ -477,7 +512,7 @@ impl RuntimeConfigError { Self::PlaintextDatabase => "/database/testOnlyPlaintext", Self::InvalidPackage => "/package", Self::PackageRootUnavailable | Self::UnsafePackageRoot => "/package/root", - Self::InvalidOidc => "/authentication/oidc", + Self::InvalidOidc | Self::InvalidStaticJwks(_) => "/authentication/oidc", Self::InvalidOidcLeeway => "/authentication/oidc/leewayMilliseconds", Self::InvalidAudit => "/audit", Self::InvalidCursor => "/cursor", @@ -501,7 +536,7 @@ impl RuntimeConfigError { /// The edit that fixes a refusal this runtime decides itself /// (CFG-DIAG-6). A reader refusal carries its own action in each /// diagnostic. - fn suggested_action(&self) -> &'static str { + fn suggested_action(&self) -> &str { match self { Self::Reader(_) => "", Self::InvalidTaskGrantStatus => { @@ -549,6 +584,8 @@ impl RuntimeConfigError { Self::InvalidOidc => { "Correct authentication.oidc and authentication.authorityClaims: use an https issuer, loopback http, or set authentication.oidc.allowInsecureHttp: true for a declared non-loopback http issuer; keep values bounded without whitespace, list entries distinct, and claim names non-repeating." } + // The remedy is the cause's own text, which `diagnostics` states. + Self::InvalidStaticJwks(_) => "", Self::InvalidOidcLeeway => { "Set authentication.oidc.leewayMilliseconds to a multiple of 1000 no greater than 300000." } @@ -556,6 +593,8 @@ impl RuntimeConfigError { "Give the file audit destination an absolute path, and leave audit.path, audit.rotateBytes, and audit.retentionDays out for the stdout destination." } Self::InvalidCursor => "Name cursor.secretRef by secret reference.", + Self::InvalidDeliveryKey { action, .. } => action, + Self::DuplicateCompletionRecipient { .. } => "Give each review authority its own completion.recipientBinding.", Self::InvalidEventDestination => { "Correct the event destination bindings: an https origin, a path that starts with `/`, and secret references for keys and TLS material." } @@ -591,6 +630,7 @@ impl RuntimeConfigError { Self::Secret => { "Make every secret reference resolve through the declared secret providers." } + Self::SecretFile(check) => check.suggested_action(), } } @@ -604,9 +644,14 @@ impl RuntimeConfigError { } let action = match self { Self::InvalidMetricsListener(cause) => cause.remedy(METRICS_NETWORK_EXPOSURE_KEY), + Self::InvalidStaticJwks(cause) => cause.to_string(), other => other.suggested_action().to_owned(), }; - let mut diagnostic = Diagnostic::error(self.code(), self.path(), self.to_string(), action); + let message = match self { + Self::InvalidDeliveryKey { reason, .. } => reason.clone(), + other => other.to_string(), + }; + let mut diagnostic = Diagnostic::error(self.code(), self.path(), message, action); diagnostic.source = file.map(|file| Source { file: file.display().to_string(), line: None, @@ -626,8 +671,11 @@ impl RuntimeConfigError { } impl From for RuntimeConfigError { - fn from(_error: SecretError) -> Self { - Self::Secret + fn from(error: SecretError) -> Self { + match error { + SecretError::UnsafeFile(check) => Self::SecretFile(check), + _ => Self::Secret, + } } } @@ -1008,7 +1056,7 @@ fn runtime_stand_in(pointer: &str) -> &'static str { /// position reach the operator. The file is held to the shared 1 MiB bound /// (CFG-YAML-6). const fn runtime_config_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: RUNTIME_CONFIG_API_VERSION, kind: RUNTIME_CONFIG_KIND, }) @@ -1272,6 +1320,7 @@ impl RuntimeConfig { } let resolver = self.secret_resolver()?; let mut activated = BTreeMap::new(); + let mut recipients = BTreeMap::new(); // Activate retained operator bindings as well as bindings referenced by // the new package. Durable submissions created by the previous package // must keep their worker after a review policy is changed or removed. @@ -1280,18 +1329,53 @@ impl RuntimeConfig { config.token_ref.as_ref(), config.private_key_jwt.as_ref(), )?; - let completion = config - .completion - .as_ref() - .map( - |(token_ref, recipient)| -> Result<(Zeroizing, String)> { - let token = resolver.resolve_reference(token_ref)?; - let token = std::str::from_utf8(token.expose_secret()) - .map_err(|_| RuntimeConfigError::Secret)?; - Ok((Zeroizing::new(token.to_owned()), recipient.clone())) - }, - ) - .transpose()?; + let (completion_keys, recipient) = if let Some(completion) = &config.completion { + let block = format!("reviewAuthorities.{authority}.completion"); + let pointer_authority = authority.replace('~', "~0").replace('/', "~1"); + let pointer = format!("/reviewAuthorities/{pointer_authority}/completion"); + if let Some(first) = recipients.insert(&completion.recipient_binding, authority) { + return Err(RuntimeConfigError::DuplicateCompletionRecipient { + first: format!("reviewAuthorities.{first}.completion.recipientBinding"), + second: format!("{block}.recipientBinding"), + path: format!("{pointer}/recipientBinding"), + }); + } + let keys = completion.resolve_keys(&resolver, &block).map_err(|error| { + let (member_path, reason, action) = match error { + EventDestinationActivationError::SigningKeyUnavailable {path, reason, action} => ( + path.clone(), + format!("{path} could not be resolved: {reason}."), + action.to_owned(), + ), + EventDestinationActivationError::InvalidSigningKey { + path, length, trailing_newline, reason, + } => ( + path.clone(), + format!("{path} has {length} bytes (trailing newline: {trailing_newline})."), + signing_key_action(&reason).to_owned(), + ), + EventDestinationActivationError::PreviousEqualsCurrent { current, previous } => ( + previous.clone(), + format!("{previous} holds the same bytes as {current}."), + format!("To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}."), + ), + _ => unreachable!("key resolution returns only key errors"), + }; + let member = if member_path.ends_with(PREVIOUS_KEY_MEMBER) { + PREVIOUS_KEY_MEMBER + } else { + CURRENT_KEY_MEMBER + }; + RuntimeConfigError::InvalidDeliveryKey { + path: format!("{pointer}/{member}"), + reason, + action, + } + })?; + (Some(keys), Some(completion.recipient_binding.clone())) + } else { + (None, None) + }; let client = registry_review_client::ReviewClient::new( registry_review_client::ReviewClientConfig::new(config.endpoint.clone()) .with_attempt_timeout(self.operational_timeouts.http_request) @@ -1305,8 +1389,8 @@ impl RuntimeConfig { config.profile.clone(), config.producer_id.clone(), config.recovery_days, - completion.as_ref().map(|(token, _)| token.clone()), - completion.map(|(_, recipient)| recipient), + completion_keys, + recipient, ) .map_err(|_| RuntimeConfigError::InvalidBinding)?; activated.insert(authority.clone(), Arc::new(authority_client)); @@ -1480,11 +1564,51 @@ impl RuntimeConfig { > { let resolver = self .secret_resolver() - .map_err(|_| crate::event_destination::EventDestinationActivationError::Secret)?; - ActivatedEventDestinationRegistry::activate(compiled, &self.event_destinations, &resolver) - .map(|destinations| { - destinations.with_payload_retention(self.retention.payload_retention) + .map_err(|_| EventDestinationActivationError::Secret)?; + let completion_keys = self + .review_authorities + .iter() + .filter_map(|(authority, config)| Some((authority, config.completion.as_ref()?))) + .map(|(authority, completion)| { + let block = format!("reviewAuthorities.{authority}.completion"); + completion + .resolve_keys(&resolver, &block) + .map(|keys| (block, keys)) }) + .collect::, _>>()?; + ActivatedEventDestinationRegistry::activate( + compiled, + &self.event_destinations, + &resolver, + completion_keys + .iter() + .flat_map(|(block, keys)| labeled_delivery_keys(block, keys)) + .collect(), + ) + .map(|destinations| destinations.with_payload_retention(self.retention.payload_retention)) + } + + /// Activate hook destinations and check their keys against the active review authorities. + pub fn activate_event_destinations_with_review_authorities( + &self, + compiled: &CompiledRegistry, + authorities: Option<&crate::review_store::ReviewAuthorityRegistry>, + ) -> std::result::Result + { + let resolver = self + .secret_resolver() + .map_err(|_| crate::event_destination::EventDestinationActivationError::Secret)?; + let review_keys = authorities + .into_iter() + .flat_map(|authority| authority.labeled_completion_keys()) + .collect(); + ActivatedEventDestinationRegistry::activate( + compiled, + &self.event_destinations, + &resolver, + review_keys, + ) + .map(|destinations| destinations.with_payload_retention(self.retention.payload_retention)) } pub fn operational_timeouts(&self) -> &OperationalTimeouts { @@ -1838,10 +1962,7 @@ impl PublicOrigin { .host() .trim_start_matches('[') .trim_end_matches(']'); - let loopback = host.eq_ignore_ascii_case("localhost") - || host - .parse::() - .is_ok_and(|address| address.is_loopback()); + let loopback = registry_platform_httputil::loopback::loopback_host(host).is_some(); let scheme_allowed = match uri.scheme_str() { Some("https") => true, Some("http") => loopback, @@ -2056,6 +2177,18 @@ impl DatabaseConfig { pub fn ca_bundle_ref(&self) -> Option<&SecretReference> { self.ca_bundle_ref.as_ref() } + + /// The secret reference to the runtime role's PostgreSQL URL, which + /// `bregctl provision` reads for the role, database and password. + pub fn runtime_url_ref(&self) -> &SecretReference { + &self.runtime_url_ref + } + + /// The secret reference to the migration role's PostgreSQL URL, which + /// `bregctl provision` reads for the role, database and password. + pub fn migration_url_ref(&self) -> &SecretReference { + &self.migration_url_ref + } } impl fmt::Debug for DatabaseConfig { @@ -2189,7 +2322,7 @@ impl OidcVerifierConfig { // development and test deployments that run their issuer beside the // registry; every other issuer and key URI is `https`. raw.provider - .check("authentication.oidc", true) + .check_without_posture("authentication.oidc", true) .map_err(|_| RuntimeConfigError::InvalidOidc)?; validate_oidc_value(&raw.access_token_type)?; validate_claim_name(&raw.scope_claim)?; @@ -2391,12 +2524,14 @@ impl OidcJwksSource { JwksSource::Uri { uri } => Ok(Self::Uri { uri: uri.into_string(), }), - JwksSource::Static { document_ref } => Ok(Self::Static { - document_ref: parse_secret_reference( - document_ref, - RuntimeConfigError::InvalidOidc, - )?, - }), + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { + Ok(Self::Static { + document_ref: parse_secret_reference( + document_ref, + RuntimeConfigError::InvalidOidc, + )?, + }) + } } } @@ -2421,11 +2556,8 @@ fn validate_static_jwks( allowed_algorithm: AccessTokenAlgorithm, denied_kids: &[String], ) -> Result { - let value = parse_json_strict(bytes).map_err(|_| RuntimeConfigError::InvalidOidc)?; + let value = public_jwks_document(bytes).map_err(RuntimeConfigError::InvalidStaticJwks)?; let object = value.as_object().ok_or(RuntimeConfigError::InvalidOidc)?; - if object.len() != 1 || !object.contains_key("keys") { - return Err(RuntimeConfigError::InvalidOidc); - } let keys = object .get("keys") .and_then(Value::as_array) @@ -2433,9 +2565,8 @@ fn validate_static_jwks( if keys.is_empty() || keys.len() > MAX_LIST_ITEMS { return Err(RuntimeConfigError::InvalidOidc); } - let mut kids = HashSet::new(); for key in keys { - validate_static_jwk(key, allowed_algorithm, denied_kids, &mut kids)?; + validate_static_jwk(key, allowed_algorithm, denied_kids)?; } serde_json::from_value::(value).map_err(|_| RuntimeConfigError::InvalidOidc) } @@ -2444,10 +2575,8 @@ fn validate_static_jwk( value: &Value, allowed_algorithm: AccessTokenAlgorithm, denied_kids: &[String], - kids: &mut HashSet, ) -> Result<()> { let object = value.as_object().ok_or(RuntimeConfigError::InvalidOidc)?; - validate_static_jwk_members(object)?; validate_static_jwk_use(object)?; validate_static_jwk_key_ops(object)?; let kid = object @@ -2455,7 +2584,7 @@ fn validate_static_jwk( .and_then(Value::as_str) .ok_or(RuntimeConfigError::InvalidOidc)?; validate_bounded_list(&[kid.to_owned()])?; - if denied_kids.iter().any(|denied| denied == kid) || !kids.insert(kid.to_owned()) { + if denied_kids.iter().any(|denied| denied == kid) { return Err(RuntimeConfigError::InvalidOidc); } if object.get("alg").and_then(Value::as_str) != Some(allowed_algorithm.jwa_name()) { @@ -2479,19 +2608,6 @@ fn validate_static_jwk( Ok(()) } -fn validate_static_jwk_members(object: &Map) -> Result<()> { - const ALLOWED: &[&str] = &[ - "kty", "kid", "alg", "use", "key_ops", "crv", "x", "y", "n", "e", - ]; - if object - .keys() - .any(|member| !ALLOWED.contains(&member.as_str())) - { - return Err(RuntimeConfigError::InvalidOidc); - } - Ok(()) -} - fn validate_static_jwk_use(object: &Map) -> Result<()> { match object.get("use") { None => Ok(()), @@ -2967,7 +3083,7 @@ struct ReviewAuthorityConfig { private_key_jwt: Option, producer_id: String, recovery_days: u32, - completion: Option<(SecretReference, String)>, + completion: Option, } impl ReviewAuthorityConfig { @@ -2994,19 +3110,14 @@ impl ReviewAuthorityConfig { "endpoint must not carry user information, a query or a fragment", )); } - let completion = match (raw.completion_token_ref, raw.completion_recipient) { - (None, None) => None, - (Some(token_ref), Some(recipient)) - if crate::review_store::valid_completion_recipient(&recipient) => - { - Some((token_ref, recipient)) - } - _ => { - return Err(ReviewAuthorityRefusal( - "completionTokenRef and completionRecipient must be written together, with a recipient of 1 to 256 visible ASCII characters", - )) - } - }; + let completion = raw.completion; + if completion.as_ref().is_some_and(|completion| { + !crate::review_store::valid_completion_recipient(&completion.recipient_binding) + }) { + return Err(ReviewAuthorityRefusal( + "completion.recipientBinding must contain 1 to 256 visible ASCII characters", + )); + } let token_ref = raw.token_ref; let private_key_jwt = raw .private_key_jwt @@ -3067,18 +3178,43 @@ struct RawReviewAuthorityConfig { schemars(with = "BoundedU32<1, { crate::review_store::MAXIMUM_REVIEW_RECOVERY_DAYS }>") )] recovery_days: u32, - /// The bearer token the review authority presents when it notifies this - /// registry that a review completed. Written together with - /// `completionRecipient`; omitted, no completion notification is - /// accepted and the registry polls for results. - #[serde(default, skip_serializing_if = "Option::is_none")] - completion_token_ref: Option, - /// The logical recipient the review authority names in each completion - /// notification. Written together with `completionTokenRef`; omitted, no - /// completion notification is accepted and the registry polls for - /// results. + /// Standard Webhooks authentication for review completion notifications. + /// Omit this block to poll for results without notifications. #[serde(default, skip_serializing_if = "Option::is_none")] - completion_recipient: Option, + completion: Option, +} + +#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))] +#[derive(Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RawReviewCompletionConfig { + /// Recipient binding the completion sender supplies to select this authority. + recipient_binding: String, + /// Runtime secret reference for 32 to 64 exact HMAC-SHA-256 key bytes. + hmac_sha256_key_ref: SecretReference, + /// Optional previous completion signing key during rotation. + #[serde( + default, + deserialize_with = "present_hook_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + previous_hmac_sha256_key_ref: Option, +} + +impl RawReviewCompletionConfig { + fn resolve_keys( + &self, + resolver: &SecretResolver, + path: &str, + ) -> std::result::Result { + resolve_delivery_keys( + resolver, + path, + &self.hmac_sha256_key_ref, + self.previous_hmac_sha256_key_ref.as_ref(), + ) + } } #[derive(Clone)] @@ -4467,9 +4603,9 @@ mod tests { "exactly one of tokenRef and privateKeyJwt", ), ( - "/completionRecipient", - serde_json::json!("registry"), - "completionTokenRef and completionRecipient", + "/completion", + serde_json::json!({"recipientBinding": "registry bad", "hmacSha256KeyRef": "secret:file/completion-key"}), + "completion.recipientBinding", ), ( "/privateKeyJwt/resource", diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index 5abf5a734b..3f24d2218b 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Startup ordering gate for one verified Registry package. +pub use registry_platform_oidc::StaticJwksError; use std::collections::BTreeMap; use std::future::Future; use std::net::SocketAddr; @@ -150,6 +151,10 @@ pub enum StartupError { ExternalProjectionRoleMode, #[error("the Registry OIDC key source was refused")] Oidc, + /// The shared static key set rule refused the pinned key set. The cause + /// names the rule and the key's position, never a key value. + #[error("the Registry OIDC key source was refused")] + StaticKeySet(StaticJwksError), #[error("the Registry authentication profile was refused")] Authentication, /// The project names clients that `authentication.oidc.allowedClients` @@ -160,7 +165,7 @@ pub enum StartupError { )] AuthenticationClientsUnlisted, #[error("the Registry event destination bindings were refused")] - EventDestinations, + EventDestinations(String), #[error( "{retained_deliveries} retained hook deliveries require superseded bindings; inspect \ them with `bregctl hook list` and either restore the exact bindings or explicitly \ @@ -726,10 +731,34 @@ impl OperationalEvent { .expect("background task stop and stage refusal records have a code"); tracing::error!(target: "registry_breg::startup", code, message = record.message); } - Self::StoppedWithError(StartupError::AuditDestination(reason)) => { + Self::StoppedWithError( + StartupError::AuditDestination(reason) | StartupError::EventDestinations(reason), + ) => { + let error = record + .error + .expect("stopped-with-error records have a closed error"); + tracing::error!( + target: "registry_breg::startup", + error, + reason = reason.as_str(), + message = record.message + ); + } + Self::StoppedWithError(StartupError::RuntimeConfig( + cause @ (RuntimeConfigError::InvalidDeliveryKey { .. } + | RuntimeConfigError::DuplicateCompletionRecipient { .. }), + )) => { + let error = record + .error + .expect("stopped-with-error records have a closed error"); + let reason = cause.to_string(); + tracing::error!(target: "registry_breg::startup", error, reason, message = record.message); + } + Self::StoppedWithError(StartupError::StaticKeySet(cause)) => { let error = record .error .expect("stopped-with-error records have a closed error"); + let reason = cause.to_string(); tracing::error!( target: "registry_breg::startup", error, @@ -870,7 +899,7 @@ impl StartupError { Self::Cursor => "the Registry cursor profile was refused", Self::ExternalSources => "the external source binding list or the external projection store was refused", Self::ExternalProjectionRoleMode => "indexed external projections require separate migration and runtime PostgreSQL roles", - Self::Oidc => "the Registry OIDC key source was refused", + Self::Oidc | Self::StaticKeySet(_) => "the Registry OIDC key source was refused", Self::Authentication => "the Registry authentication profile was refused", Self::AuthenticationClientsUnlisted => { "the project names clients that authentication.oidc.allowedClients does not list; list each client named in requesterClients, trusted actors, or consent recipients there" @@ -878,7 +907,7 @@ impl StartupError { Self::AttachmentStorage => { "the Registry attachment storage or verification binding was refused" } - Self::EventDestinations => "the Registry event destination bindings were refused", + Self::EventDestinations(_) => "the Registry event destination bindings were refused", Self::RetainedHookBindings { .. } => { "retained hook deliveries require superseded bindings; run `bregctl doctor` to name the recovery" } @@ -1242,6 +1271,18 @@ pub async fn rehearse_schema_fingerprint( config: &RuntimeConfig, registry: &CompiledRegistry, ) -> Result { + measure_schema_install(config, registry) + .await + .map(|measurement| measurement.fingerprint) +} + +/// The same rehearsal as [`rehearse_schema_fingerprint`], also returning the +/// server's PostgreSQL major version, which a rehearsal receipt records. +#[cfg(all(feature = "runtime", feature = "tooling"))] +pub async fn measure_schema_install( + config: &RuntimeConfig, + registry: &CompiledRegistry, +) -> Result { validate_rehearsal_registry_binding(registry)?; let migration = config .migration_database_connection_config() @@ -1285,7 +1326,9 @@ pub async fn rehearse_schema_fingerprint_with_connection_config_for_test( migration: &crate::postgres::ConnectionConfig, ) -> Result { validate_rehearsal_registry_binding(registry)?; - rehearse_schema_fingerprint_with_connection_config(config, registry, migration).await + rehearse_schema_fingerprint_with_connection_config(config, registry, migration) + .await + .map(|measurement| measurement.fingerprint) } #[cfg(all(feature = "runtime", feature = "tooling"))] @@ -1293,7 +1336,7 @@ async fn rehearse_schema_fingerprint_with_connection_config( config: &RuntimeConfig, registry: &CompiledRegistry, migration: &crate::postgres::ConnectionConfig, -) -> Result { +) -> Result { crate::postgres::rehearse_schema_fingerprint_with_connection( migration, config.database().roles().migration(), @@ -1533,7 +1576,7 @@ async fn prepare_verified_package_with_key_source( /// refuses to start instead of interleaving entries. async fn open_registry_audit(config: &RuntimeConfig) -> Result { let profile = config.audit_profile().map_err(|_| StartupError::Audit)?; - let writer = AuditWriter::open(config.audit().destination().clone()) + let writer = AuditWriter::open_without_posture(config.audit().destination().clone()) .await .map_err(|error| StartupError::AuditDestination(error.operator_description()))?; Ok(RegistryAudit::new(profile, writer)) @@ -1566,7 +1609,7 @@ fn check_registry_audit(config: &RuntimeConfig) -> Result { .map_err(|error| StartupError::AuditDestination(error.operator_description()))?; Ok(RegistryAudit::new( profile, - AuditWriter::from_line_sink(Box::new(RefuseEveryEntry)), + AuditWriter::from_line_sink_without_posture(Box::new(RefuseEveryEntry)), )) } @@ -1681,10 +1724,16 @@ async fn finish_prepared_server( // Every verified database holds the subject access-log storage, so // retention always runs. let access_log_retention = Some((pool.clone(), Arc::::default())); + let review_authorities = config + .activate_review_authorities(®istry) + .map_err(StartupError::RuntimeConfig)?; let event_destinations = Arc::new( config - .activate_event_destinations(®istry) - .map_err(|_| StartupError::EventDestinations)?, + .activate_event_destinations_with_review_authorities( + ®istry, + review_authorities.as_deref(), + ) + .map_err(|error| StartupError::EventDestinations(error.to_string()))?, ); let authenticator = Arc::new( RegistryAuthenticator::new( @@ -1983,7 +2032,9 @@ async fn finish_prepared_server( } => StartupError::RetainedHookBindings { retained_deliveries, }, - HookRetainedBindingError::Unavailable => StartupError::EventDestinations, + HookRetainedBindingError::Unavailable => StartupError::EventDestinations( + "retained hook bindings could not be read".to_owned(), + ), })?; // The worker also owns payload expiry, so it runs even when the active // package declares no events. Compatible retained work is checked above. @@ -1992,9 +2043,6 @@ async fn finish_prepared_server( let evidence = config .activate_evidence(®istry) .map_err(StartupError::RuntimeConfig)?; - let review_authorities = config - .activate_review_authorities(®istry) - .map_err(StartupError::RuntimeConfig)?; crate::review_store::verify_retained_bindings(&pool, ®istry, review_authorities.as_deref()) .await .map_err(review_binding_startup_error)?; @@ -2288,6 +2336,7 @@ pub fn map_runtime_config_error(error: RuntimeConfigError) -> StartupError { RuntimeConfigError::InvalidAudit => StartupError::Audit, RuntimeConfigError::InvalidCursor => StartupError::Cursor, RuntimeConfigError::InvalidOidc => StartupError::Oidc, + RuntimeConfigError::InvalidStaticJwks(cause) => StartupError::StaticKeySet(cause), other => StartupError::RuntimeConfig(other), } } diff --git a/crates/registry-breg/src/task_grant.rs b/crates/registry-breg/src/task_grant.rs index 34505e881a..774a688e12 100644 --- a/crates/registry-breg/src/task_grant.rs +++ b/crates/registry-breg/src/task_grant.rs @@ -163,7 +163,7 @@ impl TaskGrantStatusClient { token: Arc, trusted_roots: Option<&[u8]>, ) -> Result { - registry_platform_oidc::task_grant::TaskGrantStatusClient::new( + registry_platform_oidc::task_grant::TaskGrantStatusClient::new_without_peer_policy( source_issuer, resource, base, diff --git a/crates/registry-breg/src/task_grant/config.rs b/crates/registry-breg/src/task_grant/config.rs index 0f008f0f78..0fbc86c3b8 100644 --- a/crates/registry-breg/src/task_grant/config.rs +++ b/crates/registry-breg/src/task_grant/config.rs @@ -29,7 +29,7 @@ impl TaskGrantStatusRegistry { resource: &str, secrets: &SecretResolver, ) -> Result { - registry_platform_oidc::task_grant::TaskGrantStatusRegistry::activate( + registry_platform_oidc::task_grant::TaskGrantStatusRegistry::activate_without_peer_policy( &endpoints(configs), resource, secrets, diff --git a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs index 4df980de14..00797af48e 100644 --- a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs +++ b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs @@ -52,6 +52,44 @@ fn prospective_row_boundary_refusal_is_documented_only_where_it_can_apply() { assert_eq!(example["title"], "Forbidden"); } +#[test] +fn availability_response_admits_a_bounded_guard_label_beside_its_reason() { + let registry = compiled_asset_result_action_registry(); + let action = registry + .actions() + .actions + .iter() + .find(|action| action.id == "register-asset") + .unwrap(); + let schema = inline_validator(&super::openapi_action_availability_response_schema(action)); + let unavailable = |members: Value| { + let mut availability = json!({ + "available": false, "observedRevision": 3, + "reason": "guard-not-satisfied", "recovery": "none" + }); + for (key, value) in members.as_object().unwrap() { + availability[key] = value.clone(); + } + json!({"availability": availability}) + }; + assert_valid(&schema, &unavailable(json!({}))); + assert_valid( + &schema, + &unavailable( + json!({"guardReason": "not-submitted", "guardLabel": "Only a submitted application can be approved."}), + ), + ); + assert_invalid(&schema, &unavailable(json!({"guardLabel": ""}))); + assert_invalid( + &schema, + &unavailable(json!({"guardLabel": "a".repeat(257)})), + ); + assert_invalid( + &schema, + &json!({"availability": {"available": true, "observedRevision": 3, "guardLabel": "Misplaced."}}), + ); +} + #[test] fn write_outside_boundary_problem_is_exact_and_does_not_narrow_located_problems() { let schema = inline_validator(&super::problem_schema()); diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs new file mode 100644 index 0000000000..4f20df74ce --- /dev/null +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -0,0 +1,1011 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every authentication refusal answers with the fixed 401 problem, counts +//! once under `breg_request_refusals_total{check}`, and writes one value-free +//! `request refused` line that names the check. +//! +//! The recorder is process-wide and admits five log lines per check per +//! minute, so this file drives every case from one test and keeps each check +//! under that bound. +//! +//! `tests/golden/authentication_refusals.json` freezes the status, the +//! headers that matter and the body (minus `traceId`) of each answer. +//! `REGISTRY_BREG_WRITE_GOLDEN=1` rewrites it. A change to the file in a +//! review is a change to a public response. + +#![cfg(feature = "runtime")] + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::body::{to_bytes, Body}; +use axum::http::header::AUTHORIZATION; +use axum::http::{HeaderValue, Request}; +use jsonwebtoken::jwk::JwkSet; +use jsonwebtoken::Algorithm; +use registry_breg::api::{ + authenticated_router, router, HeldReadResponse, HttpService, ReadRuntimeIdentity, + ReadServiceError, ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthorityClaimConfig, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; +use registry_breg::postgres::{ConnectionConfig, PoolBounds}; +use registry_breg::review_store::{ + ReviewAuthorityClient, ReviewAuthorityRegistry, ReviewCompletionReceiver, +}; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{ClaimNames, JwksFetcher, JwksFetcherConfig, TokenVerifierConfig}; +use registry_platform_testing::{ + fixtures, oidc_verifier_config, sign_ed25519_compact_jwt, MockIdp, +}; +use registry_review_client::{ReviewClient, ReviewClientConfig}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber; +use zeroize::Zeroizing; + +const AUDIENCE: &str = "urn:example:breg"; +const PRINCIPAL: &str = "principal-value-never-rendered"; +const ACTOR_ID: &str = "00000000-0000-4000-8000-0000000000aa"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GOLDEN: &str = "tests/golden/authentication_refusals.json"; + +const PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: refusal-recording, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + public: + default: true + principalClaim: registry_principal + requiredScopes: [registry.read] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} +"#; + +const CONTEXTUAL_PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: refusal-recording-contextual, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + standing-agent: + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [citizen-self-service] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + delegated-agent: + default: true + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [record-review] + taskGrant: {sourceIssuer: https://casework.example} + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: + - {field: tenant, claim: tenant_claim, operator: equals} +"#; + +struct EmptyReads; + +impl RecordReadService for EmptyReads { + fn get( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("fixture serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} + +fn compiled(source: &str) -> Arc { + let project = parse_project_yaml(source.as_bytes()).expect("project parses"); + Arc::new(compile_project(&project, &[], CompileProfile::Authoring).expect("project compiles")) +} + +fn service(registry: Arc) -> HttpService { + HttpService::new( + registry, + ReadRuntimeIdentity { + package_revision: "package-refusal-test".to_owned(), + schema_fingerprint: "schema-refusal-test".to_owned(), + }, + Arc::new(EmptyReads), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("test cursor key is valid"), + ), + ) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_secs() +} + +fn key_source(idp: &MockIdp) -> Arc { + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )) +} + +struct Harness { + app: axum::Router, + idp: MockIdp, +} + +impl Harness { + async fn plain() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let authenticator = RegistryAuthenticator::new( + ®istry, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + key_source(&idp), + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + /// A harness whose key source cannot be reached: the issuer's key set URL + /// names a loopback port nothing listens on. + async fn key_source_outage() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let unreachable = Arc::new(JwksFetcher::new_with_fetch_url_policy( + "http://127.0.0.1:9/jwks.json".to_owned(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )); + let authenticator = RegistryAuthenticator::new( + ®istry, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + unreachable, + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + async fn contextual() -> Self { + let registry = compiled(CONTEXTUAL_PROJECT); + let idp = MockIdp::start().await; + let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); + verifier.allowed_clients = vec!["agent-client".to_owned()]; + let claims = AuthorityClaimConfig::new("sub", Some("registry_purpose".to_owned())) + .with_contextual_claims( + ClaimNames::default(), + BTreeMap::from([("agent-client".to_owned(), ACTOR_ID.to_owned())]), + ); + let authenticator = + RegistryAuthenticator::new(®istry, verifier, key_source(&idp), claims) + .expect("contextual authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + fn signed(&self, mut claims: Value, kid: &str) -> String { + let now = unix_now(); + let object = claims.as_object_mut().expect("claims are an object"); + object + .entry("iss") + .or_insert_with(|| json!(self.idp.issuer())); + object.entry("iat").or_insert_with(|| json!(now)); + object.entry("nbf").or_insert_with(|| json!(now)); + object.entry("exp").or_insert_with(|| json!(now + 900)); + sign_ed25519_compact_jwt(fixtures::ED25519_PRIVATE_JWK, "JWT", kid, claims) + } + + fn token(&self, claims: Value) -> String { + self.signed(claims, "registry-platform-testing-ed25519-1") + } +} + +fn valid_claims() -> Value { + json!({ + "aud": AUDIENCE, + "registry_actor_kind": "service", + "registry_principal": PRINCIPAL, + "scope": "registry.read", + }) +} + +fn delegated_grant_claims(now: u64) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "registry_principal": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "record-review", + "request_purpose": "record-review", + "registry_grant_id": "00000000-0000-4000-8000-0000000000bf", + "registry_approver": "h:synthetic-approver", + "registry_grant_source_issuer": "https://casework.example", + "registry_grant_client": "agent-client", + "registry_grant_resource": AUDIENCE, + "registry_grant_exp": now + 600, + "registry_grant_bounds": {"type":"breg","permissions":[{"collection":"cases","operations":["get"]}]}, + "identity": {"tenant_claim": "tenant-from-approved-identity"} + }) +} + +fn standing_agent_claims(act: Value) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "citizen-self-service", + "act": act + }) +} + +fn read_request(path: &str, authorization: &[&str]) -> Request { + let mut request = Request::builder() + .uri(path) + .body(Body::empty()) + .expect("request"); + for value in authorization { + request.headers_mut().append( + AUTHORIZATION, + HeaderValue::from_str(value).expect("header value"), + ); + } + request +} + +fn completion_keys(byte: u8) -> registry_platform_crypto::delivery_signature::DeliveryKeys { + use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; + DeliveryKeys::new(DeliveryKey::new(&[byte; 32]).unwrap(), None).unwrap() +} + +fn completion_request(key: Option, recipient: Option<&str>, offset: i64) -> Request { + let event = "00000000-0000-4000-8000-000000000001"; + let timestamp = (chrono::Utc::now().timestamp() + offset) as u64; + let body = b"{}"; + let mut builder = Request::builder() + .method("POST") + .uri("/v1/review-completions") + .header("webhook-id", event) + .header("webhook-timestamp", timestamp.to_string()); + if let Some(recipient) = recipient { + builder = builder.header("registry-recipient-binding", recipient); + } + if let Some(key) = key { + let signature = registry_platform_crypto::delivery_signature::sign( + &completion_keys(key), + event, + timestamp, + body, + ) + .unwrap(); + builder = builder.header("webhook-signature", signature); + } + builder + .body(Body::from(body.as_slice())) + .expect("completion request") +} + +/// The review-completion router: a receiver with one authority and a pool +/// that never connects. +fn completion_app() -> axum::Router { + let registry = compiled(PROJECT); + let authenticator = Arc::new( + RegistryAuthenticator::new( + ®istry, + TokenVerifierConfig::access_token_profile( + "https://issuer.example.test", + vec![AUDIENCE.to_owned()], + vec![Algorithm::EdDSA], + vec!["at+jwt".to_owned()], + ), + Arc::new(JwksFetcher::new_static( + JwkSet { keys: Vec::new() }, + JwksFetcherConfig::defaults(), + )), + AuthorityClaimConfig::new("registry_principal", None), + ) + .expect("authentication config is valid"), + ); + let bounds = PoolBounds::new( + 1, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(50), + ) + .expect("pool bounds are valid"); + let certificate = rcgen::generate_simple_self_signed(vec!["db.example.invalid".to_owned()]) + .expect("test CA is valid"); + let pool = ConnectionConfig::require_tls_with_custom_ca( + "postgresql://registry_runtime@db.example.invalid/registry", + certificate.cert.der(), + bounds, + ) + .expect("test connection configuration is valid") + .build_pool() + .expect("test pool builds"); + let review_client = ReviewClient::new(ReviewClientConfig::new( + "https://review.example.invalid/" + .parse() + .expect("reserved HTTPS URL"), + )) + .expect("review client builds"); + let authority = Arc::new( + ReviewAuthorityClient::new( + "casework-a".to_owned(), + review_client, + Arc::new( + registry_platform_httputil::StaticToken::new("outgoing-token".to_owned()) + .expect("outgoing token is valid"), + ), + "producer-profile".to_owned(), + "producer-a".to_owned(), + 7, + Some(completion_keys(b'k')), + Some("registry-a".to_owned()), + ) + .expect("review authority is valid"), + ); + let authorities = Arc::new( + ReviewAuthorityRegistry::new(BTreeMap::from([("casework-a".to_owned(), authority)])) + .expect("review authority registry is valid"), + ); + let receiver = Arc::new(ReviewCompletionReceiver::new(pool, authorities)); + let service = Arc::new(service(registry).with_review_completions(receiver)); + authenticated_router(service, authenticator) +} + +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl std::io::Write for CapturedLogs { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 + .lock() + .expect("captured log buffer") + .extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { + type Writer = Self; + + fn make_writer(&'writer self) -> Self::Writer { + self.clone() + } +} + +impl CapturedLogs { + fn subscriber(&self) -> tracing::Dispatch { + let writer = self.clone(); + tracing::Dispatch::new( + tracing_subscriber::fmt() + .json() + .without_time() + .with_ansi(false) + .with_writer(writer) + .finish(), + ) + } + + fn events(&self) -> Vec { + let bytes = self.0.lock().expect("captured log buffer").clone(); + String::from_utf8(bytes) + .expect("log lines are UTF-8") + .lines() + .map(|line| serde_json::from_str(line).expect("JSON log line")) + .collect() + } +} + +/// The counter, read the way an operator reads it: from the metrics listener. +async fn refusal_counts() -> BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + let text = String::from_utf8(bytes.to_vec()).expect("metrics are UTF-8"); + let mut counts = BTreeMap::new(); + for line in text.lines() { + if let Some(rest) = line.strip_prefix("breg_request_refusals_total{check=\"") { + let (label, value) = rest.split_once("\"} ").expect("sample line"); + counts.insert(label.to_owned(), value.parse().expect("counter value")); + } + } + counts +} + +struct Observed { + name: &'static str, + expected_check: &'static str, + answer: Value, + counted: BTreeMap, + refusal_lines: Vec, + log_text: String, +} + +async fn observe( + name: &'static str, + expected_check: &'static str, + app: &axum::Router, + request: Request, +) -> Observed { + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + let response = app + .clone() + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + let after = refusal_counts().await; + let status = response.status().as_u16(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let content_type = header("content-type"); + let cache_control = header("cache-control"); + let www_authenticate = header("www-authenticate"); + let retry_after = header("retry-after"); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("response body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("problem body is JSON"); + assert!( + body.as_object_mut() + .expect("problem body is an object") + .remove("traceId") + .is_some_and(|trace| trace.as_str().is_some_and(|id| id.len() == 32)), + "{name}: the problem carries the request trace id" + ); + let counted = after + .iter() + .filter_map(|(label, value)| { + let delta = value - before.get(label).copied().unwrap_or(0); + (delta > 0).then(|| (label.clone(), delta)) + }) + .collect(); + let events = captured.events(); + let log_text = events.iter().map(Value::to_string).collect::(); + let refusal_lines = events + .into_iter() + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + Observed { + name, + expected_check, + answer: json!({ + "status": status, + "contentType": content_type, + "cacheControl": cache_control, + "wwwAuthenticate": www_authenticate, + "retryAfter": retry_after, + "body": body, + }), + counted, + refusal_lines, + log_text, + } +} + +#[tokio::test] +async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire() { + let record = format!("/v1/records/cases/{RECORD_ID}"); + let mut observed = Vec::new(); + + let plain = Harness::plain().await; + let valid = plain.idp.mint_token(valid_claims()); + // Change a character in the middle of the signature. The last character + // of a base64url Ed25519 signature carries padding bits, so changing it + // can make the token fail to decode instead of failing the signature. + let mut tampered = valid.clone(); + let position = tampered.len() - 10; + let replacement = if &valid[position..=position] == "A" { + "B" + } else { + "A" + }; + tampered.replace_range(position..=position, replacement); + let now = unix_now(); + let mut wrong_audience = valid_claims(); + wrong_audience["aud"] = json!("urn:example:another-resource"); + let mut expired = valid_claims(); + expired["iat"] = json!(now - 7200); + expired["nbf"] = json!(now - 7200); + expired["exp"] = json!(now - 3600); + let mut wrong_issuer = valid_claims(); + wrong_issuer["iss"] = json!("https://issuer-canary.example.test"); + let mut no_actor_kind = valid_claims(); + no_actor_kind + .as_object_mut() + .expect("claims are an object") + .remove("registry_actor_kind"); + let mut object_principal = valid_claims(); + object_principal["registry_principal"] = json!({"value": PRINCIPAL}); + let mut malformed_actor_kind = valid_claims(); + malformed_actor_kind["registry_actor_kind"] = json!(["service"]); + let bearer = |token: &str| format!("Bearer {token}"); + + for (name, check, request) in [ + ( + "no-authorization-header", + "credential-missing", + read_request(&record, &[]), + ), + ( + "basic-scheme", + "credential-missing", + read_request(&record, &["Basic canary-basic-secret"]), + ), + ( + "repeated-authorization-header", + "credential-malformed", + read_request( + &record, + &["Bearer canary-one.two.three", "Bearer canary-four.five.six"], + ), + ), + ( + "double-space-separator", + "credential-malformed", + read_request(&record, &["Bearer canary-double-space"]), + ), + ( + "token-not-compact", + "credential-malformed", + read_request(&record, &["Bearer canary-not-compact"]), + ), + ( + "tampered-signature", + "token-signature", + read_request(&record, &[&bearer(&tampered)]), + ), + ( + "wrong-audience", + "token-audience", + read_request(&record, &[&bearer(&plain.token(wrong_audience))]), + ), + ( + "expired-token", + "token-time", + read_request(&record, &[&bearer(&plain.token(expired))]), + ), + ( + "unknown-key-id", + "token-key", + read_request( + &record, + &[&bearer(&plain.signed(valid_claims(), "kid-canary-unknown"))], + ), + ), + ( + "wrong-issuer", + "token-issuer", + read_request(&record, &[&bearer(&plain.token(wrong_issuer))]), + ), + ( + "missing-actor-kind", + "actor-kind", + read_request(&record, &[&bearer(&plain.token(no_actor_kind))]), + ), + ( + "actor-kind-is-not-a-string", + "actor-kind", + read_request(&record, &[&bearer(&plain.token(malformed_actor_kind))]), + ), + ( + "token-type-is-not-admitted", + "token-type", + read_request( + &record, + &[&bearer(&sign_ed25519_compact_jwt( + fixtures::ED25519_PRIVATE_JWK, + "canary+type", + "registry-platform-testing-ed25519-1", + { + let mut claims = valid_claims(); + claims["iss"] = json!(plain.idp.issuer()); + claims["iat"] = json!(now); + claims["nbf"] = json!(now); + claims["exp"] = json!(now + 900); + claims + }, + ))], + ), + ), + ( + "principal-claim-is-an-object", + "token-claims", + read_request(&record, &[&bearer(&plain.token(object_principal))]), + ), + ] { + observed.push(observe(name, check, &plain.app, request).await); + } + + // The low-level router has no bearer layer, so a route that reads claims + // finds none. + let unauthenticated = router(Arc::new(service(compiled(PROJECT)))); + observed.push( + observe( + "extractor-without-authentication-context", + "credential-missing", + &unauthenticated, + read_request("/v1/registry", &[]), + ) + .await, + ); + + let contextual = Harness::contextual().await; + let agent_path = format!("{record}?accessProfile=standing-agent"); + let grant_path = format!("{record}?accessProfile=delegated-agent"); + let untrusted_actor = contextual.token(standing_agent_claims( + json!({"sub": "00000000-0000-4000-8000-0000000000ff", "iss": contextual.idp.issuer()}), + )); + let mut actor_without_client = + standing_agent_claims(json!({"sub": ACTOR_ID, "iss": contextual.idp.issuer()})); + actor_without_client + .as_object_mut() + .expect("claims are an object") + .remove("azp"); + let act_not_an_object = contextual.token(standing_agent_claims(json!("not-an-object"))); + let mut long_grant = delegated_grant_claims(now); + long_grant["iat"] = json!(now); + long_grant["exp"] = json!(now + 901); + let mut partial_grant = delegated_grant_claims(now); + partial_grant["iat"] = json!(now); + partial_grant["exp"] = json!(now + 600); + partial_grant["registry_grant_bounds"] = json!("not-an-object"); + let mut expired_grant = delegated_grant_claims(now); + expired_grant["registry_grant_exp"] = json!(now - 1); + let mut other_client_grant = delegated_grant_claims(now); + other_client_grant["registry_grant_client"] = json!("other-client"); + let mut other_resource_grant = delegated_grant_claims(now); + other_resource_grant["registry_grant_resource"] = json!("urn:example:other-resource"); + let mut future_issued_grant = delegated_grant_claims(now); + future_issued_grant["iat"] = json!(now + 600); + future_issued_grant["nbf"] = json!(now); + future_issued_grant["exp"] = json!(now + 1200); + for (name, check, request) in [ + ( + "actor-is-not-the-trusted-actor", + "delegation", + read_request(&agent_path, &[&bearer(&untrusted_actor)]), + ), + ( + "act-claim-is-not-an-object", + "delegation", + read_request(&agent_path, &[&bearer(&act_not_an_object)]), + ), + ( + "actor-without-a-matched-client", + "token-client", + read_request( + &agent_path, + &[&bearer(&contextual.token(actor_without_client))], + ), + ), + ( + "task-grant-token-issued-for-too-long", + "task-grant-lifetime", + read_request(&grant_path, &[&bearer(&contextual.token(long_grant))]), + ), + ( + "task-grant-claims-malformed", + "task-grant-claims", + read_request(&grant_path, &[&bearer(&contextual.token(partial_grant))]), + ), + ( + "task-grant-expired", + "task-grant-expired", + read_request(&grant_path, &[&bearer(&contextual.token(expired_grant))]), + ), + ( + "task-grant-bound-to-another-client", + "task-grant-binding", + read_request( + &grant_path, + &[&bearer(&contextual.token(other_client_grant))], + ), + ), + ( + "task-grant-bound-to-another-resource", + "task-grant-binding", + read_request( + &grant_path, + &[&bearer(&contextual.token(other_resource_grant))], + ), + ), + ( + "task-grant-token-issued-in-the-future", + "task-grant-claims", + read_request( + &grant_path, + &[&bearer(&contextual.token(future_issued_grant))], + ), + ), + ] { + observed.push(observe(name, check, &contextual.app, request).await); + } + + let outage = Harness::key_source_outage().await; + let outage_token = outage.token(valid_claims()); + observed.push( + observe( + "key-source-unreachable", + "key-source-unavailable", + &outage.app, + read_request(&record, &[&bearer(&outage_token)]), + ) + .await, + ); + + let completions = completion_app(); + let mut repeated = completion_request(Some(b'k'), Some("registry-a"), 0); + repeated.headers_mut().append( + "webhook-signature", + HeaderValue::from_static("v1,canary-second-header"), + ); + let mut malformed = completion_request(Some(b'k'), Some("registry-a"), 0); + malformed.headers_mut().insert( + "webhook-timestamp", + HeaderValue::from_static("malformed-timestamp-canary"), + ); + for (name, check, request) in [ + ( + "review-completion-without-signature", + "delivery-signature", + completion_request(None, Some("registry-a"), 0), + ), + ( + "review-completion-with-two-signatures", + "delivery-signature", + repeated, + ), + ( + "review-completion-without-recipient", + "delivery-signature", + completion_request(Some(b'k'), None, 0), + ), + ( + "review-completion-wrong-key", + "delivery-signature", + completion_request(Some(b'x'), Some("registry-a"), 0), + ), + ( + "review-completion-wrong-recipient", + "delivery-signature", + completion_request(Some(b'k'), Some("wrong-recipient-canary"), 0), + ), + ( + "review-completion-expired-signature", + "delivery-freshness", + completion_request(Some(b'k'), Some("registry-a"), -301), + ), + ( + "review-completion-malformed-timestamp", + "delivery-freshness", + malformed, + ), + ] { + observed.push(observe(name, check, &completions, request).await); + } + + // The answers, frozen. + let answers: BTreeMap<&str, &Value> = observed + .iter() + .map(|case| (case.name, &case.answer)) + .collect(); + let golden_path = format!("{}/{GOLDEN}", env!("CARGO_MANIFEST_DIR")); + if std::env::var_os("REGISTRY_BREG_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("answers serialize"); + text.push('\n'); + std::fs::write(&golden_path, text).expect("golden file is writable"); + } else { + let frozen: Value = serde_json::from_str( + &std::fs::read_to_string(&golden_path).expect("golden file exists"), + ) + .expect("golden file is JSON"); + assert_eq!( + serde_json::to_value(&answers).expect("answers serialize"), + frozen, + "an authentication refusal changed on the wire" + ); + } + + // The recording: one count, one line, no caller value. + let mut used: BTreeSet<&str> = BTreeSet::new(); + for case in &observed { + used.insert(case.expected_check); + assert_eq!( + case.counted, + BTreeMap::from([(case.expected_check.to_owned(), 1)]), + "{}: the refusal counts once under its check", + case.name + ); + assert_eq!( + case.refusal_lines.len(), + 1, + "{}: one refusal line", + case.name + ); + let line = &case.refusal_lines[0]; + assert_eq!(line["level"], "INFO", "{}", case.name); + let fields = line["fields"].as_object().expect("line fields"); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.expected_check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + assert!( + fields["trace_id"] + .as_str() + .is_some_and(|id| id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())), + "{}: the line carries the request trace id", + case.name + ); + let keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); + assert_eq!( + keys, + BTreeSet::from([ + "decision", + "failed_check", + "message", + "suppressed", + "trace_id" + ]), + "{}: the line carries only the fixed fields", + case.name + ); + for canary in [ + "canary", + PRINCIPAL, + "agent-client", + "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "registry-a", + "Bearer", + ] { + assert!( + !case.log_text.contains(canary) && !case.answer.to_string().contains(canary), + "{}: the refusal exposed a canary value", + case.name + ); + } + } + assert!( + used.len() >= 14, + "the cases cover every authentication check" + ); + + // The shared malformed-token corpus goes through the router. The counter + // has no budget, so every token counts once under `credential-malformed`, + // whatever the log line budget admits. + let corpus = registry_platform_testing::malformed_access_token_fixtures(); + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + for token in &corpus { + let response = plain + .app + .clone() + .oneshot(read_request(&record, &[&bearer(token)])) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + assert_eq!(response.status().as_u16(), 401); + } + let after = refusal_counts().await; + let counted = |label: &str| { + after.get(label).copied().unwrap_or(0) - before.get(label).copied().unwrap_or(0) + }; + assert_eq!( + counted("credential-malformed"), + u64::try_from(corpus.len()).expect("corpus length fits"), + "each malformed token counts once" + ); + // The line budget is shared with the cases above, so the corpus writes + // exactly the lines they left: none once they have spent it. The log is + // still searched, because anything else the corpus logged must be value-free. + let spent = observed + .iter() + .filter(|case| case.expected_check == "credential-malformed") + .count(); + let events = captured.events(); + let refusal_lines = events + .iter() + .filter(|event| event["fields"]["message"] == "request refused") + .count(); + assert_eq!( + refusal_lines, + (registry_platform_authcommon::REFUSAL_LOG_LINES_PER_WINDOW as usize).saturating_sub(spent), + "the corpus writes the refusal lines the budget admits" + ); + let log_text = events.iter().map(Value::to_string).collect::(); + assert!(!log_text.contains("canary"), "the corpus reached the log"); +} diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index 8154a650c5..1d3f2a65a0 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -82,6 +82,8 @@ //! `attachment.content-type`, `attachment.digest-mismatch` and //! `attachment.slot-write-once` in the generated Problem schema likewise move //! artifact revisions only. SQL and Action fingerprints stay fixed. +//! The Standard Webhooks review completion contract changes the OpenAPI +//! document and artifact revisions. The SQL and Action pins stay fixed. use registry_breg::compiler::{compile_project, CompileProfile}; use registry_breg::contract::{parse_module_yaml, parse_project_yaml}; @@ -104,7 +106,7 @@ const FIXTURES: &[Fixture] = &[ ), module: None, ddl_sha256: "6d6431e3e4fb3eb254ef8f3b2e895aed2c09ed4ee7ca506627e1d063359f4578", - revision: "sha256:08f60d4a781ad80f957579927f703668a9a60fd75ff66533ba11e0137e157ea1", + revision: "sha256:a2731a8488f0a4fb38ac83b4653edada05e32f4c1a4e3bf95a2a790b4e18a4ac", }, Fixture { name: "asset-registration-actions", @@ -115,7 +117,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/asset-registration-actions/modules/asset-registration-actions-core/module.yaml" )), ddl_sha256: "43acdae956eb2f932fb22a2cccc5cee5ed19cf806f2f28bbc677eff219d00b99", - revision: "sha256:49ca49a8d3c42e51d6e87e6c2a4cf3b48912ba643182e2333f948bdbb6330d52", + revision: "sha256:93430c7ee130dec712b266657489c4696b081e949d758c276e5477fa8659fa6a", }, Fixture { name: "facility-registry-actions", @@ -126,7 +128,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/facility-registry-actions/modules/facility-registry-actions-core/module.yaml" )), ddl_sha256: "6439a877ee6508b999a77242542695d8ccddc6d80518699d90eddc32b305780b", - revision: "sha256:b2b2a04f66dc65e9144b4b77099953572e3e16d8e94446dbfcb47954c31f7667", + revision: "sha256:2fef99b05394908da9264987e29022231853386ef6df8b6461fcd459d7016c66", }, Fixture { name: "household-contact-actions", @@ -137,7 +139,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/household-contact-actions/modules/household-contact-actions-core/module.yaml" )), ddl_sha256: "f82f2f8376df97fb184c04d31c8e42c291f7a03dbd909828e1bf61612106de35", - revision: "sha256:80a558305edc78b5db62bac2eb75c078994aad4a518b1f6f8eed1d235a226717", + revision: "sha256:1d71b28f2d3483c6304c01ee6a683b6cd2b2b6b5190a8b672e3a9430fafcb13d", }, ]; diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index 366e558870..db88606381 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -3180,6 +3180,7 @@ fn all_acceptance_fixtures_compile_manifest_projection_under_production() { dependencies: Vec::new(), functions: Vec::new(), value_types: Default::default(), + row_boundary_sets: Default::default(), entities: Vec::new(), extend_entities: Vec::new(), actions: Vec::new(), @@ -6233,6 +6234,20 @@ fn generated_openapi_routes_and_physical_names_share_one_compiled_inventory() { assert_eq!(generated_compiled_operation_ids, compiled_operation_ids); let review_completion = &value["paths"]["/v1/review-completions"]["post"]; assert_eq!(review_completion["operationId"], "receiveReviewCompletion"); + assert_eq!( + review_completion["security"], + json!([{"reviewCompletion": []}]) + ); + assert_eq!( + value["components"]["securitySchemes"]["reviewCompletion"]["name"], + "webhook-signature" + ); + assert_eq!(review_completion["parameters"].as_array().unwrap().len(), 4); + assert_eq!( + review_completion["responses"]["401"]["headers"]["WWW-Authenticate"]["schema"]["const"], + r#"Registry-Signature scheme="standard-webhooks", version="v1""# + ); + assert!(review_completion["responses"].get("413").is_some()); assert!(review_completion.get("x-registry-recordType").is_none()); assert_eq!( value["components"]["securitySchemes"]["bearerAuth"], diff --git a/crates/registry-breg/tests/concealment_refusals.rs b/crates/registry-breg/tests/concealment_refusals.rs new file mode 100644 index 0000000000..ac86c35725 --- /dev/null +++ b/crates/registry-breg/tests/concealment_refusals.rs @@ -0,0 +1,661 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every concealed read refusal answers with the fixed 404 problem, counts +//! once under `breg_request_refusals_total{check}`, and writes one value-free +//! `request refused` line that names the check. +//! +//! The recorder is process-wide and admits five log lines per check per +//! minute, so this file drives every case from one test and keeps each check +//! under that bound. +//! +//! `tests/golden/concealment_refusals.json` freezes the status, the headers +//! that matter and the body (minus `traceId`) of each answer. +//! `REGISTRY_BREG_WRITE_GOLDEN=1` rewrites it. A change to the file in a +//! review is a change to a public response. + +#![cfg(feature = "runtime")] + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::body::{to_bytes, Body}; +use axum::http::header::AUTHORIZATION; +use axum::http::{HeaderValue, Request}; +use registry_breg::api::{ + authenticated_router, HeldReadResponse, HttpService, ReadRuntimeIdentity, ReadServiceError, + ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthorityClaimConfig, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{ClaimNames, JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{ + fixtures, oidc_verifier_config, sign_ed25519_compact_jwt, MockIdp, +}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber; +use zeroize::Zeroizing; + +const AUDIENCE: &str = "urn:example:breg"; +const PRINCIPAL: &str = "principal-value-never-rendered"; +const ACTOR_ID: &str = "00000000-0000-4000-8000-0000000000aa"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GOLDEN: &str = "tests/golden/concealment_refusals.json"; + +const PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: concealment-recording, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + - {id: tenant, type: string, required: true, maximumLength: 100, classification: internal} +datasets: + test-dataset: {} + +accessProfiles: + reader: + default: true + principalClaim: sub + requiredScopes: [registry.read] + permissions: + records: + - {recordType: case, operations: [get, list], readableFields: [label], rowBoundaries: unrestricted} + purposeful: + principalClaim: sub + requiredScopes: unrestricted + requiredPurposes: [record-review] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + human-only: + principalClaim: sub + requiredScopes: unrestricted + actorKind: human + requesterClients: [human-client] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + client-bound: + principalClaim: sub + requiredScopes: unrestricted + actorKind: service + requesterClients: [agent-client] + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} + tenant-bound: + principalClaim: sub + requiredScopes: unrestricted + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: + - {field: tenant, claim: tenant_claim, operator: equals} + granted: + principalClaim: sub + requiredScopes: unrestricted + actorKind: agent + requesterClients: [agent-client] + requiredPurposes: [record-review] + taskGrant: {sourceIssuer: https://casework.example} + permissions: + records: + - {recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted} +"#; + +struct EmptyReads; + +impl RecordReadService for EmptyReads { + fn get( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("fixture serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} + +fn compiled(source: &str) -> Arc { + let project = parse_project_yaml(source.as_bytes()).expect("project parses"); + Arc::new(compile_project(&project, &[], CompileProfile::Authoring).expect("project compiles")) +} + +fn service(registry: Arc) -> HttpService { + HttpService::new( + registry, + ReadRuntimeIdentity { + package_revision: "package-refusal-test".to_owned(), + schema_fingerprint: "schema-refusal-test".to_owned(), + }, + Arc::new(EmptyReads), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("test cursor key is valid"), + ), + ) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_secs() +} + +fn key_source(idp: &MockIdp) -> Arc { + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )) +} + +struct Harness { + app: axum::Router, + idp: MockIdp, +} + +impl Harness { + async fn start() -> Self { + let registry = compiled(PROJECT); + let idp = MockIdp::start().await; + let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); + verifier.allowed_clients = vec![ + "agent-client".to_owned(), + "other-client".to_owned(), + "human-client".to_owned(), + ]; + let claims = AuthorityClaimConfig::new("sub", Some("registry_purpose".to_owned())) + .with_contextual_claims( + ClaimNames::default(), + BTreeMap::from([("agent-client".to_owned(), ACTOR_ID.to_owned())]), + ); + let authenticator = + RegistryAuthenticator::new(®istry, verifier, key_source(&idp), claims) + .expect("authentication config is valid"); + let app = authenticated_router(Arc::new(service(registry)), Arc::new(authenticator)); + Self { app, idp } + } + + fn token(&self, mut claims: Value) -> String { + let now = unix_now(); + let object = claims.as_object_mut().expect("claims are an object"); + object + .entry("iss") + .or_insert_with(|| json!(self.idp.issuer())); + object.entry("iat").or_insert_with(|| json!(now)); + object.entry("nbf").or_insert_with(|| json!(now)); + object.entry("exp").or_insert_with(|| json!(now + 900)); + sign_ed25519_compact_jwt( + fixtures::ED25519_PRIVATE_JWK, + "JWT", + "registry-platform-testing-ed25519-1", + claims, + ) + } +} + +fn service_claims() -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "service", + "scope": "registry.read", + }) +} + +fn with(mut claims: Value, key: &str, value: Value) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .insert(key.to_owned(), value); + claims +} + +fn without(mut claims: Value, key: &str) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .remove(key); + claims +} + +fn grant_claims(now: u64) -> Value { + json!({ + "aud": AUDIENCE, + "sub": PRINCIPAL, + "registry_principal": PRINCIPAL, + "azp": "agent-client", + "registry_actor_kind": "agent", + "registry_purpose": "record-review", + "request_purpose": "record-review", + "registry_grant_id": "00000000-0000-4000-8000-0000000000bf", + "registry_approver": "h:synthetic-approver", + "registry_grant_source_issuer": "https://casework.example", + "registry_grant_client": "agent-client", + "registry_grant_resource": AUDIENCE, + "registry_grant_exp": now + 600, + "registry_grant_bounds": {"type":"breg","permissions":[{"collection":"cases","operations":["get"]}]}, + "identity": {"tenant_claim": "tenant-from-approved-identity"}, + }) +} + +fn read_request(path: &str, token: Option<&str>) -> Request { + let mut request = Request::builder() + .uri(path) + .body(Body::empty()) + .expect("request"); + if let Some(token) = token { + request.headers_mut().append( + AUTHORIZATION, + HeaderValue::from_str(&format!("Bearer {token}")).expect("header value"), + ); + } + request +} + +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl std::io::Write for CapturedLogs { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 + .lock() + .expect("captured log buffer") + .extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { + type Writer = Self; + + fn make_writer(&'writer self) -> Self::Writer { + self.clone() + } +} + +impl CapturedLogs { + fn subscriber(&self) -> tracing::Dispatch { + let writer = self.clone(); + tracing::Dispatch::new( + tracing_subscriber::fmt() + .json() + .without_time() + .with_ansi(false) + .with_writer(writer) + .finish(), + ) + } + + fn events(&self) -> Vec { + let bytes = self.0.lock().expect("captured log buffer").clone(); + String::from_utf8(bytes) + .expect("log lines are UTF-8") + .lines() + .map(|line| serde_json::from_str(line).expect("JSON log line")) + .collect() + } +} + +/// The counter, read the way an operator reads it: from the metrics listener. +async fn refusal_counts() -> BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + let text = String::from_utf8(bytes.to_vec()).expect("metrics are UTF-8"); + let mut counts = BTreeMap::new(); + for line in text.lines() { + if let Some(rest) = line.strip_prefix("breg_request_refusals_total{check=\"") { + let (label, value) = rest.split_once("\"} ").expect("sample line"); + counts.insert(label.to_owned(), value.parse().expect("counter value")); + } + } + counts +} + +struct Observed { + name: &'static str, + expected_check: &'static str, + answer: Value, + counted: BTreeMap, + refusal_lines: Vec, + log_text: String, +} + +async fn observe( + name: &'static str, + expected_check: &'static str, + app: &axum::Router, + request: Request, +) -> Observed { + let captured = CapturedLogs::default(); + let before = refusal_counts().await; + let response = app + .clone() + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("router responds"); + let after = refusal_counts().await; + let status = response.status().as_u16(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let content_type = header("content-type"); + let cache_control = header("cache-control"); + let www_authenticate = header("www-authenticate"); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("response body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("problem body is JSON"); + assert!( + body.as_object_mut() + .expect("problem body is an object") + .remove("traceId") + .is_some_and(|trace| trace.as_str().is_some_and(|id| id.len() == 32)), + "{name}: the problem carries the request trace id" + ); + let counted = after + .iter() + .filter_map(|(label, value)| { + let delta = value - before.get(label).copied().unwrap_or(0); + (delta > 0).then(|| (label.clone(), delta)) + }) + .collect(); + let events = captured.events(); + let log_text = events.iter().map(Value::to_string).collect::(); + let refusal_lines = events + .into_iter() + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + Observed { + name, + expected_check, + answer: json!({ + "status": status, + "contentType": content_type, + "cacheControl": cache_control, + "wwwAuthenticate": www_authenticate, + "body": body, + }), + counted, + refusal_lines, + log_text, + } +} + +#[tokio::test] +async fn every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire() { + let record = format!("/v1/records/cases/{RECORD_ID}"); + let now = unix_now(); + let harness = Harness::start().await; + let token = |claims: Value| harness.token(claims); + let mut observed = Vec::new(); + + let ok = token(service_claims()); + let tenant_token = |tenant: Option<&str>| { + let claims = service_claims(); + match tenant { + Some(tenant) => token(with(claims, "tenant_claim", json!(tenant))), + None => token(claims), + } + }; + let cases: Vec<(&'static str, &'static str, Request)> = vec![ + ( + "unknown-access-profile", + "access-profile", + read_request(&format!("{record}?accessProfile=nobody"), Some(&ok)), + ), + ( + "missing-scope", + "scope", + // The token carries another scope, so the line can be seen to name + // the declared one and not the presented one. + read_request( + &record, + Some(&token(with( + service_claims(), + "scope", + json!("token-held-canary-scope"), + ))), + ), + ), + ( + "purpose-not-declared", + "purpose", + read_request(&format!("{record}?accessProfile=purposeful"), Some(&ok)), + ), + ( + "actor-kind-mismatch", + "actor-kind", + read_request(&format!("{record}?accessProfile=human-only"), Some(&ok)), + ), + ( + "requester-client-not-admitted", + "requester-client", + read_request( + &format!("{record}?accessProfile=client-bound"), + Some(&token(with(service_claims(), "azp", json!("other-client")))), + ), + ), + ( + "row-claim-missing", + "row-boundary", + read_request( + &format!("{record}?accessProfile=tenant-bound"), + Some(&tenant_token(None)), + ), + ), + ( + "task-grant-missing", + "task-grant-missing", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + with( + with(service_claims(), "registry_actor_kind", json!("agent")), + "registry_purpose", + json!("record-review"), + ), + "act", + json!({"sub": ACTOR_ID, "iss": harness.idp.issuer()}), + ))), + ), + ), + ( + "task-grant-from-another-issuer", + "task-grant-binding", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + grant_claims(now), + "registry_grant_source_issuer", + json!("https://other.example"), + ))), + ), + ), + ( + "task-grant-bounds-do-not-cover-the-profile", + "task-grant-scope", + read_request( + &format!("{record}?accessProfile=granted"), + Some(&token(with( + grant_claims(now), + "registry_grant_bounds", + json!({"type":"breg","permissions":[{"collection":"cases","operations":["list"]}]}), + ))), + ), + ), + ( + "select-beyond-the-readable-fields", + "disclosure", + read_request(&format!("{record}?$select=tenant"), Some(&ok)), + ), + ( + "record-id-is-not-a-uuid", + "visibility", + read_request("/v1/records/cases/not-a-uuid", Some(&ok)), + ), + ( + "record-is-absent-or-outside-the-boundary", + "visibility", + read_request(&record, Some(&ok)), + ), + ( + "schema-of-a-record-type-the-caller-cannot-read", + "visibility", + read_request( + "/v1/schemas/cases", + Some(&token(without(service_claims(), "scope"))), + ), + ), + ]; + for (name, check, request) in cases { + observed.push(observe(name, check, &harness.app, request).await); + } + + // The answers, frozen. + let answers: BTreeMap<&str, &Value> = observed + .iter() + .map(|case| (case.name, &case.answer)) + .collect(); + let golden_path = format!("{}/{GOLDEN}", env!("CARGO_MANIFEST_DIR")); + if std::env::var_os("REGISTRY_BREG_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("answers serialize"); + text.push('\n'); + std::fs::write(&golden_path, text).expect("golden file is writable"); + } else { + let frozen: Value = serde_json::from_str( + &std::fs::read_to_string(&golden_path).expect("golden file exists"), + ) + .expect("golden file is JSON"); + assert_eq!( + serde_json::to_value(&answers).expect("answers serialize"), + frozen, + "a concealed refusal changed on the wire" + ); + } + + // The recording: one count, one line, no caller value. + let mut used: BTreeSet<&str> = BTreeSet::new(); + for case in &observed { + used.insert(case.expected_check); + assert_eq!( + case.counted, + BTreeMap::from([(case.expected_check.to_owned(), 1)]), + "{}: the refusal counts once under its check", + case.name + ); + assert_eq!( + case.refusal_lines.len(), + 1, + "{}: one refusal line", + case.name + ); + let line = &case.refusal_lines[0]; + assert_eq!(line["level"], "INFO", "{}", case.name); + let fields = line["fields"].as_object().expect("line fields"); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.expected_check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + let keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); + let mut expected = BTreeSet::from([ + "decision", + "failed_check", + "message", + "suppressed", + "trace_id", + ]); + if case.expected_check == "scope" { + // A scope refusal also names what the operator declared: the scope + // claim, the scope the profile needs and the profile. + expected.extend(["scope_claim", "required_scope", "access_profile"]); + assert_eq!(fields["scope_claim"], "scope", "{}", case.name); + assert_eq!(fields["required_scope"], "registry.read", "{}", case.name); + assert_eq!(fields["access_profile"], "reader", "{}", case.name); + } + assert_eq!( + keys, expected, + "{}: the line carries only the fixed fields", + case.name + ); + for canary in [ + PRINCIPAL, + "agent-client", + "other-client", + "token-held-canary-scope", + "nobody", + "not-a-uuid", + "https://other.example", + "Bearer", + ] { + assert!( + !case.log_text.contains(canary), + "{}: the log exposed {canary}", + case.name + ); + } + } + assert!( + used.len() >= 11, + "the cases cover every concealment check of the read routes" + ); +} diff --git a/crates/registry-breg/tests/consent_access.rs b/crates/registry-breg/tests/consent_access.rs index 84140a9d9e..c40725d2d6 100644 --- a/crates/registry-breg/tests/consent_access.rs +++ b/crates/registry-breg/tests/consent_access.rs @@ -885,7 +885,7 @@ mod startup { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); RegistryAuthenticator::new( registry, @@ -940,7 +940,7 @@ mod startup { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let claims = AuthorityClaimConfig::new("principal", Some("purpose".to_owned())) .with_contextual_claims( diff --git a/crates/registry-breg/tests/golden/authentication_refusals.json b/crates/registry-breg/tests/golden/authentication_refusals.json new file mode 100644 index 0000000000..c073d49cf1 --- /dev/null +++ b/crates/registry-breg/tests/golden/authentication_refusals.json @@ -0,0 +1,450 @@ +{ + "act-claim-is-not-an-object": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "actor-is-not-the-trusted-actor": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "actor-kind-is-not-a-string": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "actor-without-a-matched-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "basic-scheme": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "double-space-separator": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "expired-token": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "extractor-without-authentication-context": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "key-source-unreachable": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "missing-actor-kind": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "no-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "principal-claim-is-an-object": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "repeated-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "review-completion-expired-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-malformed-timestamp": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-with-two-signatures": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-without-recipient": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-without-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-wrong-key": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "review-completion-wrong-recipient": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" + }, + "tampered-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-bound-to-another-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-bound-to-another-resource": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-claims-malformed": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-expired": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-token-issued-for-too-long": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "task-grant-token-issued-in-the-future": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "token-not-compact": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "token-type-is-not-admitted": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "unknown-key-id": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "wrong-audience": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + }, + "wrong-issuer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer token or delivery signature was not accepted.", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-breg/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-breg/tests/golden/concealment_refusals.json b/crates/registry-breg/tests/golden/concealment_refusals.json new file mode 100644 index 0000000000..8506ae0388 --- /dev/null +++ b/crates/registry-breg/tests/golden/concealment_refusals.json @@ -0,0 +1,171 @@ +{ + "actor-kind-mismatch": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "missing-scope": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "purpose-not-declared": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "record-id-is-not-a-uuid": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "record-is-absent-or-outside-the-boundary": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "requester-client-not-admitted": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "row-claim-missing": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "schema-of-a-record-type-the-caller-cannot-read": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "select-beyond-the-readable-fields": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-bounds-do-not-cover-the-profile": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-from-another-issuer": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "task-grant-missing": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + }, + "unknown-access-profile": { + "body": { + "code": "resource.not_found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not_found" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "status": 404, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt index 498b49e2f3..b5ffbf23b0 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt @@ -137,3 +137,50 @@ breg_metrics_sample_failures_total{sample="ingestion-run"} 0 # HELP breg_active_package_info The package this process verified at startup, by digest. # TYPE breg_active_package_info gauge breg_active_package_info{package_digest="sha256:abababababababababababababababababababababababababababababababab"} 1 +# HELP breg_request_refusals_total Requests refused, by the check that failed. +# TYPE breg_request_refusals_total counter +breg_request_refusals_total{check="credential-missing"} 0 +breg_request_refusals_total{check="credential-malformed"} 0 +breg_request_refusals_total{check="token-algorithm"} 0 +breg_request_refusals_total{check="token-type"} 0 +breg_request_refusals_total{check="token-key"} 0 +breg_request_refusals_total{check="token-signature"} 0 +breg_request_refusals_total{check="token-issuer"} 0 +breg_request_refusals_total{check="token-audience"} 0 +breg_request_refusals_total{check="token-time"} 0 +breg_request_refusals_total{check="token-client"} 0 +breg_request_refusals_total{check="token-assertion-issuer"} 0 +breg_request_refusals_total{check="token-claims"} 0 +breg_request_refusals_total{check="actor-kind"} 0 +breg_request_refusals_total{check="delegation"} 0 +breg_request_refusals_total{check="sender-constraint"} 0 +breg_request_refusals_total{check="key-source-unavailable"} 0 +breg_request_refusals_total{check="shared-secret"} 0 +breg_request_refusals_total{check="one-time-credential"} 0 +breg_request_refusals_total{check="delivery-signature"} 0 +breg_request_refusals_total{check="delivery-freshness"} 0 +breg_request_refusals_total{check="delivery-binding"} 0 +breg_request_refusals_total{check="host-origin"} 0 +breg_request_refusals_total{check="scope"} 0 +breg_request_refusals_total{check="access-profile"} 0 +breg_request_refusals_total{check="requester-client"} 0 +breg_request_refusals_total{check="purpose"} 0 +breg_request_refusals_total{check="operation"} 0 +breg_request_refusals_total{check="disclosure"} 0 +breg_request_refusals_total{check="subject-selector"} 0 +breg_request_refusals_total{check="revision-pin"} 0 +breg_request_refusals_total{check="acquisition-channel"} 0 +breg_request_refusals_total{check="source-authority"} 0 +breg_request_refusals_total{check="separation-of-duties"} 0 +breg_request_refusals_total{check="task-grant-missing"} 0 +breg_request_refusals_total{check="task-grant-claims"} 0 +breg_request_refusals_total{check="task-grant-expired"} 0 +breg_request_refusals_total{check="task-grant-binding"} 0 +breg_request_refusals_total{check="task-grant-scope"} 0 +breg_request_refusals_total{check="task-grant-lifetime"} 0 +breg_request_refusals_total{check="task-grant-status"} 0 +breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="ownership"} 0 +breg_request_refusals_total{check="visibility"} 0 +breg_request_refusals_total{check="action-guard"} 0 +breg_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt index 50e7ca19df..f469ffcaa8 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt @@ -108,3 +108,50 @@ breg_metrics_sample_failures_total{sample="ingestion-run"} 0 # HELP breg_active_package_info The package this process verified at startup, by digest. # TYPE breg_active_package_info gauge breg_active_package_info{package_digest="sha256:abababababababababababababababababababababababababababababababab"} 1 +# HELP breg_request_refusals_total Requests refused, by the check that failed. +# TYPE breg_request_refusals_total counter +breg_request_refusals_total{check="credential-missing"} 0 +breg_request_refusals_total{check="credential-malformed"} 0 +breg_request_refusals_total{check="token-algorithm"} 0 +breg_request_refusals_total{check="token-type"} 0 +breg_request_refusals_total{check="token-key"} 0 +breg_request_refusals_total{check="token-signature"} 0 +breg_request_refusals_total{check="token-issuer"} 0 +breg_request_refusals_total{check="token-audience"} 0 +breg_request_refusals_total{check="token-time"} 0 +breg_request_refusals_total{check="token-client"} 0 +breg_request_refusals_total{check="token-assertion-issuer"} 0 +breg_request_refusals_total{check="token-claims"} 0 +breg_request_refusals_total{check="actor-kind"} 0 +breg_request_refusals_total{check="delegation"} 0 +breg_request_refusals_total{check="sender-constraint"} 0 +breg_request_refusals_total{check="key-source-unavailable"} 0 +breg_request_refusals_total{check="shared-secret"} 0 +breg_request_refusals_total{check="one-time-credential"} 0 +breg_request_refusals_total{check="delivery-signature"} 0 +breg_request_refusals_total{check="delivery-freshness"} 0 +breg_request_refusals_total{check="delivery-binding"} 0 +breg_request_refusals_total{check="host-origin"} 0 +breg_request_refusals_total{check="scope"} 0 +breg_request_refusals_total{check="access-profile"} 0 +breg_request_refusals_total{check="requester-client"} 0 +breg_request_refusals_total{check="purpose"} 0 +breg_request_refusals_total{check="operation"} 0 +breg_request_refusals_total{check="disclosure"} 0 +breg_request_refusals_total{check="subject-selector"} 0 +breg_request_refusals_total{check="revision-pin"} 0 +breg_request_refusals_total{check="acquisition-channel"} 0 +breg_request_refusals_total{check="source-authority"} 0 +breg_request_refusals_total{check="separation-of-duties"} 0 +breg_request_refusals_total{check="task-grant-missing"} 0 +breg_request_refusals_total{check="task-grant-claims"} 0 +breg_request_refusals_total{check="task-grant-expired"} 0 +breg_request_refusals_total{check="task-grant-binding"} 0 +breg_request_refusals_total{check="task-grant-scope"} 0 +breg_request_refusals_total{check="task-grant-lifetime"} 0 +breg_request_refusals_total{check="task-grant-status"} 0 +breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="ownership"} 0 +breg_request_refusals_total{check="visibility"} 0 +breg_request_refusals_total{check="action-guard"} 0 +breg_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index dbbb383b92..4697d827ff 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -30,7 +30,10 @@ use registry_breg::review_store::{ ReviewAuthorityClient, ReviewAuthorityRegistry, ReviewCompletionReceiver, }; use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; -use registry_platform_crypto::PrivateJwk; +use registry_platform_crypto::{ + delivery_signature::{sign, DeliveryKey, DeliveryKeys}, + PrivateJwk, +}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ access_token_typ_set, ActorKind, ClaimNames, JwksFetcher, JwksFetcherConfig, OidcError, @@ -47,7 +50,7 @@ use zeroize::Zeroizing; const AUDIENCE: &str = "urn:example:breg"; #[tokio::test] -async fn compact_token_admission_logs_one_value_free_header_diagnostic() { +async fn compact_token_admission_refuses_malformed_credentials_and_writes_no_line_itself() { use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; use tracing::instrument::WithSubscriber; let captured = CapturedDiagnosticLogs::default(); @@ -71,7 +74,10 @@ async fn compact_token_admission_logs_one_value_free_header_diagnostic() { )); } } - captured.assert_one_value_free_header_diagnostic(&tokens); + // The counted refusal and its one bounded line belong to the request + // boundary, which `tests/authentication_refusals.rs` drives with this + // same corpus. + assert_eq!(captured.text(), "", "admission writes no line of its own"); } #[tokio::test] @@ -522,31 +528,51 @@ async fn review_completion_authentication_refusals_use_the_registered_problem() .expect("test connection configuration is valid") .build_pool() .expect("test pool builds"); - let review_client = ReviewClient::new(ReviewClientConfig::new( - "https://review.example.invalid/" - .parse() - .expect("reserved HTTPS URL"), - )) - .expect("review client builds"); - let authority = Arc::new( - ReviewAuthorityClient::new( - "casework-a".to_owned(), - review_client, - Arc::new( - registry_platform_httputil::StaticToken::new("outgoing-token".to_owned()) - .expect("outgoing token is valid"), - ), - "producer-profile".to_owned(), - "producer-a".to_owned(), - 7, - Some(Zeroizing::new("completion-secret".to_owned())), - Some("registry-a".to_owned()), + let review_client = || { + ReviewClient::new(ReviewClientConfig::new( + "https://review.example.invalid/" + .parse() + .expect("reserved HTTPS URL"), + )) + .expect("review client builds") + }; + let keys = |current, previous: Option| { + DeliveryKeys::new( + DeliveryKey::new(&[current; 32]).unwrap(), + previous.map(|byte| DeliveryKey::new(&[byte; 32]).unwrap()), ) - .expect("review authority is valid"), - ); + .unwrap() + }; + let make_authority = |id: &str, recipient: &str, key| { + Arc::new( + ReviewAuthorityClient::new( + id.to_owned(), + review_client(), + Arc::new( + registry_platform_httputil::StaticToken::new("outgoing-token".to_owned()) + .expect("outgoing token is valid"), + ), + "producer-profile".to_owned(), + "producer-a".to_owned(), + 7, + Some(key), + Some(recipient.to_owned()), + ) + .expect("review authority is valid"), + ) + }; let authorities = Arc::new( - ReviewAuthorityRegistry::new(BTreeMap::from([("casework-a".to_owned(), authority)])) - .expect("review authority registry is valid"), + ReviewAuthorityRegistry::new(BTreeMap::from([ + ( + "casework-a".to_owned(), + make_authority("casework-a", "registry-a", keys(1, Some(2))), + ), + ( + "casework-b".to_owned(), + make_authority("casework-b", "registry-b", keys(3, None)), + ), + ])) + .expect("review authority registry is valid"), ); let receiver = Arc::new(ReviewCompletionReceiver::new(pool.clone(), authorities)); let service = Arc::new( @@ -561,105 +587,194 @@ async fn review_completion_authentication_refusals_use_the_registered_problem() ); let app = authenticated_router(service, authenticator); - let mut missing = Request::builder() - .method("POST") - .uri("/v1/review-completions") - .body(Body::empty()) - .expect("missing-credential request"); - missing.headers_mut().insert( - "registry-recipient-binding", - HeaderValue::from_static("registry-a"), - ); - let mut malformed = Request::builder() - .method("POST") - .uri("/v1/review-completions") - .body(Body::empty()) - .expect("malformed-credential request"); - malformed.headers_mut().insert( - AUTHORIZATION, - HeaderValue::from_static("Basic malformed-canary"), + let event = "00000000-0000-4000-8000-000000000001"; + let request = |recipient: Option<&str>, + id, + offset: i64, + signing_keys: Option, + content_type, + body: Vec| { + let timestamp = chrono::Utc::now().timestamp().checked_add(offset).unwrap() as u64; + let mut builder = Request::builder() + .method("POST") + .uri("/v1/review-completions") + .header("webhook-id", id) + .header("webhook-timestamp", timestamp.to_string()) + .header("content-type", content_type); + if let Some(recipient) = recipient { + builder = builder.header("registry-recipient-binding", recipient); + } + if let Some(keys) = signing_keys { + builder = builder.header( + "webhook-signature", + sign(&keys, id, timestamp, &body).unwrap(), + ); + } + builder.body(Body::from(body)).unwrap() + }; + let body = || { + serde_json::to_vec(&json!({ + "type": "review.completed", + "eventId": event, + "requestId": "00000000-0000-4000-8000-000000000002", + "resultId": "00000000-0000-4000-8000-000000000003", + "completedAt": chrono::Utc::now(), + })) + .unwrap() + }; + let valid = |offset, key| { + request( + Some("registry-a"), + event, + offset, + Some(key), + "application/json", + body(), + ) + }; + let mut duplicate = valid(0, keys(1, None)); + duplicate.headers_mut().append( + "webhook-signature", + HeaderValue::from_static("v1,duplicate-canary"), ); + let mut malformed = valid(0, keys(1, None)); malformed.headers_mut().insert( - "registry-recipient-binding", - HeaderValue::from_static("registry-a"), - ); - let mut invalid = Request::builder() - .method("POST") - .uri("/v1/review-completions") - .body(Body::empty()) - .expect("invalid-credential request"); - invalid.headers_mut().insert( - AUTHORIZATION, - HeaderValue::from_static("Bearer invalid-credential-canary"), - ); - invalid.headers_mut().insert( - "registry-recipient-binding", - HeaderValue::from_static("registry-a"), + "webhook-timestamp", + HeaderValue::from_static("malformed-canary"), ); - let mut wrong_recipient = Request::builder() - .method("POST") - .uri("/v1/review-completions") - .body(Body::empty()) - .expect("wrong-recipient request"); - wrong_recipient.headers_mut().insert( - AUTHORIZATION, - HeaderValue::from_static("Bearer completion-secret"), - ); - wrong_recipient.headers_mut().insert( - "registry-recipient-binding", - HeaderValue::from_static("wrong-recipient-canary"), - ); - let mut admitted = Request::builder() - .method("POST") - .uri("/v1/review-completions") - .body(Body::empty()) - .expect("admitted-credential request"); - admitted.headers_mut().insert( - AUTHORIZATION, - HeaderValue::from_static("Bearer completion-secret"), - ); - admitted.headers_mut().insert( - "registry-recipient-binding", - HeaderValue::from_static("registry-a"), - ); - + use registry_platform_authcommon::RefusalNote; let code = ProblemCode::AuthenticationRefused; - assert!(ProblemCode::ALL.contains(&code)); - for request in [missing, malformed, invalid, wrong_recipient] { - let response = app.clone().oneshot(request).await.expect("router responds"); + for (request, check) in [ + ( + request( + None, + event, + 0, + Some(keys(1, None)), + "application/json", + body(), + ), + "delivery-signature", + ), + ( + request( + Some("wrong-recipient-canary"), + event, + 0, + Some(keys(1, None)), + "application/json", + body(), + ), + "delivery-signature", + ), + ( + request( + Some("registry-a"), + event, + 0, + None, + "application/json", + body(), + ), + "delivery-signature", + ), + ( + request(Some("registry-a"), event, 0, None, "text/plain", body()), + "delivery-signature", + ), + (duplicate, "delivery-signature"), + (valid(0, keys(4, None)), "delivery-signature"), + (valid(0, keys(3, None)), "delivery-signature"), + (valid(-301, keys(1, None)), "delivery-freshness"), + (malformed, "delivery-freshness"), + ] { + let response = app.clone().oneshot(request).await.unwrap(); + assert_eq!( + response + .extensions() + .get::() + .map(|note| note.check.as_str()), + Some(check) + ); assert_eq!(response.status().as_u16(), code.status()); + assert_eq!( + response.headers()["www-authenticate"], + r#"Registry-Signature scheme="standard-webhooks", version="v1""#, + ); let problem = body_json(response).await; assert_eq!(problem["code"], code.code()); assert_eq!(problem["type"], code.type_uri()); assert_eq!(problem["title"], code.title()); assert_eq!(problem["status"], code.status()); assert_eq!(problem["detail"], code.description()); - let rendered = problem.to_string(); - for canary in [ - "malformed-canary", - "invalid-credential-canary", - "wrong-recipient-canary", - ] { - assert!(!rendered.contains(canary)); - } + assert!(!problem.to_string().contains("canary")); + } + assert_eq!(pool.status().size, 0); + for (request, expected) in [ + ( + request( + Some("registry-a"), + event, + 0, + Some(keys(1, None)), + "text/plain", + body(), + ), + 415, + ), + ( + request( + Some("registry-a"), + "another-event", + 0, + Some(keys(1, None)), + "application/json", + body(), + ), + 400, + ), + ( + request( + Some("registry-a"), + event, + 0, + Some(keys(1, None)), + "application/json", + vec![b'a'; 2049], + ), + 413, + ), + ] { + assert_eq!( + app.clone() + .oneshot(request) + .await + .unwrap() + .status() + .as_u16(), + expected + ); + } + for (key, expected) in [ + (2, StatusCode::SERVICE_UNAVAILABLE), + (3, StatusCode::UNAUTHORIZED), + ] { + let response = app + .clone() + .oneshot(valid(0, keys(key, None))) + .await + .unwrap(); + assert_eq!(response.status(), expected); + } + // Unix seconds on the wire are compared against the receiver's subsecond clock. + for (offset, previous) in [(-299, None), (300, None), (0, Some(2))] { + let response = app + .clone() + .oneshot(valid(offset, keys(1, previous))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); } - let admitted = app - .oneshot(admitted) - .await - .expect("router admits the configured callback credential"); - let unsupported = ProblemCode::UnsupportedMediaType; - assert_eq!(admitted.status().as_u16(), unsupported.status()); - let problem = body_json(admitted).await; - assert_eq!(problem["code"], unsupported.code()); - assert_eq!(problem["type"], unsupported.type_uri()); - assert_eq!(problem["title"], unsupported.title()); - assert_eq!(problem["status"], unsupported.status()); - assert_eq!(problem["detail"], unsupported.description()); - assert_eq!( - pool.status().size, - 0, - "review-completion admission opened PostgreSQL" - ); } #[tokio::test] @@ -1976,13 +2091,24 @@ async fn malformed_or_duplicate_bearer_is_refused_before_record_io() { assert_eq!(body_json(response).await["code"], "authentication.refused"); assert_eq!(harness.records.calls.load(Ordering::SeqCst), before); let rendered = captured.text(); - let diagnostics = rendered + // The process-wide recorder admits a bounded number of lines per + // check, and other tests in this process spend that budget, so the + // exact line count is asserted in `tests/authentication_refusals.rs`. + let refusals = rendered .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .filter(|event| event["fields"]["message"] == "BReg authentication refused") + .map(|line| serde_json::from_str::(line).expect("JSON log line")) + .filter(|event| event["fields"]["message"] == "request refused") .collect::>(); - assert_eq!(diagnostics.len(), 1); - assert_eq!(diagnostics[0]["fields"]["stage"], "header"); + assert!(refusals.len() <= 1); + for refusal in &refusals { + assert!( + matches!( + refusal["fields"]["failed_check"].as_str(), + Some("credential-missing" | "credential-malformed") + ), + "{refusal}" + ); + } assert!(!rendered.contains("canary")); assert!(!rendered.contains("Bearer")); } @@ -2413,7 +2539,7 @@ fn authenticator_with_verifier( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); RegistryAuthenticator::new(registry, verifier, key_source, claims) } @@ -2426,7 +2552,7 @@ fn key_source(idp: &MockIdp) -> Arc { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } diff --git a/crates/registry-breg/tests/immediate_action_compiler.rs b/crates/registry-breg/tests/immediate_action_compiler.rs index e4745f884a..d303891e34 100644 --- a/crates/registry-breg/tests/immediate_action_compiler.rs +++ b/crates/registry-breg/tests/immediate_action_compiler.rs @@ -1046,3 +1046,47 @@ fn ambiguous_action_can_require_explicit_profile_but_cannot_have_two_defaults() .iter() .any(|diagnostic| diagnostic.code == "breg.action.route-access-default-multiple")); } + +#[test] +fn current_revision_refuses_a_function_plan_that_writes_an_existing_record() { + use registry_breg::compiler::compile_project_with_assets; + use registry_breg::contract::ModuleAssetSource; + use serde_json::{json, Value}; + + let mut source: Value = serde_json::from_str(&household_contact_project("")).unwrap(); + let effects = source["actions"]["register-household-contact"]["plan"]["effects"].take(); + let writes = effects + .as_array() + .unwrap() + .iter() + .map(|effect| { + json!({ + "id": effect["id"], "target": effect["target"], "operation": effect["operation"], + "fields": effect["set"].as_object().unwrap().keys().collect::>() + }) + }) + .collect::>(); + source["functions"] = json!({"contact-plan": {"runtime":"rhai","source":"scripts/handler.rhai","entrypoint":"handle","abi":"registry.action-plan/v1"}}); + source["actions"]["register-household-contact"]["plan"] = json!({"type":"function","function":"contact-plan","inputs":["household","person-code","legal-name"],"writes":writes}); + source["actions"]["register-household-contact"]["execution"] = + json!({"mode":"immediate","concurrency":"current-revision"}); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let failure = compile_project_with_assets( + &project, + &[], + &[ModuleAssetSource { + module: None, + path: "scripts/handler.rhai".to_owned(), + bytes: br#"fn handle(ctx) { #{effects:[]} }"#.to_vec(), + }], + CompileProfile::Authoring, + ) + .expect_err("a function plan cannot write an existing record without a condition"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "breg.action.concurrency-caller-value"), + "{failure:?}" + ); +} diff --git a/crates/registry-breg/tests/immediate_action_requirements.rs b/crates/registry-breg/tests/immediate_action_requirements.rs index 973a15e0e1..241d08282c 100644 --- a/crates/registry-breg/tests/immediate_action_requirements.rs +++ b/crates/registry-breg/tests/immediate_action_requirements.rs @@ -65,6 +65,88 @@ fn authored_guard_copy_keys_are_bounded_and_only_apply_to_field_guards() { } } +#[test] +fn a_guard_label_is_a_bounded_constant_that_requires_a_reason() { + let guard = |members: Value| { + let mut source = support::project(); + let target = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + for (key, value) in members.as_object().unwrap() { + target[key] = value.clone(); + } + source + }; + let refused = |members: Value, code: &str| { + let report = format!("{:?}", compile(guard(members)).unwrap_err()); + assert!(report.contains(code), "{report}"); + }; + + let registry = compile(guard(json!({ + "reason": "parent-inactive", "label": "Only an active parent takes a child." + }))) + .expect("a label beside its reason compiles"); + let compiled = ®istry.actions().actions[0].requires[0]; + assert_eq!(compiled.reason.as_deref(), Some("parent-inactive")); + assert_eq!( + compiled.label.as_deref(), + Some("Only an active parent takes a child.") + ); + compile(guard( + json!({"reason": "parent-inactive", "label": "é".repeat(128)}), + )) + .expect("256 bytes is the bound itself"); + + refused( + json!({"label": "A label without a reason."}), + "breg.action.commit_guards.label-requires-reason", + ); + for label in [ + "".to_owned(), + " ".to_owned(), + "a".repeat(257), + "é".repeat(129), + "line\nbreak".to_owned(), + ] { + refused( + json!({"reason": "parent-inactive", "label": label}), + "breg.action.commit_guards.label-invalid", + ); + } + + let unlabelled = compile(guard(json!({"reason": "parent-inactive"}))).unwrap(); + let compiled = serde_json::to_value(&unlabelled).unwrap(); + assert!( + !compiled.to_string().contains("\"label\":\"Only"), + "an Action without a label serializes without the member" + ); +} + +#[test] +fn rewording_a_guard_label_changes_neither_the_action_revision_nor_the_migration_review_revision() { + let guarded = |label: Option<&str>| { + let mut source = support::project(); + let target = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + target["reason"] = json!("parent-inactive"); + if let Some(label) = label { + target["label"] = json!(label); + } + compile(source).unwrap().actions().actions[0].clone() + }; + let none = guarded(None); + let first = guarded(Some("Only an active parent takes a child.")); + let second = guarded(Some("The parent must be active.")); + assert_ne!(first, second, "the compiled Actions differ by their label"); + assert_eq!(first.definition_revision, second.definition_revision); + assert_eq!(first.definition_revision, none.definition_revision); + assert_eq!( + registry_breg::immediate_actions::migration_review_revision(&first), + registry_breg::immediate_actions::migration_review_revision(&second) + ); + assert_eq!( + registry_breg::immediate_actions::migration_review_revision(&first), + registry_breg::immediate_actions::migration_review_revision(&none) + ); +} + #[test] fn action_requirements_can_compare_a_target_field_to_a_typed_action_input() { let mut source = support::project(); @@ -146,6 +228,67 @@ fn current_date_offsets_are_bounded_and_bound_to_current_date() { } } +#[test] +fn current_date_month_offsets_are_bounded_bound_to_current_date_and_exclusive_with_days() { + let guard_project = |members: Value| { + let mut source = ordered_guard_project(); + source["project"]["timezone"] = json!("UTC"); + let mut guard = json!({"input": "parent", "field": "opened-on"}); + for (key, value) in members.as_object().unwrap() { + guard[key] = value.clone(); + } + source["actions"]["register-child"]["commitGuards"]["targets"] = json!([guard]); + source + }; + let refused = |members: Value| { + let report = format!("{:?}", compile(guard_project(members)).unwrap_err()); + assert!( + report.contains("breg.action.commit_guards.current-date-offset-invalid"), + "{report}" + ); + }; + + let registry = compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": -3}), + )) + .expect("a signed whole-month offset compiles"); + let guard = ®istry.actions().actions[0].requires[0]; + assert_eq!(guard.current_date_offset_months, -3); + assert_eq!(guard.current_date_offset_days, 0); + + let explicit_zero = compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": 0}), + )) + .expect("zero keeps the existing comparison"); + let absent = compile(guard_project(json!({"currentDate": "on-or-after"}))) + .expect("an absent offset keeps the existing comparison"); + assert_eq!( + explicit_zero.actions().actions[0].requires[0], + absent.actions().actions[0].requires[0] + ); + let compiled = serde_json::to_value(&absent).unwrap(); + assert!( + !compiled.to_string().contains("currentDateOffsetMonths"), + "a zero month offset leaves the compiled model, and every digest over it, unchanged" + ); + + for months in [12_000, -12_000] { + compile(guard_project( + json!({"currentDate": "on-or-after", "currentDateOffsetMonths": months}), + )) + .expect("the bound itself compiles"); + } + for months in [12_001, -12_001] { + refused(json!({"currentDate": "on-or-after", "currentDateOffsetMonths": months})); + } + refused(json!({"currentDateOffsetMonths": 1})); + refused(json!({ + "currentDate": "on-or-after", + "currentDateOffsetMonths": 1, + "currentDateOffsetDays": 1 + })); +} + /// A project whose parent stores one ordered field of each kind and whose /// action takes a required input of each kind. fn ordered_guard_project() -> Value { @@ -507,3 +650,227 @@ fn equality_inputs_must_be_required_and_an_unset_value_is_stated_explicitly() { assert!(format!("{:?}", compile(source).unwrap_err()) .contains("breg.action.commit_guards.targets-value-invalid")); } + +/// `support::project()` plus `deactivate-parent`, an immediate Action that +/// patches an existing parent and guards the status the patch changes. +fn deactivate_project(execution: Value) -> Value { + let mut source = support::project(); + source["actions"]["deactivate-parent"] = json!({ + "execution": execution, + "inputs": [ + {"id": "parent", "apiName": "parentId", "type": "reference", "target": "parent", "required": true, "classification": "restricted"}, + {"id": "zone", "type": "string", "maximumLength": 32, "required": true, "classification": "restricted"} + ], + "commitGuards": {"targets": [ + {"input": "parent", "field": "status", "equals": "active", "reason": "not-active"} + ]}, + "plan": {"type": "fixed", "effects": [ + {"id": "deactivate", "target": {"fromInput": "parent"}, "operation": "patch", + "set": {"status": {"value": "inactive"}}} + ]} + }); + source["accessProfiles"]["registrar"]["permissions"]["actions"] + .as_array_mut() + .unwrap() + .push(json!({"action": "deactivate-parent", "operations": ["invoke"], "targets": [ + {"recordType": "parent", "rowBoundaries": [{"field": "zone", "claim": "zone", "operator": "equals"}]} + ]})); + source +} + +fn current_revision() -> Value { + json!({"mode": "immediate", "concurrency": "current-revision"}) +} + +fn deactivate_parent( + registry: ®istry_breg::CompiledRegistry, +) -> ®istry_breg::model::CompiledAction { + registry + .actions() + .actions + .iter() + .find(|action| action.id == "deactivate-parent") + .expect("the project declares deactivate-parent") +} + +fn refused_with(source: Value, code: &str) -> String { + let failure = compile(source).expect_err("the Action is refused"); + let report = format!("{failure:?}"); + assert!( + failure.diagnostics().iter().any(|d| d.code == code), + "expected {code}: {report}" + ); + report +} + +#[test] +fn a_current_revision_action_needs_no_condition_from_the_caller() { + let conditioned = compile(deactivate_project(json!({"mode": "immediate"}))).unwrap(); + let before = deactivate_parent(&conditioned); + assert!(before.condition_route.is_some()); + assert!(before + .target_uses + .iter() + .any(|use_| use_.condition_required)); + + let registry = compile(deactivate_project(current_revision())).unwrap(); + let action = deactivate_parent(®istry); + assert!(action.condition_route.is_none()); + assert!(action + .target_uses + .iter() + .all(|use_| !use_.condition_required)); + assert_eq!( + action.concurrency, + registry_breg::contract::ActionConcurrency::CurrentRevision + ); + assert_ne!( + action.definition_revision, before.definition_revision, + "the concurrency mode is part of the Action's identity" + ); + assert_ne!( + registry_breg::immediate_actions::migration_review_revision(action), + registry_breg::immediate_actions::migration_review_revision(before), + "turning it on is a reviewed change" + ); +} + +#[test] +fn omitting_concurrency_leaves_the_compiled_action_unchanged() { + let omitted = compile(deactivate_project(json!({"mode": "immediate"}))).unwrap(); + let named = compile(deactivate_project( + json!({"mode": "immediate", "concurrency": "condition-required"}), + )) + .unwrap(); + assert_eq!( + serde_json::to_value(deactivate_parent(&omitted)).unwrap(), + serde_json::to_value(deactivate_parent(&named)).unwrap() + ); + assert!(!serde_json::to_string(deactivate_parent(&omitted)) + .unwrap() + .contains("concurrency")); +} + +#[test] +fn concurrency_is_refused_under_a_proposal_execution() { + let mut source = deactivate_project(current_revision()); + let proposal = json!({"mode": "proposal", "concurrency": "current-revision"}); + source["actions"]["deactivate-parent"]["execution"] = proposal; + let error = parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect_err("a proposal Action names no concurrency"); + assert!(format!("{error:?}").contains("concurrency"), "{error:?}"); +} + +#[test] +fn current_revision_refuses_a_revision_guard() { + let mut source = deactivate_project(current_revision()); + source["actions"]["deactivate-parent"]["commitGuards"]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"input": "parent", "revision": "unchanged"})); + refused_with(source, "breg.action.concurrency-revision-guard"); +} + +#[test] +fn current_revision_refuses_caller_values_written_into_an_existing_record() { + let mut from_input = deactivate_project(current_revision()); + from_input["actions"]["deactivate-parent"]["plan"]["effects"][0]["set"] = + json!({"status": {"value": "inactive"}, "zone": {"fromInput": "zone"}}); + let report = refused_with(from_input, "breg.action.concurrency-caller-value"); + assert!( + report.contains("deactivate") && report.contains("zone"), + "{report}" + ); + + let mut from_effect = deactivate_project(current_revision()); + from_effect["actions"]["deactivate-parent"] = json!({ + "execution": current_revision(), + "inputs": [ + {"id": "child", "apiName": "childId", "type": "reference", "target": "child", "required": true, "classification": "restricted"} + ], + "commitGuards": {"targets": [{"input": "child", "field": "label", "equals": "old"}]}, + "plan": {"type": "fixed", "effects": [ + {"id": "fresh", "target": {"recordType": "parent"}, "operation": "create", + "set": {"status": {"value": "active"}, "zone": {"value": "north"}}}, + {"id": "reparent", "target": {"fromInput": "child"}, "operation": "patch", + "set": {"label": {"value": "new"}, "parent": {"fromEffect": "fresh"}}} + ]} + }); + from_effect["accessProfiles"]["registrar"]["permissions"]["actions"][1]["targets"] = json!([ + {"recordType": "parent", "rowBoundaries": "unrestricted"}, + {"recordType": "child", "rowBoundaries": "unrestricted"} + ]); + refused_with(from_effect, "breg.action.concurrency-caller-value"); +} + +#[test] +fn current_revision_allows_a_caller_value_into_a_created_record() { + let mut source = deactivate_project(current_revision()); + source["actions"]["deactivate-parent"]["plan"]["effects"] + .as_array_mut() + .unwrap() + .push( + json!({"id": "child", "target": {"recordType": "child"}, "operation": "create", + "set": {"parent": {"fromInput": "parent"}, "label": {"fromInput": "zone"}}}), + ); + source["accessProfiles"]["registrar"]["permissions"]["actions"][1]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType": "child", "rowBoundaries": "unrestricted"})); + compile(source).expect("a create takes a caller value under current-revision"); +} + +#[test] +fn current_revision_allows_clearing_a_field() { + let mut source = support::project(); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id": "note", "type": "string", "maximumLength": 32, "classification": "restricted"})); + let mut with_note = deactivate_project(current_revision()); + with_note["recordTypes"] = source["recordTypes"].clone(); + with_note["actions"]["deactivate-parent"]["plan"]["effects"][0]["clear"] = json!(["note"]); + compile(with_note).expect("a clear is a constant"); +} + +#[test] +fn current_revision_needs_a_guard_the_write_falsifies() { + // No guard on the patched record. + let mut unguarded = deactivate_project(current_revision()); + unguarded["actions"]["deactivate-parent"]["commitGuards"] = json!({"targets": []}); + refused_with(unguarded, "breg.action.concurrency-guard-missing"); + + // A guard on a field the write does not change. + let mut elsewhere = deactivate_project(current_revision()); + elsewhere["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "zone", "equals": "north"}]); + refused_with(elsewhere, "breg.action.concurrency-guard-missing"); + + // A guard the write leaves true: both want "inactive". + let mut same = deactivate_project(current_revision()); + same["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "status", "equals": "inactive"}]); + refused_with(same, "breg.action.concurrency-guard-missing"); + + // A guard that depends on the caller cannot be falsified by the write. + let mut by_input = deactivate_project(current_revision()); + by_input["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "zone", "equalsFromInput": "zone"}]); + refused_with(by_input, "breg.action.concurrency-guard-missing"); +} + +#[test] +fn current_revision_accepts_a_null_guard_the_write_falsifies() { + let mut source = support::project(); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id": "closed-on", "type": "string", "maximumLength": 32, "classification": "restricted"})); + let mut open = deactivate_project(current_revision()); + open["recordTypes"] = source["recordTypes"].clone(); + open["actions"]["deactivate-parent"]["commitGuards"]["targets"] = + json!([{"input": "parent", "field": "closed-on", "isNull": true}]); + open["actions"]["deactivate-parent"]["plan"]["effects"][0]["set"] = + json!({"closed-on": {"value": "2026-11-27"}}); + compile(open).expect("setting a field the guard requires unset falsifies the guard"); +} diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index 628c81e912..b18e048867 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -230,7 +230,7 @@ async fn setup_relationships() -> (TestDatabase, Router, MockIdp) { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into()]; @@ -311,7 +311,7 @@ async fn setup_registry(registry: CompiledRegistry) -> (TestDatabase, Router, Mo let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into(), "evidence-service".into()]; @@ -1025,7 +1025,7 @@ async fn setup_with_mutations( let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into(), "agency".into()]; diff --git a/crates/registry-breg/tests/postgres_action_task_grants.rs b/crates/registry-breg/tests/postgres_action_task_grants.rs index d9ea24f579..08f0e78f46 100644 --- a/crates/registry-breg/tests/postgres_action_task_grants.rs +++ b/crates/registry-breg/tests/postgres_action_task_grants.rs @@ -107,7 +107,7 @@ async fn task_action_scope_subjects_replay_and_fresh_revocation_are_enforced() { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())) .with_contextual_claims( @@ -471,7 +471,7 @@ async fn task_record_read_is_bound_to_the_grant_identity_by_the_profile_row_boun Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())) .with_contextual_claims( diff --git a/crates/registry-breg/tests/postgres_consent_access.rs b/crates/registry-breg/tests/postgres_consent_access.rs index df5632237b..244a938405 100644 --- a/crates/registry-breg/tests/postgres_consent_access.rs +++ b/crates/registry-breg/tests/postgres_consent_access.rs @@ -154,7 +154,7 @@ impl Harness { let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.into()]); verifier.allowed_clients = vec![ diff --git a/crates/registry-breg/tests/postgres_data_export.rs b/crates/registry-breg/tests/postgres_data_export.rs index 3a02799a91..b24634123d 100644 --- a/crates/registry-breg/tests/postgres_data_export.rs +++ b/crates/registry-breg/tests/postgres_data_export.rs @@ -449,7 +449,7 @@ fn authenticated_app( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_fixture_journeys.rs b/crates/registry-breg/tests/postgres_fixture_journeys.rs index 52bc5c88dc..b1e9ae69dc 100644 --- a/crates/registry-breg/tests/postgres_fixture_journeys.rs +++ b/crates/registry-breg/tests/postgres_fixture_journeys.rs @@ -473,6 +473,132 @@ async fn production_schema_test_setup_failures_identify_configuration_without_se } } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn deployed_and_rehearsed_delivery_bindings_refuse_shared_or_invalid_keys() { + let _runtime_guard = WASM_RUNTIME_TEST_LOCK.lock().await; + use registry_breg::startup::{check_with_connection_config_for_test, StartupError}; + + let baseline = String::from_utf8(compiled_fixture().1).unwrap(); + let project_source = baseline.replacen( + " fields:\n", + r#" hooks: + - id: widget-created + phase: after + trigger: created + projection: [label] + handler: {type: url, destinationId: receiver} + fields: +"#, + 1, + ); + let project = parse_project_yaml(project_source.as_bytes()).unwrap(); + let module = parse_module_yaml(MODULE_SOURCE).unwrap(); + let compiled = compile_project(&project, &[module], CompileProfile::Production).unwrap(); + let schema_fingerprint = measure_compiled_schema_fingerprint(&compiled).await; + let package = package_fixture(project_source.as_bytes(), &schema_fingerprint); + let suite = validate_fixture_journeys(JOURNEY_SOURCE, &compiled).unwrap(); + let idp = MockIdp::start().await; + let current = "reviewAuthorities.casework.completion.hmacSha256KeyRef"; + let previous = "reviewAuthorities.casework.completion.previousHmacSha256KeyRef"; + let hook = "destinations.hooks.receiver.hmacSha256KeyRef"; + let repeated = format!("{hook} and {current} resolve to the same key bytes. Give {current} its own key by writing 32 new random bytes to another secret and referencing it there."); + for (key, rotation, expected) in [ + (&[0x22; 32][..], "", repeated.clone()), + (&[0x13; 31][..], "", format!("{current} has 31 bytes (trailing newline: false). Supply 32 to 64 exact key bytes.")), + (&[0x13; 32][..], " previousHmacSha256KeyRef: secret:file/old-key\n", format!("{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}.")), + ] { + let database = TestDatabase::create(8).await; + let path = package.write_runtime_config(&database, &idp); + let secrets = package.directory.join("secrets"); + write_private(&secrets.join("completion-key"), key); + write_private(&secrets.join("old-key"), key); + write_private(&secrets.join("hook-key"), &[0x22; 32]); + write_private(&secrets.join("review-token"), b"synthetic-review-token"); + let bindings = r#"destinations: + hooks: + receiver: + origin: https://receiver.example.test + path: /events + networkProfile: production-https + dnsFamily: ipv4-only + allowedPrivateCidrs: [] + hmacSha256KeyRef: secret:file/hook-key + classificationCeiling: public + deliveryCeilings: + attemptTimeoutMilliseconds: 1000 + maximumAttempts: 1 +reviewAuthorities: + casework: + endpoint: https://review.example.test/ + profile: producer + producerId: registry-producer + recoveryDays: 7 + tokenRef: secret:file/review-token + completion: + recipientBinding: registry + hmacSha256KeyRef: secret:file/completion-key +"#; + let append_bindings = |path: &Path| { + let mut source = fs::read_to_string(path).unwrap(); + source.push_str(bindings); + source.push_str(rotation); + fs::write(path, source).unwrap(); + }; + append_bindings(&path); + let config = load_runtime_config(&path).unwrap(); + let database_for_test = prepare_schema_test_database_with_connection_configs_for_test( + &config, + &package.prepared, + &database.migration_config, + &database.runtime_config, + ) + .await + .unwrap(); + if expected == repeated { + let serving = TestDatabase::create(8).await; + let (migration, task) = serving.connect_migration().await; + install_compiled_schema(&migration, &compiled, &serving.runtime_role) + .await + .unwrap(); + initialize_compiled_registry_state_for_test( + &migration, + &serving.runtime_role, + &compiled, + RegistryStateTestIdentity { + package_id: &package.package.manifest().package_id, + database_id: DATABASE_ID, + label: &package.revision, + }, + ) + .await + .unwrap(); + drop(migration); + task.abort(); + let serving_path = package.write_runtime_config(&serving, &idp); + append_bindings(&serving_path); + let serve = prepare_with_connection_config_for_test(&serving_path, serving.runtime_config.clone()).await.err().unwrap(); + let doctor = check_with_connection_config_for_test(&serving_path, serving.runtime_config.clone()).await.unwrap_err(); + for error in [serve, doctor] { + assert!(matches!(error, StartupError::EventDestinations(ref message) if message == &repeated), "{error:?}"); + } + serving.cleanup().await; + } + let error = execute_schema_test( + database_for_test, &config, &package.prepared, &suite, + successful_credential_bindings(&suite, &idp), + ) + .await + .unwrap_err(); + let FixtureError::RuntimeSetup(cause) = error else { + panic!("expected the runtime setup refusal, got {error:?}"); + }; + let detail = cause.to_string(); + assert_eq!(detail.strip_prefix("schema-test ").unwrap_or(&detail), expected); + database.cleanup().await; + } + idp.stop().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn production_schema_test_executor_uses_only_prepared_database_and_private_credentials() { let _runtime_guard = WASM_RUNTIME_TEST_LOCK.lock().await; diff --git a/crates/registry-breg/tests/postgres_immediate_action_requirements.rs b/crates/registry-breg/tests/postgres_immediate_action_requirements.rs index 7c9e3d3d5a..32542ee220 100644 --- a/crates/registry-breg/tests/postgres_immediate_action_requirements.rs +++ b/crates/registry-breg/tests/postgres_immediate_action_requirements.rs @@ -363,6 +363,41 @@ async fn current_date_offset_is_enforced_at_immediate_commit() { database.cleanup().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn current_date_month_offset_is_enforced_at_immediate_commit() { + let mut source = support::project(); + source["project"]["timezone"] = json!("UTC"); + source["recordTypes"]["parent"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "id":"eligible-on", "type":"date", "classification":"restricted" + })); + source["actions"]["register-child"]["commitGuards"]["targets"] + .as_array_mut() + .unwrap() + .push(json!({ + "input":"parent", "field":"eligible-on", "currentDate":"on-or-after", + "currentDateOffsetMonths":1 + })); + let (database, registry, identity) = setup_with_project(source).await; + let today = registry + .local_date_at(time::OffsetDateTime::now_utc()) + .unwrap(); + let threshold = today.checked_add_months(chrono::Months::new(1)).unwrap(); + set_parent_eligible_on(&database, ®istry, threshold).await; + let app = app(&database, registry.clone(), identity, None); + let accepted = invoke(app.clone(), "month-offset-accepted", ID).await; + assert_eq!(accepted.0, StatusCode::OK, "{}", accepted.1); + let committed = counts(&database, ®istry).await; + + set_parent_eligible_on(&database, ®istry, today).await; + let refused = invoke(app, "month-offset-refused", ID).await; + assert_eq!(refused.0, StatusCode::PRECONDITION_FAILED, "{}", refused.1); + assert_eq!(counts(&database, ®istry).await, committed); + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn ordered_input_guards_compare_dates_and_instants_against_stored_fields() { let mut source = with_parent_get( @@ -1103,6 +1138,123 @@ async fn counts(database: &TestDatabase, registry: ®istry_breg::CompiledRegis (0..6).map(|index| row.get(index)).collect() } +const GUARD_LABEL: &str = "Only an active parent can take a new child."; + +/// The registrar's one guard carries a reason and an authored label. +fn with_guard_label(mut source: Value) -> Value { + let guard = &mut source["actions"]["register-child"]["commitGuards"]["targets"][0]; + guard["reason"] = json!("parent-inactive"); + guard["label"] = json!(GUARD_LABEL); + source +} + +/// A body without the per-request `traceId`, so two refusals compare. +fn without_trace(mut body: Value) -> Value { + body.as_object_mut().unwrap().remove("traceId"); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_guard_label_rides_only_the_readable_guard_refusal_and_availability() { + let source = with_guard_label(with_parent_get(support::project(), &["status", "zone"])); + let (database, registry, identity) = setup_with_project(source).await; + let app = app(&database, registry.clone(), identity, None); + database + .admin + .execute( + &status_sql(®istry), + &[&"inactive", &Uuid::parse_str(ID).unwrap()], + ) + .await + .unwrap(); + let before = counts(&database, ®istry).await; + + let refused = invoke(app.clone(), "labelled-guard", ID).await; + assert_eq!(refused.0, StatusCode::PRECONDITION_FAILED, "{}", refused.1); + assert_eq!(refused.1["code"], "action.guard_failed"); + assert_eq!(refused.1["guardReason"], "parent-inactive"); + assert_eq!(refused.1["detail"], GUARD_LABEL); + + let unavailable = availability(app.clone(), json!({"parentId":ID})).await; + assert_eq!(unavailable.0, StatusCode::OK, "{}", unavailable.1); + assert_eq!( + unavailable.1, + json!({"availability":{ + "available":false, + "observedRevision":2, + "reason":"guard-not-satisfied", + "guardReason":"parent-inactive", + "guardLabel":GUARD_LABEL, + "recovery":"none" + }}) + ); + assert_eq!(before, counts(&database, ®istry).await); + database.cleanup().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_unreadable_guard_field_never_discloses_the_guard_label() { + // The profile cannot read `status`, so the failed guard stays the fixed + // precondition refusal, byte-identical to a row-boundary refusal. + let source = with_guard_label(with_parent_get(support::project(), &["zone"])); + let (database, registry, identity) = setup_with_project(source).await; + insert_parent( + &database, + ®istry, + &identity.activation_id, + FOREIGN_ID, + "active", + "zone-b", + ) + .await; + let mut app = app(&database, registry.clone(), identity, None); + database + .admin + .execute( + &status_sql(®istry), + &[&"inactive", &Uuid::parse_str(ID).unwrap()], + ) + .await + .unwrap(); + + let hidden_guard = invoke(app.clone(), "hidden-guard", ID).await; + let boundary = invoke(app.clone(), "hidden-boundary", FOREIGN_ID).await; + assert_eq!(hidden_guard.0, StatusCode::PRECONDITION_FAILED); + assert_eq!(hidden_guard.0, boundary.0); + assert_eq!(hidden_guard.1["code"], "precondition.failed"); + assert_eq!( + without_trace(hidden_guard.1.clone()), + without_trace(boundary.1), + "a hidden guard answers exactly as a boundary refusal does" + ); + assert!(!hidden_guard.1.to_string().contains(GUARD_LABEL)); + assert!(hidden_guard.1.get("guardReason").is_none()); + + // Neither the headers nor an availability answer carry the label. + let mut request = Request::builder() + .method("POST") + .uri("/v1/actions/register-child") + .header("content-type", "application/json") + .header("idempotency-key", "hidden-guard-headers") + .body(Body::from( + serde_json::to_vec(&json!({"input": {"parentId": ID, "label": "synthetic"}})).unwrap(), + )) + .unwrap(); + request.extensions_mut().insert(registrar_claims()); + let response = app.call(request).await.unwrap(); + assert!(response + .headers() + .iter() + .all(|(_, value)| !String::from_utf8_lossy(value.as_bytes()).contains(GUARD_LABEL))); + let hidden_availability = availability(app, json!({"parentId":ID})).await; + assert!( + !hidden_availability.1.to_string().contains(GUARD_LABEL), + "{}", + hidden_availability.1 + ); + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn action_requirements_are_acceptance_only_atomic_and_replayable() { let (database, registry, identity) = setup().await; diff --git a/crates/registry-breg/tests/postgres_immediate_actions.rs b/crates/registry-breg/tests/postgres_immediate_actions.rs index 72898e5063..326dcbf2b1 100644 --- a/crates/registry-breg/tests/postgres_immediate_actions.rs +++ b/crates/registry-breg/tests/postgres_immediate_actions.rs @@ -3828,3 +3828,325 @@ fn history_registry() -> registry_breg::CompiledRegistry { .expect("history project parses"); compile_project(&project, &[], CompileProfile::Authoring).expect("history project compiles") } + +/// The action project plus `close-household`, a `current-revision` Action +/// whose guard (`status-note` unset) is the write it makes false, and +/// `recode-household`, a condition-required Action that changes another +/// field of the same record. +fn current_revision_registry() -> registry_breg::CompiledRegistry { + let mut source: Value = serde_json::from_slice(ACTION_PROJECT).expect("action project is JSON"); + let household_input = json!({ + "id": "household", "apiName": "householdId", "type": "reference", + "target": "household", "required": true, "classification": "restricted" + }); + source["actions"]["close-household"] = json!({ + "inputs": [household_input.clone()], + "execution": {"mode": "immediate", "concurrency": "current-revision"}, + "commitGuards": {"targets": [ + {"input": "household", "field": "status-note", "isNull": true, "reason": "already-closed"} + ]}, + "plan": {"type": "fixed", "effects": [ + {"id": "close", "target": {"fromInput": "household"}, "operation": "patch", + "set": {"status-note": {"value": "closed"}}} + ]} + }); + source["actions"]["recode-household"] = json!({ + "inputs": [household_input, { + "id": "household-code", "apiName": "householdCode", "type": "string", + "maximumLength": 64, "required": true, "classification": "restricted" + }], + "execution": {"mode": "immediate"}, + "plan": {"type": "fixed", "effects": [ + {"id": "recode", "target": {"fromInput": "household"}, "operation": "patch", + "set": {"household-code": {"fromInput": "household-code"}}} + ]} + }); + let boundary = json!([{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]); + let permissions = source["accessProfiles"]["contact-registrar"]["permissions"]["actions"] + .as_array_mut() + .expect("the registrar grants Actions"); + for (action, result) in [("close-household", "close"), ("recode-household", "recode")] { + permissions.push(json!({ + "action": action, "operations": ["invoke"], + "targets": [{"recordType": "household", "rowBoundaries": boundary.clone()}], + "results": [result] + })); + } + let project = parse_project_json(&serde_json::to_vec(&source).expect("project serializes")) + .expect("current-revision project parses"); + compile_project(&project, &[], CompileProfile::Authoring) + .expect("current-revision project compiles") +} + +async fn invoke_close( + app: &axum::Router, + household: &str, + key: &str, + extra: Value, +) -> ResponseParts { + let mut body = json!({"input": {"householdId": household}}); + if let Value::Object(extra) = extra { + body.as_object_mut() + .expect("body is an object") + .extend(extra); + } + response_parts( + send( + app, + Method::POST, + "/v1/actions/close-household", + Some(action_claims()), + &[ + ("content-type", "application/json"), + ("idempotency-key", key), + ], + serde_json::to_vec(&body).expect("body serializes"), + ) + .await, + ) + .await +} + +fn without_trace(mut body: Value) -> Value { + body.as_object_mut().map(|map| map.remove("traceId")); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_current_revision_action_commits_over_plain_http_without_a_condition() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + // The contract names no condition route, so a caller has none to ask for. + let route = response_parts( + send( + &app, + Method::POST, + "/v1/actions/close-household/target-conditions", + Some(action_claims()), + &[("content-type", "application/json")], + serde_json::to_vec(&json!({"input": {"householdId": HOUSEHOLD_ID}})).unwrap(), + ) + .await, + ) + .await; + assert_eq!(route.status, StatusCode::NOT_FOUND, "{}", route.body); + + let closed = invoke_close(&app, HOUSEHOLD_ID, "close-1", json!({})).await; + assert_eq!(closed.status, StatusCode::OK, "{}", closed.body); + assert_eq!( + closed.body["results"]["close"]["revision"], 2, + "{}", + closed.body + ); + let (code, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!( + (code.as_str(), note.as_deref(), revision), + ("H-001", Some("closed"), 2) + ); + + // A second run finds the guard false on the current row. + let again = invoke_close(&app, HOUSEHOLD_ID, "close-2", json!({})).await; + assert_eq!( + again.status, + StatusCode::PRECONDITION_FAILED, + "{}", + again.body + ); + // The caller holds no read grant on the guarded field, so the refusal + // is the generic one and names no guard. + assert_eq!(again.body["code"], "precondition.failed", "{}", again.body); + assert!(again.body.get("guardReason").is_none(), "{}", again.body); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_concurrent_current_revision_invocations_commit_exactly_once() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let (first, second) = tokio::join!( + invoke_close(&app, HOUSEHOLD_ID, "race-a", json!({})), + invoke_close(&app, HOUSEHOLD_ID, "race-b", json!({})), + ); + let mut statuses = [first.status, second.status]; + statuses.sort(); + assert_eq!( + statuses, + [StatusCode::OK, StatusCode::PRECONDITION_FAILED], + "{} / {}", + first.body, + second.body + ); + let loser = if first.status == StatusCode::OK { + &second + } else { + &first + }; + assert_eq!(loser.body["code"], "precondition.failed", "{}", loser.body); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((note.as_deref(), revision), (Some("closed"), 2)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn condition_required_still_demands_a_condition_and_current_revision_refuses_one() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let recode = |preconditions: Option, key: &'static str| { + let app = app.clone(); + async move { + let mut body = + json!({"input": {"householdId": HOUSEHOLD_ID, "householdCode": "H-NEW"}}); + if let Some(preconditions) = preconditions { + body["preconditions"] = preconditions; + } + response_parts( + send( + &app, + Method::POST, + "/v1/actions/recode-household", + Some(action_claims()), + &[ + ("content-type", "application/json"), + ("idempotency-key", key), + ], + serde_json::to_vec(&body).unwrap(), + ) + .await, + ) + .await + } + }; + let missing = recode(None, "recode-missing").await; + assert_eq!(missing.status, StatusCode::BAD_REQUEST, "{}", missing.body); + let (code, _, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((code.as_str(), revision), ("H-001", 1)); + + // A condition sent to an Action that asks for none is refused, and the + // row is untouched. + let stale = json!({"householdId": {"ifMatch": "W/\"anything\""}}); + let unwanted = invoke_close( + &app, + HOUSEHOLD_ID, + "close-conditioned", + json!({"preconditions": stale}), + ) + .await; + assert_eq!( + unwanted.status, + StatusCode::BAD_REQUEST, + "{}", + unwanted.body + ); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!((note, revision), (None, 1)); + + // The conditioned Action changes the code, then the current-revision + // Action patches the locked current row: the code keeps its new value. + let condition = response_parts( + send( + &app, + Method::POST, + "/v1/actions/recode-household/target-conditions", + Some(action_claims()), + &[("content-type", "application/json")], + serde_json::to_vec(&json!({"input": {"householdId": HOUSEHOLD_ID}})).unwrap(), + ) + .await, + ) + .await; + assert_eq!(condition.status, StatusCode::OK, "{}", condition.body); + let recoded = recode(Some(condition.body["preconditions"].clone()), "recode-ok").await; + assert_eq!(recoded.status, StatusCode::OK, "{}", recoded.body); + let closed = invoke_close(&app, HOUSEHOLD_ID, "close-after-recode", json!({})).await; + assert_eq!(closed.status, StatusCode::OK, "{}", closed.body); + let (code, note, revision) = + household_code_note_revision(&database, ®istry, HOUSEHOLD_ID).await; + assert_eq!( + (code.as_str(), note.as_deref(), revision), + ("H-NEW", Some("closed"), 3) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one() { + let (database, registry, identity) = install_action_registry(current_revision_registry()).await; + seed_household( + &database, + ®istry, + &identity, + HOUSEHOLD_ID, + "H-001", + "zone-a", + ) + .await; + seed_household( + &database, + ®istry, + &identity, + OTHER_HOUSEHOLD_ID, + "H-002", + "zone-b", + ) + .await; + let app = action_router(&database, registry.clone(), identity); + + let missing = invoke_close( + &app, + "00000000-0000-4000-8000-0000000009ff", + "missing", + json!({}), + ) + .await; + let outside = invoke_close(&app, OTHER_HOUSEHOLD_ID, "outside", json!({})).await; + assert_eq!( + missing.status, + StatusCode::PRECONDITION_FAILED, + "{}", + missing.body + ); + assert_eq!(outside.status, missing.status); + assert_eq!( + without_trace(outside.body.clone()), + without_trace(missing.body.clone()), + "a record outside the caller's boundary answers as a missing record does" + ); + let (_, note, revision) = + household_code_note_revision(&database, ®istry, OTHER_HOUSEHOLD_ID).await; + assert_eq!( + (note, revision), + (None, 1), + "the hidden record is untouched" + ); +} diff --git a/crates/registry-breg/tests/postgres_membership_access.rs b/crates/registry-breg/tests/postgres_membership_access.rs index 2af4beccdf..38ff7fe3a6 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -121,7 +121,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs b/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs index 0238a6017b..53d964dc42 100644 --- a/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs +++ b/crates/registry-breg/tests/postgres_multi_reference_action_authority.rs @@ -300,7 +300,7 @@ fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), ) diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 7bb2f05333..41b093d380 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -1320,6 +1320,7 @@ async fn real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic() let before_create = durable_counts(&database, &table).await; let before_create_refusals = refusal_audit_count(&database).await; + let counted_before_create = refusal_counts().await; let refused_create = send( &app, Method::POST, @@ -1336,6 +1337,12 @@ async fn real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic() assert_eq!(refused_create.status(), StatusCode::FORBIDDEN); let refused_create = body_json(refused_create).await; assert_eq!(refused_create["code"], "write.outside-boundary"); + assert_refusal_counted( + &counted_before_create, + "row-boundary", + "create outside boundary", + ) + .await; assert_eq!( refused_create["detail"], "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition." @@ -2138,6 +2145,48 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat database.cleanup().await; } +/// The refusal counter, read the way an operator reads it: from the metrics +/// listener. The recorder is process-wide, so a test that shares its process +/// with others asserts a rise of at least one. +async fn refusal_counts() -> std::collections::BTreeMap { + use tower::ServiceExt as _; + let response = registry_breg::metrics::metrics_app(Arc::new( + registry_breg::metrics::Metrics::without_pool_for_test(), + )) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("metrics respond"); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + String::from_utf8(bytes.to_vec()) + .expect("metrics are UTF-8") + .lines() + .filter_map(|line| { + let rest = line.strip_prefix("breg_request_refusals_total{check=\"")?; + let (label, value) = rest.split_once("\"} ")?; + Some((label.to_owned(), value.parse().expect("counter value"))) + }) + .collect() +} + +async fn assert_refusal_counted( + before: &std::collections::BTreeMap, + check: &str, + context: &str, +) { + let after = refusal_counts().await; + assert!( + after.get(check).copied().unwrap_or(0) > before.get(check).copied().unwrap_or(0), + "{context}: the refusal counts under {check}" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { let database = TestDatabase::create(12).await; @@ -3060,6 +3109,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { .any(|window| window == b"http-patched")); let before_bad_query = durable_counts(&database, &table).await; + let counted_before_bad_query = refusal_counts().await; let bad_query = send( &app, Method::POST, @@ -3074,6 +3124,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { .await; assert_eq!(bad_query.status(), StatusCode::NOT_FOUND); assert_eq!(body_json(bad_query).await["code"], "resource.not_found"); + assert_refusal_counted(&counted_before_bad_query, "visibility", "bad query").await; assert_eq!( durable_counts(&database, &table).await.audit, before_bad_query.audit + 1 @@ -3114,24 +3165,28 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { "refusal audit failure releases no intended refusal and commits no mutation packet" ); - for (label, uri, blocked_claims) in [ + for (label, uri, blocked_claims, expected_check) in [ ( "wrong purpose", "/v1/records/widgets?accessProfile=operator", api_claims("wrong-purpose", Some("zone-a")), + "purpose", ), ( "wrong profile", "/v1/records/widgets?accessProfile=missing", api_claims("case-management", Some("zone-a")), + "access-profile", ), ( "missing boundary", "/v1/records/widgets?accessProfile=operator", api_claims("case-management", None), + "row-boundary", ), ] { let before = durable_counts(&database, &table).await; + let counted_before = refusal_counts().await; let response = send( &app, Method::POST, @@ -3145,6 +3200,7 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { ) .await; assert_eq!(response.status(), StatusCode::NOT_FOUND, "{label}"); + assert_refusal_counted(&counted_before, expected_check, label).await; assert_eq!( durable_counts(&database, &table).await.current, before.current diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index a9a0b159ad..b05edc889a 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -70,6 +70,32 @@ async fn application_queue_age(fixture: &client_http::ClientFixture) -> f64 { .parse() .unwrap() } +/// The refusal counter, read the way an operator reads it: from the metrics +/// listener. The recorder is process-wide, so a test that shares its process +/// with others asserts a rise of at least what it caused. +async fn refusal_count(check: &str) -> u64 { + use tower::util::ServiceExt; + let response = registry_breg::metrics::metrics_app(std::sync::Arc::new( + registry_breg::metrics::Metrics::without_pool_for_test(), + )) + .oneshot( + axum::http::Request::builder() + .uri("/metrics") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + let prefix = format!("breg_request_refusals_total{{check=\"{check}\"}} "); + std::str::from_utf8(&bytes) + .unwrap() + .lines() + .find_map(|line| line.strip_prefix(prefix.as_str())) + .map_or(0, |value| value.parse().unwrap()) +} fn registry_source(automatic: bool) -> Value { let source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"proposal-test","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal.example.test"}, @@ -6373,6 +6399,33 @@ async fn review_context_projects_an_omitted_optional_input_as_null() { batch["items"][1], json!({"id": missing, "status":"concealed"}) ); + // Each concealed item counts once under its own check, though the batch + // answers 200. Other tests share the recorder, so the rise is a lower + // bound that one note per response could not reach. + let before = refusal_count("visibility").await; + let unknown = (0..3) + .map(|_| uuid::Uuid::new_v4().to_string()) + .collect::>(); + let response = reqwest::Client::new() + .get(format!( + "{}/v1/proposals/review-context", + fixture.http.base_url + )) + .query(&[("accessProfile", "clerk"), ("ids", &unknown.join(","))]) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK); + let batch: Value = response.json().await.unwrap(); + assert!(batch["items"] + .as_array() + .unwrap() + .iter() + .all(|item| item["status"] == "concealed")); + assert!( + refusal_count("visibility").await - before >= 3, + "each concealed batch item counts under visibility" + ); let before = fixture.audit_capture.entries().len(); let excessive = (0..101) .map(|_| uuid::Uuid::new_v4().to_string()) @@ -6866,7 +6919,7 @@ async fn apply_receipt_replay_refuses_a_task_grant_expiring_at_the_idempotency_l Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("sub", Some("registry_purpose".into())), ) diff --git a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs index 7cd63eb0f6..0583af84d8 100644 --- a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs +++ b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs @@ -51,10 +51,33 @@ fn registry(readable: &[&str]) -> registry_breg::CompiledRegistry { registry_with_current_date_offset(readable, None) } +/// `offset` names a `currentDate` guard member and its value: either +/// `currentDateOffsetDays` or `currentDateOffsetMonths`. fn registry_with_current_date_offset( readable: &[&str], - offset_days: Option, + offset: Option<(&str, i32)>, ) -> registry_breg::CompiledRegistry { + compile_source(guard_project(readable, offset)) +} + +const TARGET_NOT_OPEN_LABEL: &str = "Only an open target can be corrected."; +const BELOW_MINIMUM_LABEL: &str = "The target is below the requested capacity."; + +/// The guards of `registry` with an authored label on each. +fn registry_with_guard_labels(readable: &[&str]) -> registry_breg::CompiledRegistry { + let mut source = guard_project(readable, None); + let guards = &mut source["actions"]["correct-name"]["commitGuards"]["targets"]; + guards[1]["label"] = json!(TARGET_NOT_OPEN_LABEL); + guards[2]["label"] = json!(BELOW_MINIMUM_LABEL); + compile_source(source) +} + +fn compile_source(source: Value) -> registry_breg::CompiledRegistry { + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).expect("guard project compiles") +} + +fn guard_project(readable: &[&str], offset: Option<(&str, i32)>) -> Value { let mut source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"guard-failure-test","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://guard.example.test"}, "datasets":{"directory": {}}, @@ -84,7 +107,7 @@ fn registry_with_current_date_offset( "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], "ownership":"caller","targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); - if let Some(offset_days) = offset_days { + if let Some((member, offset)) = offset { source["project"]["timezone"] = json!("UTC"); source["recordTypes"]["target"]["fields"] .as_array_mut() @@ -97,11 +120,10 @@ fn registry_with_current_date_offset( .unwrap() .push(json!({ "input":"target", "field":"eligible-on", "currentDate":"on-or-after", - "currentDateOffsetDays":offset_days, "reason":"outside-date-window" + member:offset, "reason":"outside-date-window" })); } - let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); - compile_project(&project, &[], CompileProfile::Authoring).expect("guard project compiles") + source } /// A draft over a fresh target Record whose status is `status` and whose @@ -297,7 +319,7 @@ async fn proposal_apply_reevaluates_the_configured_current_date_offset() { let fixture = client_http::ClientFixture::start( registry_with_current_date_offset( &["name", "status", "capacity", "eligible-on", "jurisdiction"], - Some(30), + Some(("currentDateOffsetDays", 30)), ), claims(), ) @@ -326,6 +348,105 @@ async fn proposal_apply_reevaluates_the_configured_current_date_offset() { fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn proposal_apply_reevaluates_the_configured_current_date_month_offset() { + let fixture = client_http::ClientFixture::start( + registry_with_current_date_offset( + &["name", "status", "capacity", "eligible-on", "jurisdiction"], + Some(("currentDateOffsetMonths", 1)), + ), + claims(), + ) + .await; + let today = fixture + .registry + .local_date_at(time::OffsetDateTime::now_utc()) + .unwrap(); + let threshold = today.checked_add_months(chrono::Months::new(1)).unwrap(); + let (draft, target_id) = draft(&fixture, "open", 10, "month-guard-apply").await; + set_eligible_on(&fixture, &target_id, threshold).await; + let submitted = submit(&fixture, &draft, "month-guard-submit") + .await + .unwrap(); + + // Change only the guarded date. Apply reads current state and enforces the + // same month offset again. + set_eligible_on(&fixture, &target_id, today).await; + let refusal = apply(&fixture, &submitted, "month-guard-apply-key") + .await + .unwrap_err(); + assert_eq!( + refusal.problem_code(), + Some(BRegProblemCode::ActionGuardFailed) + ); + assert_eq!(refusal.guard_reason(), Some("outside-date-window")); + fixture.finish().await; +} + +/// The refusal a transition answers on the wire: its status and problem body. +/// The client error type keeps only the problem code and reason, so the +/// authored label is read from the raw response. +async fn raw_transition( + fixture: &client_http::ClientFixture, + proposal: &BRegProposal, + operation: &str, + body: Value, + key: &str, +) -> (u16, Value) { + let link = serde_json::to_value(proposal).unwrap()["links"][operation].clone(); + let response = reqwest::Client::new() + .post(format!( + "{}{}", + fixture.http.base_url, + link["path"].as_str().unwrap() + )) + .query(&[("accessProfile", link["accessProfile"].as_str().unwrap())]) + .header("idempotency-key", key) + .header("if-match", link["ifMatch"].as_str().unwrap_or("*")) + .json(&body) + .send() + .await + .unwrap(); + let status = response.status().as_u16(); + (status, response.json().await.unwrap()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn submit_and_apply_carry_the_guard_label_only_where_the_reason_rides() { + let fixture = client_http::ClientFixture::start( + registry_with_guard_labels(&["name", "status", "capacity", "jurisdiction"]), + claims(), + ) + .await; + let (retired, _) = draft(&fixture, "retired", 10, "label-submit").await; + let (status, problem) = + raw_transition(&fixture, &retired, "submit", json!({}), "label-submit-key").await; + assert_eq!(status, 412, "{problem}"); + assert_eq!(problem["code"], "action.guard_failed"); + assert_eq!(problem["guardReason"], "target-not-open"); + assert_eq!(problem["detail"], TARGET_NOT_OPEN_LABEL); + + // Apply holds its guards without labels, so a reworded label never + // strands a frozen Proposal, and the refusal names the current label. + let (open, open_id) = draft(&fixture, "open", 10, "label-apply").await; + let submitted = submit(&fixture, &open, "label-apply-submit").await.unwrap(); + set_status(&fixture, &open_id, "retired").await; + let (status, problem) = raw_transition( + &fixture, + &submitted, + "apply", + json!({"submissionVersion":submitted.submission_version(), + "effectDigest":submitted.effect_digest().unwrap()}), + "label-apply-key", + ) + .await; + assert_eq!(status, 412, "{problem}"); + assert_eq!(problem["code"], "action.guard_failed"); + assert_eq!(problem["guardReason"], "target-not-open"); + assert_eq!(problem["detail"], TARGET_NOT_OPEN_LABEL); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn submit_names_a_failed_input_comparison_guard() { let fixture = client_http::ClientFixture::start( diff --git a/crates/registry-breg/tests/postgres_proposal_hooks.rs b/crates/registry-breg/tests/postgres_proposal_hooks.rs index 7355199a96..38333fd9ce 100644 --- a/crates/registry-breg/tests/postgres_proposal_hooks.rs +++ b/crates/registry-breg/tests/postgres_proposal_hooks.rs @@ -412,47 +412,44 @@ async fn native_url_delivery_keeps_exact_bytes_tightened_budgets_and_expired_lea let requests = received.lock().await; assert_eq!(requests.len(), 1); assert_eq!(requests[0].1, bytes); - assert_eq!(requests[0].0["ce-type"], "proposal.submitted"); + let (headers, body) = &requests[0]; + let application_headers = headers + .keys() + .map(|name| name.as_str()) + .filter(|name| !matches!(*name, "host" | "content-length")) + .collect::>(); assert_eq!( - requests[0].0["ce-dataschema"], - registry_breg::proposal_hooks::PROPOSAL_EVENT_SCHEMA + application_headers, + std::collections::BTreeSet::from([ + "accept", + "content-type", + "webhook-id", + "webhook-timestamp", + "webhook-signature", + ]) ); - assert_eq!(requests[0].0["x-registry-delivery-attempt"], "2"); - assert!(requests[0].0["x-registry-signature"] - .to_str() - .unwrap() - .starts_with("v1=")); - use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; - use hmac::{Hmac, KeyInit, Mac}; - let mut mac = Hmac::::new_from_slice(&[7u8; 32]).unwrap(); - mac.update(b"breg-webhook-signature-v1"); - for value in [ - "ce-specversion", - "ce-id", - "ce-source", - "ce-type", - "ce-time", - "ce-dataschema", - "x-registry-event-generation", - "x-registry-delivery-attempt", - "x-registry-delivery-time", - ] - .into_iter() - .map(|name| requests[0].0[name].as_bytes()) - .chain([ - b"POST".as_slice(), - b"/events".as_slice(), - b"application/json".as_slice(), - requests[0].0["idempotency-key"].as_bytes(), - requests[0].1.as_slice(), - ]) { - mac.update(&(value.len() as u64).to_be_bytes()); - mac.update(value); - } + let envelope: Value = serde_json::from_slice(body).unwrap(); + assert_eq!(envelope["type"], "proposal.submitted"); assert_eq!( - requests[0].0["x-registry-signature"].to_str().unwrap(), - format!("v1={}", URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())) + envelope["dataschema"], + registry_breg::proposal_hooks::PROPOSAL_EVENT_SCHEMA ); + assert_eq!(envelope["id"], headers["webhook-id"].to_str().unwrap()); + use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, + }; + verify( + &DeliveryKeys::new(DeliveryKey::new(&[7; 32]).unwrap(), None).unwrap(), + SignedContent { + id: headers["webhook-id"].to_str().unwrap(), + timestamp: headers["webhook-timestamp"].to_str().unwrap(), + signature: headers["webhook-signature"].to_str().unwrap(), + body, + }, + std::time::SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .unwrap(); drop(requests); drop(http); receiver.abort(); diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index 5384525842..4ad6973e0b 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -8,6 +8,7 @@ mod client_http; #[allow(dead_code)] mod postgres_harness; +use self::COMPLETION_KEY as INCOMING_TOKEN; use axum::{ extract::{Path as AxumPath, State}, http::{HeaderMap, StatusCode}, @@ -30,6 +31,9 @@ use registry_breg_client::{ BRegActionInvocationRequest, BRegCreateRequest, BRegDirectWrite, BRegIdempotencyKey, BRegRecordFormat, }; +use registry_platform_crypto::delivery_signature::{ + sign, DeliveryKey, DeliveryKeys, SignedContent, +}; use registry_platform_testing::CapturedDiagnosticLogs; use registry_review_client::{ BearerToken, PolicyBinding, ReviewCancelRequest, ReviewCancelResponse, ReviewClient, @@ -48,15 +52,51 @@ use std::{ use tokio::sync::Notify; use tracing::instrument::WithSubscriber; use uuid::Uuid; +#[cfg(feature = "tooling")] use zeroize::Zeroizing; const AUTHORITY: &str = "private-review-authority-canary"; const PRODUCER: &str = "proposal-producer"; const OUTGOING_TOKEN: &str = "synthetic-outgoing-review-token"; -const INCOMING_TOKEN: &str = "synthetic-incoming-completion-token"; +const COMPLETION_KEY: &str = "synthetic-incoming-completion-key-canary"; +const PREVIOUS_COMPLETION_KEY: &[u8] = &[2; 32]; +const OTHER_COMPLETION_KEY: &[u8] = &[3; 32]; const RECIPIENT: &str = "private-completion-recipient-canary"; const TRACE: &str = "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"; +fn completion_keys(current: &[u8], previous: Option<&[u8]>) -> DeliveryKeys { + DeliveryKeys::new( + DeliveryKey::new(current).unwrap(), + previous.map(|key| DeliveryKey::new(key).unwrap()), + ) + .unwrap() +} + +fn verify_completion( + receiver: &ReviewCompletionReceiver, + keys: &DeliveryKeys, + recipient: &str, + completion: &ReviewCompletion, +) -> Result { + let now = std::time::SystemTime::now(); + let timestamp = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + let id = completion.event_id.to_string(); + let body = serde_json::to_vec(completion).unwrap(); + let signature = sign(keys, &id, timestamp, &body).unwrap(); + receiver + .verify_completion( + recipient, + SignedContent { + id: &id, + timestamp: ×tamp.to_string(), + signature: &signature, + body: &body, + }, + now, + ) + .map(|(authority, _)| authority.to_owned()) +} + struct Token; #[async_trait::async_trait] impl registry_platform_httputil::TokenProvider for Token { @@ -151,21 +191,31 @@ impl Authority { let client = Arc::new( ReviewClient::new(ReviewClientConfig::new(endpoint.parse().unwrap())).unwrap(), ); - let authority = Arc::new( - ReviewAuthorityClient::new( - AUTHORITY.into(), - ReviewClient::new(ReviewClientConfig::new(endpoint.parse().unwrap())).unwrap(), - Arc::new(Token), - "producer".into(), - PRODUCER.into(), - 7, - Some(Zeroizing::new(INCOMING_TOKEN.into())), - Some(RECIPIENT.into()), + let make_authority = |id: &str, recipient: &str, keys| { + Arc::new( + ReviewAuthorityClient::new( + id.into(), + ReviewClient::new(ReviewClientConfig::new(endpoint.parse().unwrap())).unwrap(), + Arc::new(Token), + "producer".into(), + PRODUCER.into(), + 7, + Some(keys), + Some(recipient.into()), + ) + .unwrap(), ) - .unwrap(), - ); + }; let registry = Arc::new( - ReviewAuthorityRegistry::new(BTreeMap::from([(AUTHORITY.into(), authority)])).unwrap(), + ReviewAuthorityRegistry::new(BTreeMap::from([( + AUTHORITY.into(), + make_authority( + AUTHORITY, + RECIPIENT, + completion_keys(COMPLETION_KEY.as_bytes(), Some(PREVIOUS_COMPLETION_KEY)), + ), + )])) + .unwrap(), ); Self { registry, @@ -1148,7 +1198,7 @@ async fn submission_logs_identify_first_delivery_retry_and_settlement_without_va assert_eq!(job(&fixture, id).await["state"], "accepted"); for canary in [ OUTGOING_TOKEN, - INCOMING_TOKEN, + COMPLETION_KEY, "delivery-log-canary", &id.to_string(), ] { @@ -1173,12 +1223,20 @@ async fn native_completion_inbox_deduplicates_refuses_substitution_correlates_an completed_at: result.completed_at, }; let receiver = ReviewCompletionReceiver::new(fixture.pool.clone(), authority.registry.clone()); - for (token, recipient) in [ - (OUTGOING_TOKEN, RECIPIENT), - (INCOMING_TOKEN, "wrong-recipient"), - ("wrong-token", RECIPIENT), + for (key, recipient) in [ + (&[9u8; 32][..], RECIPIENT), + (COMPLETION_KEY.as_bytes(), "wrong-recipient"), + (OTHER_COMPLETION_KEY, RECIPIENT), ] { - assert!(receiver.authority(token, recipient).is_none()); + assert_eq!( + verify_completion( + &receiver, + &completion_keys(key, None), + recipient, + &completion + ), + Err(registry_platform_authcommon::FailedCheck::DeliverySignature) + ); } assert_eq!( fixture @@ -1193,7 +1251,13 @@ async fn native_completion_inbox_deduplicates_refuses_substitution_correlates_an .get::<_, i64>(0), 0 ); - let (matched, _) = receiver.authority(INCOMING_TOKEN, RECIPIENT).unwrap(); + let matched = verify_completion( + &receiver, + &completion_keys(COMPLETION_KEY.as_bytes(), None), + RECIPIENT, + &completion, + ) + .unwrap(); assert_eq!(matched, AUTHORITY); receiver.receive(&matched, &completion).await.unwrap(); receiver.receive(&matched, &completion).await.unwrap(); @@ -1217,7 +1281,7 @@ async fn native_completion_inbox_deduplicates_refuses_substitution_correlates_an for canary in [ AUTHORITY, RECIPIENT, - INCOMING_TOKEN, + COMPLETION_KEY, OUTGOING_TOKEN, &completion.event_id.to_string(), &completion.request_id.to_string(), @@ -1294,7 +1358,7 @@ async fn native_completion_inbox_deduplicates_refuses_substitution_correlates_an for canary in [ AUTHORITY, RECIPIENT, - INCOMING_TOKEN, + COMPLETION_KEY, OUTGOING_TOKEN, &completion.event_id.to_string(), &completion.request_id.to_string(), @@ -1319,6 +1383,31 @@ async fn native_completion_inbox_deduplicates_refuses_substitution_correlates_an fixture.finish().await; } +#[tokio::test] +async fn a_completion_signed_during_rotation_is_accepted_once() { + let authority = Authority::start(false, true).await; + let fixture = fixture(&authority).await; + let receiver = ReviewCompletionReceiver::new(fixture.pool.clone(), authority.registry.clone()); + let completion = ReviewCompletion { + event_type: ReviewCompletionType::ReviewCompleted, + event_id: Uuid::new_v4(), + request_id: Uuid::new_v4(), + result_id: Uuid::new_v4(), + completed_at: chrono::Utc::now(), + }; + let keys = completion_keys(COMPLETION_KEY.as_bytes(), Some(PREVIOUS_COMPLETION_KEY)); + for _ in 0..2 { + let matched = verify_completion(&receiver, &keys, RECIPIENT, &completion).unwrap(); + receiver.receive(&matched, &completion).await.unwrap(); + } + let row = fixture.database.admin.query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_review_completions WHERE event_id=$1", + &[&completion.event_id], + ).await.unwrap(); + assert_eq!(row.get::<_, i64>(0), 1); + fixture.finish().await; +} + #[tokio::test] async fn native_submission_reclaims_exact_work_and_fences_late_success_and_failure() { for first_succeeds in [false, true] { @@ -2026,7 +2115,7 @@ async fn native_submission_remote_refusal_warns_the_operator_without_values() { ); for canary in [ OUTGOING_TOKEN, - INCOMING_TOKEN, + COMPLETION_KEY, RECIPIENT, "The producer is not allowed.", &id.to_string(), diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index 8a0b1185d5..efc02483ae 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -139,7 +139,7 @@ async fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -1410,7 +1410,7 @@ async fn proposal_disclosures_refuse_a_signed_grant_expiring_during_terminal_aud let entries = Arc::new(std::sync::Mutex::new(Vec::new())); let audit = RegistryAudit::new( AuditProfile::production_from_secret_bytes(vec![0x61; 32].into()).unwrap(), - AuditWriter::from_line_sink(Box::new(DelayedTerminal { + AuditWriter::from_line_sink_without_posture(Box::new(DelayedTerminal { expiry, reached: reached.clone(), was_current: was_current.clone(), diff --git a/crates/registry-breg/tests/postgres_proposal_task_authority.rs b/crates/registry-breg/tests/postgres_proposal_task_authority.rs index f454c4c941..514edd685e 100644 --- a/crates/registry-breg/tests/postgres_proposal_task_authority.rs +++ b/crates/registry-breg/tests/postgres_proposal_task_authority.rs @@ -330,7 +330,7 @@ async fn authenticator( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) diff --git a/crates/registry-breg/tests/postgres_registry_extensibility.rs b/crates/registry-breg/tests/postgres_registry_extensibility.rs index cf5f031974..adbe037db8 100644 --- a/crates/registry-breg/tests/postgres_registry_extensibility.rs +++ b/crates/registry-breg/tests/postgres_registry_extensibility.rs @@ -510,7 +510,7 @@ fn build_app( let key_source = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = Arc::new( RegistryAuthenticator::new( diff --git a/crates/registry-breg/tests/postgres_required_filters.rs b/crates/registry-breg/tests/postgres_required_filters.rs index f1e1bcb177..6a57d1b78f 100644 --- a/crates/registry-breg/tests/postgres_required_filters.rs +++ b/crates/registry-breg/tests/postgres_required_filters.rs @@ -107,7 +107,7 @@ async fn setup() -> (TestDatabase, Router, MockIdp) { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier = oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]); verifier.allowed_clients = vec!["portal".into()]; diff --git a/crates/registry-breg/tests/postgres_startup.rs b/crates/registry-breg/tests/postgres_startup.rs index 73e7075d7d..934e4b856d 100644 --- a/crates/registry-breg/tests/postgres_startup.rs +++ b/crates/registry-breg/tests/postgres_startup.rs @@ -2801,7 +2801,7 @@ async fn assert_audit_destination_has_one_writer_and_checks_take_none( serving_config: &Path, unopened: &Path, ) { - let serving_writer = registry_platform_audit::AuditWriter::open( + let serving_writer = registry_platform_audit::AuditWriter::open_without_posture( registry_platform_audit::AuditDestination::from_settings( registry_platform_audit::AuditDestinationKind::File, Some(configured_audit_path(serving_config)), @@ -2965,7 +2965,7 @@ async fn mock_idp_key_source(idp: &MockIdp) -> Arc { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("MockIdp discovery fetch succeeds"); @@ -2979,7 +2979,7 @@ async fn mock_idp_key_source(idp: &MockIdp) -> Arc { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::ZERO, }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )) } diff --git a/crates/registry-breg/tests/postgres_webhook_delivery.rs b/crates/registry-breg/tests/postgres_webhook_delivery.rs index 4fd373769a..36712a05bc 100644 --- a/crates/registry-breg/tests/postgres_webhook_delivery.rs +++ b/crates/registry-breg/tests/postgres_webhook_delivery.rs @@ -12,9 +12,8 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::engine::general_purpose::STANDARD; use base64::Engine as _; -use hmac::{Hmac, KeyInit, Mac}; use postgres_harness::TestDatabase; use rcgen::{generate_simple_self_signed, CertifiedKey}; use registry_breg::audit::HOOK_AUDIT_SCHEMA; @@ -34,6 +33,9 @@ use registry_breg::postgres::{ use registry_breg::runtime_config::parse_runtime_config; use registry_platform_audit::AuditProfile; use registry_platform_canonical_json::canonicalize_json; +use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, +}; use registry_platform_hooks::MAX_OUTPUT_BYTES; use serde_json::{json, Map, Value}; use sha2::{Digest, Sha256}; @@ -60,9 +62,6 @@ const HMAC_KEY: &[u8] = b"webhook-delivery-signing-key-0123456789abcdef"; const RECORD_VALUE_CANARY: &str = "restricted-record-value-canary"; const KEY_REF_CANARY: &str = "webhook-signing-key-canary"; const CA_REF_CANARY: &str = "webhook-ca-bundle-canary"; -const SIGNATURE_DOMAIN: &[u8] = b"breg-webhook-signature-v1"; - -type HmacSha256 = Hmac; /// The local hook handlers the running package holds. A package whose hooks /// are all `url` yields an empty registry, and every delivery it claims takes @@ -205,9 +204,9 @@ async fn real_postgres_webhook_delivery_retry_dead_letter_replay_is_package_boun let second_attempt = receiver.request(1).await; assert_exact_request(&second_attempt, &first).await; assert_eq!( - header(&first_attempt, "idempotency-key"), - header(&second_attempt, "idempotency-key"), - "idempotency is stable across attempts in one generation" + header(&first_attempt, "webhook-id"), + header(&second_attempt, "webhook-id"), + "webhook id is stable across attempts" ); assert_eq!( delivery_state(&database, &first).await, @@ -455,8 +454,8 @@ async fn real_postgres_webhook_delivery_retry_dead_letter_replay_is_package_boun let timeout_first = receiver.request(2).await; let timeout_second = receiver.request(3).await; assert_eq!( - header(&timeout_first, "idempotency-key"), - header(&timeout_second, "idempotency-key") + header(&timeout_first, "webhook-id"), + header(&timeout_second, "webhook-id") ); assert_eq!( delivery_state(&database, &timeout_event).await, @@ -530,10 +529,10 @@ async fn real_postgres_webhook_delivery_retry_dead_letter_replay_is_package_boun assert_eq!(service.deliver_once().await, Ok(HookWorkOutcome::Delivered)); receiver.wait_for_count(5).await; let replay_request = receiver.request(4).await; - assert_ne!( - header(&timeout_first, "idempotency-key"), - header(&replay_request, "idempotency-key"), - "operator replay changes the deterministic generation binding" + assert_eq!( + header(&timeout_first, "webhook-id"), + header(&replay_request, "webhook-id"), + "operator replay preserves the event id" ); // The replay is a request before its reset and a response once the // reset commits, under one correlation. @@ -616,8 +615,8 @@ async fn real_postgres_webhook_delivery_retry_dead_letter_replay_is_package_boun ); receiver.wait_for_count(6).await; assert_eq!( - header(&receiver.request(5).await, "x-registry-delivery-attempt"), - "2" + delivery_state(&database, &recovered).await, + (1, "delivered".to_owned(), 2) ); let stale_changed = database .admin @@ -1711,6 +1710,106 @@ async fn real_postgres_webhook_delivery_finishes_prior_package_work_after_compat database.cleanup().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn real_postgres_adding_a_previous_key_keeps_retained_delivery_deliverable() { + let receiver = HttpsReceiver::start().await; + let database = TestDatabase::create(6).await; + let (migration, migration_task) = database.connect_migration().await; + let compiled = compiled_registry(); + install_compiled_schema(&migration, &compiled, &database.runtime_role) + .await + .unwrap(); + let identity = initialize_compiled_registry_state_for_test( + &migration, + &database.runtime_role, + &compiled, + registry_state_test_identity(), + ) + .await + .unwrap(); + migration_task.abort(); + + let fixture = DestinationFixture::new(&receiver); + let original = Arc::new(fixture.activate(&compiled)); + let pool = database.runtime_config.build_pool().unwrap(); + let audit_profile = AuditProfile::production_from_secret_bytes(vec![0x7c; 32].into()).unwrap(); + let lock_key = RegistryLockKey::derive("webhook-delivery-registry").unwrap(); + let coordinator = MutationTransaction::new_with_event_destinations( + lock_key, + Duration::from_secs(2), + identity.clone(), + "webhook-delivery-instance", + database.audit(audit_profile.clone()), + Some(original.clone()), + ); + let plan = MutationPlan::from_compiled(&compiled, "records.case.create").unwrap(); + let mut connection = pool.get_for_test().await.unwrap(); + let captured = create_event( + &database, + &coordinator, + &mut connection, + &plan, + &mutation_claims(&compiled), + "delivery-before-rotation", + "captured-before-rotation", + ) + .await; + drop(connection); + drop(coordinator); + + let new_key = [7; 32]; + write_secret(&fixture.secret_root.join(KEY_REF_CANARY), &new_key); + write_secret(&fixture.secret_root.join("previous-key"), HMAC_KEY); + let rotated = Arc::new(fixture.activate_with_previous( + &compiled, + " previousHmacSha256KeyRef: secret:file/previous-key\n", + )); + assert_eq!(original.binding_digest(), rotated.binding_digest()); + let service = HookDeliveryService::new( + pool.clone(), + rotated, + hook_handlers(&compiled, &identity.activation_id), + Arc::new(compiled), + identity, + "webhook-delivery-instance", + lock_key, + Duration::from_secs(2), + database.audit(audit_profile), + ); + service.verify_retained_bindings().await.unwrap(); + receiver.enqueue(ResponsePlan::Status(204)).await; + assert_eq!(service.deliver_once().await, Ok(HookWorkOutcome::Delivered)); + receiver.wait_for_count(1).await; + let request = receiver.request(0).await; + assert_eq!(request.body, captured.payload); + assert_eq!( + header(&request, "webhook-id"), + captured.event_id.to_string() + ); + let signatures: Vec<_> = header(&request, "webhook-signature").split(' ').collect(); + assert_eq!(signatures.len(), 2); + verify_request(&request, &new_key); + verify_request(&request, HMAC_KEY); + for (key, expected) in [(&new_key[..], signatures[0]), (HMAC_KEY, signatures[1])] { + let keys = DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap(); + let timestamp = header(&request, "webhook-timestamp").parse().unwrap(); + assert_eq!( + registry_platform_crypto::delivery_signature::sign( + &keys, + header(&request, "webhook-id"), + timestamp, + &request.body, + ) + .unwrap(), + expected + ); + } + drop(service); + drop(pool); + receiver.stop().await; + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_webhook_worker_records_its_last_success_on_an_idle_iteration() { let receiver = HttpsReceiver::start().await; @@ -2725,7 +2824,7 @@ async fn assert_webhook_audits_are_closed_and_value_free(database: &TestDatabase KEY_REF_CANARY, CA_REF_CANARY, std::str::from_utf8(HMAC_KEY).expect("test HMAC key is UTF-8"), - "x-registry-signature", + "webhook-signature", "upstream", ] { assert!(!joined.contains(forbidden), "hook audit remains value-free"); @@ -2747,77 +2846,53 @@ async fn assert_exact_request(request: &ReceivedRequest, event: &CapturedEvent) request.body == event.payload, "request body is the exact captured canonical bytes" ); - assert_eq!(header(request, "ce-id"), event.event_id.to_string()); - assert_eq!(header(request, "ce-specversion"), "1.0"); - assert_eq!(header(request, "ce-source"), EVENT_SOURCE); - assert_eq!(header(request, "ce-type"), "case-created"); + let application_headers = request + .headers + .keys() + .map(String::as_str) + .filter(|name| !matches!(*name, "host" | "content-length")) + .collect::>(); + assert_eq!( + application_headers, + std::collections::BTreeSet::from([ + "accept", + "content-type", + "webhook-id", + "webhook-timestamp", + "webhook-signature", + ]) + ); + assert_eq!(header(request, "webhook-id"), event.event_id.to_string()); + assert_eq!(header(request, "accept"), "application/json"); + assert_eq!(header(request, "content-type"), "application/json"); + let envelope: Value = serde_json::from_slice(&request.body).unwrap(); + assert_eq!(envelope["id"], header(request, "webhook-id")); + assert_eq!(envelope["source"], EVENT_SOURCE); + assert_eq!(envelope["type"], "case-created"); assert_eq!( - header(request, "ce-time"), + envelope["time"], OffsetDateTime::from(event.created_at) .format(&Rfc3339) - .expect("captured event time formats") + .unwrap() ); - assert_eq!(header(request, "ce-dataschema"), event.data_schema); - assert_eq!(header(request, "x-registry-event-generation"), "1"); - assert_eq!(header(request, "content-type"), "application/json"); - let signature = independent_signature(IndependentSignatureFields { - event_id: header(request, "ce-id"), - source: header(request, "ce-source"), - event_type: header(request, "ce-type"), - time: header(request, "ce-time"), - data_schema: header(request, "ce-dataschema"), - generation: header(request, "x-registry-event-generation"), - attempt: header(request, "x-registry-delivery-attempt"), - delivery_time: header(request, "x-registry-delivery-time"), - method: &request.method, - request_target: &request.target, - content_type: header(request, "content-type"), - idempotency_key: header(request, "idempotency-key"), - body: &request.body, - }); - assert_eq!(header(request, "x-registry-signature"), signature); -} - -struct IndependentSignatureFields<'a> { - event_id: &'a str, - source: &'a str, - event_type: &'a str, - time: &'a str, - data_schema: &'a str, - generation: &'a str, - attempt: &'a str, - delivery_time: &'a str, - method: &'a str, - request_target: &'a str, - content_type: &'a str, - idempotency_key: &'a str, - body: &'a [u8], + assert_eq!(envelope["dataschema"], event.data_schema); + verify_request(request, HMAC_KEY); } -fn independent_signature(fields: IndependentSignatureFields<'_>) -> String { - let mut input = SIGNATURE_DOMAIN.to_vec(); - for value in [ - b"1.0".as_slice(), - fields.event_id.as_bytes(), - fields.source.as_bytes(), - fields.event_type.as_bytes(), - fields.time.as_bytes(), - fields.data_schema.as_bytes(), - fields.generation.as_bytes(), - fields.attempt.as_bytes(), - fields.delivery_time.as_bytes(), - fields.method.as_bytes(), - fields.request_target.as_bytes(), - fields.content_type.as_bytes(), - fields.idempotency_key.as_bytes(), - fields.body, - ] { - input.extend_from_slice(&(value.len() as u64).to_be_bytes()); - input.extend_from_slice(value); - } - let mut mac = HmacSha256::new_from_slice(HMAC_KEY).expect("test HMAC key is valid"); - mac.update(&input); - format!("v1={}", URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())) +fn verify_request(request: &ReceivedRequest, key: &[u8]) { + let keys = DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap(); + verify( + &keys, + SignedContent { + id: header(request, "webhook-id"), + timestamp: header(request, "webhook-timestamp"), + signature: header(request, "webhook-signature"), + body: &request.body, + }, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .expect("the exact packet verifies"); } fn compiled_registry() -> registry_breg::CompiledRegistry { @@ -2969,6 +3044,14 @@ impl DestinationFixture { fn activate( &self, compiled: ®istry_breg::CompiledRegistry, + ) -> ActivatedEventDestinationRegistry { + self.activate_with_previous(compiled, "") + } + + fn activate_with_previous( + &self, + compiled: &CompiledRegistry, + previous: &str, ) -> ActivatedEventDestinationRegistry { parse_runtime_config(&self.runtime_config(&format!( r#"destinations: @@ -2980,7 +3063,7 @@ impl DestinationFixture { dnsFamily: ipv4-only allowedPrivateCidrs: [] hmacSha256KeyRef: secret:file/{KEY_REF_CANARY} - classificationCeiling: restricted +{previous} classificationCeiling: restricted tls: caBundleRef: secret:file/{CA_REF_CANARY} deliveryCeilings: diff --git a/crates/registry-breg/tests/refactor_contract.rs b/crates/registry-breg/tests/refactor_contract.rs index 2e8db19304..4be44cca0d 100644 --- a/crates/registry-breg/tests/refactor_contract.rs +++ b/crates/registry-breg/tests/refactor_contract.rs @@ -898,7 +898,9 @@ fn immediate_mode_cannot_bypass_target_proposal_policy() { .iter_mut() .find(|action| action.id == "deactivate-facility") .unwrap() - .execution = registry_breg::contract::ActionExecutionSource::Immediate {}; + .execution = registry_breg::contract::ActionExecutionSource::Immediate { + concurrency: Default::default(), + }; for profile in &mut project.access_profiles { profile .permissions diff --git a/crates/registry-breg/tests/row_boundary_sets.rs b/crates/registry-breg/tests/row_boundary_sets.rs new file mode 100644 index 0000000000..a2984e4f1c --- /dev/null +++ b/crates/registry-breg/tests/row_boundary_sets.rs @@ -0,0 +1,387 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Named row-boundary sets: `rowBoundarySets` declares a reusable list of +//! boundaries once, and `rowBoundaries: {rowBoundarySet: }` reaches it +//! wherever a row reach is written. A grant still writes its own +//! `rowBoundaries`, so reach stays visible at every grant. A reference is +//! expanded when the file is read, and an empty list means every row, so a +//! reference never resolves to an empty list. + +use registry_breg::contract::{parse_module_yaml, parse_project_yaml, RegistryProject}; +use registry_breg::{compile_project, CompileFailure, CompileProfile, CompiledRegistry}; +use serde_json::{json, Value}; + +const SET: &str = "same-district"; +const REFERENCE_CODE: &str = "breg.row-boundary-set.reference-invalid"; + +fn boundary() -> Value { + json!({"field":"district","claim":"districts","operator":"in"}) +} + +fn reference() -> Value { + json!({"rowBoundarySet": SET}) +} + +/// A project that writes its row reach inline at every site: a record +/// permission, an Action target, a Proposal target and a record type's +/// access requirement. +fn inline() -> Value { + json!({ + "datasets":{"test-dataset": {}}, + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", "kind":"BRegProject", + "project":{"id":"access-example","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://access-example.example.test"}, + "recordTypes":{"entry": {"primaryDataset":"test-dataset","route":"entries","mutationMode":"mutable","classification":"internal", + "accessRequirements":{"rowBoundaries":[boundary()]}, + "fields":[{"id":"code","type":"string","maximumLength":32,"classification":"internal"}, + {"id":"district","type":"string","maximumLength":32,"classification":"internal"}]}}, + "accessProfiles":{"reader": {"principalClaim":"registry_principal","requiredScopes":["entry:read"], + "permissions":{ + "records":[{"recordType":"entry","operations":["get","list"], + "readableFields":["code","district"],"filterableFields":["district"], + "rowBoundaries":[boundary()]}], + "actions":[{"action":"register","operations":["invoke"], + "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}], + "proposals":[{"action":"register","operations":["get"],"ownership":"caller", + "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}] + }}} + }) +} + +const SITES: [&str; 4] = [ + "/accessProfiles/reader/permissions/records/0/rowBoundaries", + "/accessProfiles/reader/permissions/actions/0/targets/0/rowBoundaries", + "/accessProfiles/reader/permissions/proposals/0/targets/0/rowBoundaries", + "/recordTypes/entry/accessRequirements/rowBoundaries", +]; + +/// `inline()` with the set declared once and every site referencing it. +fn by_reference() -> Value { + let mut value = inline(); + value["rowBoundarySets"] = json!({ SET: [boundary()] }); + for site in SITES { + set(&mut value, site, reference()); + } + value +} + +fn set(value: &mut Value, pointer: &str, written: Value) { + *value + .pointer_mut(pointer) + .unwrap_or_else(|| panic!("{pointer} exists")) = written; +} + +fn read(value: &Value) -> Result { + parse_project_yaml(&serde_json::to_vec(value).unwrap()) +} + +fn compile(value: &Value) -> Result { + compile_project(&read(value)?, &[], CompileProfile::Authoring) +} + +/// The one refusal a read answers with, as its code, path, and message. +fn refusal(value: &Value) -> (String, String, String) { + let failure = read(value).expect_err("the project is refused when it is read"); + let [diagnostic] = failure.diagnostics() else { + panic!("one diagnostic refuses the project: {failure:?}"); + }; + ( + diagnostic.code.clone(), + diagnostic.path.clone(), + diagnostic.message.clone(), + ) +} + +/// Compiling needs the Actions the grants name, so a compiled comparison keeps +/// the record permission and the record type's requirement. +fn compilable(mut value: Value) -> Value { + let permissions = value["accessProfiles"]["reader"]["permissions"] + .as_object_mut() + .unwrap(); + permissions.remove("actions"); + permissions.remove("proposals"); + value +} + +#[test] +fn a_reference_reads_as_the_inline_list_at_every_site() { + let referenced = read(&by_reference()).expect("a reference is accepted at every site"); + let written = read(&inline()).expect("the inline form is accepted"); + assert_eq!( + serde_json::to_value(&referenced).unwrap(), + serde_json::to_value(&written).unwrap(), + "a reference expands to the boundaries the set lists, and the set is not part of the read project" + ); + let compiled = compile(&compilable(by_reference())).expect("the referenced project compiles"); + let inline_compiled = compile(&compilable(inline())).expect("the inline project compiles"); + assert_eq!( + serde_json::to_value(&compiled).unwrap(), + serde_json::to_value(&inline_compiled).unwrap(), + "the compiled model does not record where a boundary was written" + ); + let permission = &referenced.access_profiles[0].permissions; + assert_eq!(permission.entities[0].row_boundaries.len(), 1); + assert_eq!(permission.actions[0].targets[0].row_boundaries.len(), 1); + assert_eq!(permission.proposals[0].targets[0].row_boundaries.len(), 1); + assert_eq!( + referenced.entities[0] + .access_requirements + .as_ref() + .expect("the record type carries its requirement") + .row_boundaries + .len(), + 1 + ); +} + +#[test] +fn each_site_takes_the_reference_on_its_own() { + for site in SITES { + let mut value = inline(); + value["rowBoundarySets"] = json!({ SET: [boundary()] }); + set(&mut value, site, reference()); + let project = read(&value).unwrap_or_else(|failure| panic!("{site}: {failure:?}")); + assert_eq!( + serde_json::to_value(&project).unwrap(), + serde_json::to_value(read(&inline()).unwrap()).unwrap(), + "{site}" + ); + } +} + +#[test] +fn an_unknown_set_is_refused_at_the_reference() { + let mut value = by_reference(); + set( + &mut value, + SITES[0], + json!({"rowBoundarySet": "no-such-set"}), + ); + let (code, path, message) = refusal(&value); + assert_eq!(code, REFERENCE_CODE, "{message}"); + assert!( + path.ends_with("permissions.records[0].rowBoundaries.rowBoundarySet"), + "{path}" + ); + + // No declaration at all is the same refusal, never an unrestricted read. + let mut undeclared = inline(); + set(&mut undeclared, SITES[0], reference()); + let (code, _, message) = refusal(&undeclared); + assert_eq!(code, REFERENCE_CODE, "{message}"); +} + +#[test] +fn a_reference_is_a_mapping_with_one_string_member() { + for written in [ + json!({"rowBoundarySet": SET, "field": "district"}), + json!({"rowBoundarySet": ["a"]}), + json!({"rowBoundarySet": 3}), + ] { + let mut value = by_reference(); + set(&mut value, SITES[0], written); + let (code, _, message) = refusal(&value); + assert_eq!(code, REFERENCE_CODE, "{message}"); + } +} + +#[test] +fn a_set_lists_at_least_one_boundary_and_is_never_unrestricted() { + for written in [json!([]), json!("unrestricted")] { + let mut value = by_reference(); + value["rowBoundarySets"][SET] = written; + let (code, path, message) = refusal(&value); + assert_eq!(code, "config.invalid-value", "{message}"); + assert_eq!(path, format!("project.rowBoundarySets.{SET}")); + assert!( + message.contains("at least one row boundary"), + "the refusal says what a set holds: {message}" + ); + } +} + +#[test] +fn an_unresolved_reference_never_decodes_to_an_empty_list() { + // The reader expands references before typed decoding. A path that + // reaches the typed model without it must be refused, because an empty + // list means every row. + serde_json::from_value::(inline()) + .expect("the same project written inline decodes, so only the reference is refused"); + let value = by_reference(); + let decoded = serde_json::from_value::(value); + let error = decoded.expect_err("a reference that reaches the typed model is refused"); + assert!( + error.to_string().contains("a row boundary set reference"), + "the typed model names the unexpanded reference: {error}" + ); +} + +/// A structured field whose schema literal holds a mapping shaped like a +/// reference. The shape is schema data here, not a row reach. +fn with_reference_shaped_literal(mut value: Value, name: &str) -> Value { + value["recordTypes"]["entry"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"payload","type":"structured","maximumBytes":256,"classification":"internal", + "schema":{"type":"object","additionalProperties":false, + "const":{"rowBoundaries":{"rowBoundarySet": name}}}})); + value +} + +#[test] +fn a_reference_shaped_schema_literal_is_data_and_never_a_reference() { + const LITERAL: &str = "/recordTypes/entry/fields/2/schema/const"; + for (declared, name) in [(false, "no-such-set"), (true, SET)] { + let mut value = with_reference_shaped_literal(inline(), name); + if declared { + value["rowBoundarySets"] = json!({ SET: [boundary()] }); + } + let parsed = read(&value).expect("a schema literal is not a row boundary reference"); + let written = serde_json::to_value(&parsed).unwrap(); + assert_eq!( + written.pointer(LITERAL), + Some(&json!({"rowBoundaries":{"rowBoundarySet": name}})), + "the literal is kept as written (set declared: {declared})" + ); + } +} + +#[test] +fn a_reference_shaped_schema_literal_beside_a_real_reference_stays_unchanged() { + let value = with_reference_shaped_literal(by_reference(), SET); + let parsed = read(&value).expect("references and literals read together"); + let written = serde_json::to_value(&parsed).unwrap(); + assert_eq!( + written.pointer("/recordTypes/entry/fields/2/schema/const"), + Some(&json!({"rowBoundaries":{"rowBoundarySet": SET}})) + ); + assert_eq!( + written.pointer("/accessProfiles/reader/permissions/records/0/rowBoundaries"), + Some(&json!([boundary()])) + ); +} + +#[test] +fn a_module_profile_takes_the_reference_where_it_writes_its_reach() { + let module = serde_json::to_vec(&json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule", + "id":"extra","version":"1", + "rowBoundarySets":{ SET: [boundary()] }, + "extendRecordTypes":{"entry": {"accessProfiles":{"auditor":{ + "principalClaim":"registry_principal","requiredScopes":"unrestricted", + "operations":["get"],"readableFields":["code"], + "rowBoundaries": reference()}}}} + })) + .unwrap(); + let parsed = parse_module_yaml(&module).expect("a module profile reaches its own set"); + let written = serde_json::to_value(&parsed).unwrap(); + assert_eq!( + written.pointer("/extendRecordTypes/entry/accessProfiles/auditor/rowBoundaries"), + Some(&json!([boundary()])) + ); +} + +#[test] +fn a_set_field_missing_on_the_record_type_is_refused_as_an_inline_boundary_is() { + let mut referenced = compilable(by_reference()); + referenced["rowBoundarySets"][SET][0]["field"] = json!("missing"); + let mut written = compilable(inline()); + for site in [SITES[0], SITES[3]] { + written.pointer_mut(site).unwrap()[0]["field"] = json!("missing"); + } + let by_set = compile(&referenced).expect_err("a boundary on a missing field is refused"); + let by_hand = compile(&written).expect_err("a boundary on a missing field is refused"); + let summarize = |failure: &CompileFailure| { + failure + .diagnostics() + .iter() + .map(|diagnostic| (diagnostic.code.clone(), diagnostic.message.clone())) + .collect::>() + }; + assert_eq!(summarize(&by_set), summarize(&by_hand)); + let codes: Vec<_> = summarize(&by_set) + .into_iter() + .map(|(code, _)| code) + .collect(); + for expected in [ + "breg.access-profile.field-unknown", + "breg.access.requirements-row-boundary-invalid", + ] { + assert!( + codes.iter().any(|code| code == expected), + "the refusal carries {expected}: {codes:?}" + ); + } +} + +#[test] +fn unrestricted_inline_lists_and_omission_keep_their_meaning() { + let mut value = by_reference(); + set(&mut value, SITES[0], json!("unrestricted")); + set(&mut value, SITES[1], json!([boundary()])); + let project = read(&value).expect("the three forms sit beside each other"); + let permissions = &project.access_profiles[0].permissions; + assert!(permissions.entities[0].row_boundaries.is_empty()); + assert_eq!(permissions.actions[0].targets[0].row_boundaries.len(), 1); + assert_eq!(permissions.proposals[0].targets[0].row_boundaries.len(), 1); + + let mut omitted = by_reference(); + omitted + .pointer_mut("/accessProfiles/reader/permissions/records/0") + .and_then(Value::as_object_mut) + .unwrap() + .remove("rowBoundaries"); + let (code, _, message) = refusal(&omitted); + assert_eq!(code, "config.invalid-value", "{message}"); + assert!( + message.contains("write unrestricted to reach every row"), + "{message}" + ); +} + +#[test] +fn a_module_resolves_its_own_sets_and_never_the_projects() { + let module = |set_declared: bool| { + let mut module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule", + "id":"extra","version":"1", + "extendRecordTypes":{"entry": {"accessRequirements":{"rowBoundaries": reference()}}} + }); + if set_declared { + module["rowBoundarySets"] = json!({ SET: [boundary()] }); + } + serde_json::to_vec(&module).unwrap() + }; + let parsed = parse_module_yaml(&module(true)).expect("a module reaches its own set"); + let written = serde_json::to_value(&parsed).unwrap(); + assert_eq!( + written.pointer("/extendRecordTypes/entry/accessRequirements/rowBoundaries"), + Some(&json!([boundary()])) + ); + assert!(written.get("rowBoundarySets").is_none()); + + let failure = parse_module_yaml(&module(false)) + .expect_err("a module does not see a set its project declares"); + let [diagnostic] = failure.diagnostics() else { + panic!("one diagnostic refuses the module: {failure:?}"); + }; + assert_eq!(diagnostic.code, REFERENCE_CODE); +} + +#[test] +fn the_authoring_schema_accepts_the_reference_and_the_set_declaration() { + let schema = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/generated/authoring/registry-project.schema.json"), + ) + .expect("the generated authoring schema is committed"); + let schema: Value = serde_json::from_str(&schema).unwrap(); + assert!( + schema.pointer("/properties/rowBoundarySets").is_some(), + "the project schema declares rowBoundarySets" + ); + let text = schema.to_string(); + assert!( + text.contains("\"rowBoundarySet\""), + "the schema describes the reference mapping" + ); +} diff --git a/crates/registry-breg/tests/runtime_config.rs b/crates/registry-breg/tests/runtime_config.rs index 61417bd3d9..02ef24f321 100644 --- a/crates/registry-breg/tests/runtime_config.rs +++ b/crates/registry-breg/tests/runtime_config.rs @@ -24,8 +24,9 @@ use registry_platform_config::package::{write_sum_file, PackageLimits}; use registry_platform_config::MetricsBindError; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::destination::{ - DestinationDnsFamily, DestinationSendError, EventDeliveryHeaders, + DestinationDnsFamily, DestinationSendError, SignedEventHeaders, }; +use registry_platform_oidc::StaticJwksError; use serde_json::{json, Value}; const DATABASE_URL_CANARY: &str = @@ -110,6 +111,12 @@ fn public_origin_accepts_only_explicit_web_origins_and_redacts_debug() { ("http://127.0.0.1:8080", "http://127.0.0.1:8080"), ("http://[::1]:8080/", "http://[::1]:8080"), ("http://localhost:8080", "http://localhost:8080"), + ("http://LOCALHOST:8080", "http://LOCALHOST:8080"), + ("http://127.0.0.2:8080", "http://127.0.0.2:8080"), + ( + "http://[::ffff:127.0.0.1]:8080", + "http://[::ffff:127.0.0.1]:8080", + ), ] { let origin = PublicOrigin::parse(input).expect("explicit HTTPS or loopback origin"); assert_eq!(origin.as_str(), expected); @@ -122,6 +129,9 @@ fn public_origin_accepts_only_explicit_web_origins_and_redacts_debug() { "ftp://registry.example", "http://registry.example", "http://127.0.0.1.attacker.example", + "http://localhost.:8080", + "http://app.localhost:8080", + "http://[::ffff:10.0.0.1]:8080", "https://user:secret@registry.example", "https://registry.example/a//b", "https://registry.example/a/../b", @@ -709,18 +719,11 @@ fn compiled_webhooks(destinations: &[(&str, u32, u8)]) -> registry_breg::Compile compile_project(&parsed, &[], CompileProfile::Authoring).expect("hooks compile") } -fn event_headers() -> EventDeliveryHeaders<'static> { - EventDeliveryHeaders { - id: b"event-id", - source: b"urn:registrystack:registry:example:instance:primary", - event_type: b"case.created", - time: b"2026-08-30T00:00:00Z", - dataschema: b"urn:registrystack:registry:example:event:case.created:schema:sha256:aaa", - generation: b"1", - attempt: b"1", - delivery_time: b"2026-08-30T00:00:01Z", - idempotency_key: b"delivery-key", - signature: b"v1=signature", +fn event_headers() -> SignedEventHeaders<'static> { + SignedEventHeaders { + id: b"event", + timestamp: b"1000", + signature: b"v1,caller-owned-signature", } } @@ -2065,7 +2068,7 @@ fn review_authority_completion_recipient_accepts_the_shared_byte_bound() { let base = valid_runtime(&fixture.secret_root, &fixture.package_root); let recipient = "x".repeat(256); let valid = format!( - "{base}reviewAuthorities:\n casework-a:\n endpoint: https://casework.example/reviews/\n profile: producer\n producerId: registry-producer\n recoveryDays: 7\n tokenRef: secret:file/opaque-review-token\n completionTokenRef: secret:file/review-completion-token\n completionRecipient: {recipient}\n" + "{base}reviewAuthorities:\n casework-a:\n endpoint: https://casework.example/reviews/\n profile: producer\n producerId: registry-producer\n recoveryDays: 7\n tokenRef: secret:file/opaque-review-token\n completion:\n hmacSha256KeyRef: secret:file/review-completion-key\n recipientBinding: {recipient}\n" ); parse_runtime_config_with_env(&valid, env_lookup) .expect("a completion recipient at the shared byte bound is accepted"); @@ -3325,12 +3328,6 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { }; let cases = [ ("top-level-missing", "{}".to_owned(), "EdDSA"), - ( - "top-level-unknown", - serde_json::to_string(&json!({"keys":[valid.clone()],"issuer":"issuer-canary"})) - .expect("JWKS serializes"), - "EdDSA", - ), ("empty-keys", r#"{"keys":[]}"#.to_owned(), "EdDSA"), ( "keys-not-array", @@ -3342,11 +3339,6 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { static_jwks_document(&[with_member(valid.clone(), "d", json!("private-canary"))]), "EdDSA", ), - ( - "unknown-member", - static_jwks_document(&[with_member(valid.clone(), "x5c", json!(["cert-canary"]))]), - "EdDSA", - ), ( "duplicate-json-field", format!( @@ -3462,7 +3454,32 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { .oidc_key_source() .await .expect_err("invalid static JWKS refused"); - assert_eq!(error, RuntimeConfigError::InvalidOidc, "{name}"); + let expected = match name { + "top-level-missing" | "keys-not-array" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::NotAKeySet) + } + "empty-keys" => RuntimeConfigError::InvalidStaticJwks(StaticJwksError::Empty), + "private-member" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }) + } + "duplicate-json-field" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::NotJson) + } + "oct-key" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::SymmetricKey { key: 0 }) + } + "missing-kid" | "empty-kid" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::MissingKeyId { key: 0 }) + } + "duplicate-kid" => { + RuntimeConfigError::InvalidStaticJwks(StaticJwksError::RepeatedKeyId { key: 1 }) + } + _ => RuntimeConfigError::InvalidOidc, + }; + assert_eq!(error, expected, "{name}"); let rendered = format!("{error:?} {error} {config:?}"); for canary in [ "oidc-jwks", @@ -3482,6 +3499,86 @@ async fn static_jwks_validation_refuses_unsafe_documents_value_free() { } } +#[tokio::test] +async fn a_static_key_set_with_unknown_public_members_loads() { + let fixture = RuntimeFixture::new(); + let kid = "static-ed25519"; + let key = static_ed25519_jwk(kid); + let documents = [ + ( + "x5c", + static_jwks_document(&[with_member(key.clone(), "x5c", json!(["cert-canary"]))]), + ), + ( + "ext", + static_jwks_document(&[with_member(key.clone(), "ext", json!(true))]), + ), + ( + "top-level", + serde_json::to_string(&json!({"keys":[key.clone()],"issuer":"issuer-canary"})) + .expect("JWKS serializes"), + ), + ]; + for (name, document) in documents { + fixture.write_secret("oidc-jwks", document.as_bytes()); + let config = parse_runtime_config_with_env( + &runtime_with_static_jwks_ref(&fixture, "secret:file/oidc-jwks"), + env_lookup, + ) + .expect("runtime shell parses"); + let source = config + .oidc_key_source() + .await + .unwrap_or_else(|error| panic!("{name} key set refused: {error}")); + source + .key_for_kid(kid) + .await + .unwrap_or_else(|_| panic!("{name} key set key is selectable by kid")); + } +} + +#[tokio::test] +async fn a_private_member_in_a_static_key_set_is_named_in_the_startup_refusal() { + let fixture = RuntimeFixture::new(); + let document = static_jwks_document(&[with_member( + static_ed25519_jwk("static-ed25519"), + "d", + json!("private-canary"), + )]); + fixture.write_secret("oidc-jwks", document.as_bytes()); + let config = parse_runtime_config_with_env( + &runtime_with_static_jwks_ref(&fixture, "secret:file/oidc-jwks"), + env_lookup, + ) + .expect("runtime shell parses"); + let error = config + .oidc_key_source() + .await + .expect_err("private member refused"); + let rendered = error.render_human(None); + assert!(rendered.contains("breg.runtime.invalid-oidc"), "{rendered}"); + assert!(rendered.contains("/authentication/oidc"), "{rendered}"); + assert!(rendered.contains("private-key member \"d\""), "{rendered}"); + assert!(!rendered.contains("private-canary"), "{rendered}"); + assert_eq!( + rendered.matches("private-key member").count(), + 1, + "the cause appears once: {rendered}" + ); + + // The startup surfaces keep the key-source class and carry the rule. + let startup = registry_breg::startup::map_runtime_config_error(error); + let registry_breg::startup::StartupError::StaticKeySet(cause) = &startup else { + panic!("a refused static key set is a key-source startup refusal: {startup:?}"); + }; + assert!(cause.to_string().contains("private-key member \"d\"")); + let record = registry_breg::startup::OperationalEvent::StoppedWithError(startup).record(); + assert_eq!( + record.error(), + Some("the Registry OIDC key source was refused") + ); +} + #[tokio::test] async fn static_jwks_resolves_once_and_rotates_only_on_reconstruction() { let fixture = RuntimeFixture::new(); @@ -4379,7 +4476,7 @@ async fn pinned_loopback_https_event_profile_activates_with_exact_test_tls_and_c let request = destination .request_template() - .render_event(event_headers(), br#"{"label":"value"}"#.to_vec()) + .render_signed_event(event_headers(), br#"{"label":"value"}"#.to_vec()) .expect("closed event request renders"); assert_eq!( destination @@ -4444,10 +4541,41 @@ fn activation_constructs_the_exact_platform_policy_template_and_signing_material assert!(destination.binding_digest().starts_with("sha256:")); assert_eq!(destination.binding_digest().len(), 71); let destination_binding_digest = destination.binding_digest().to_owned(); - destination.with_hmac_sha256_key(|key| assert_eq!(key, KEY_CANARY)); + use registry_platform_crypto::delivery_signature::{ + verify_authenticity, DeliveryKey, DeliveryKeys, SignedContent, + }; + use registry_platform_hooks::delivery::{ + DeliverySignatureFields, HookDestination, SharedUrlDestination, + }; + let shared = SharedUrlDestination( + activated + .lookup_shared(DESTINATION_CANARY) + .expect("active destination"), + ); + let body = br#"{"label":"value"}"#; + let signature = shared + .sign_delivery(DeliverySignatureFields { + id: "event", + timestamp: 1000, + body, + }) + .unwrap(); + let keys = DeliveryKeys::new(DeliveryKey::new(KEY_CANARY).unwrap(), None).unwrap(); + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + id: "event", + timestamp: "1000", + signature: &signature, + body + } + ), + Ok(1000) + ); let request = destination .request_template() - .render_event(event_headers(), br#"{"label":"value"}"#.to_vec()) + .render_signed_event(event_headers(), br#"{"label":"value"}"#.to_vec()) .expect("closed event request renders"); let diagnostic = format!("{config:?} {activated:?} {destination:?} {request:?}"); @@ -4779,6 +4907,357 @@ fn event_destination_digest_is_deterministic_across_yaml_map_order() { ); } +#[test] +fn a_destination_key_of_31_bytes_names_its_path_and_length() { + assert_destination_key_error(&[b'a'; 31], "31 bytes"); +} + +#[test] +fn a_65_byte_destination_key_ending_in_a_newline_names_the_newline() { + let mut key = [b'a'; 65]; + key[64] = b'\n'; + assert_destination_key_error(&key, "65 bytes (trailing newline: true)"); +} + +fn assert_destination_key_error(key: &[u8], expected: &str) { + let fixture = RuntimeFixture::new(); + fixture.write_secret("event-hmac-key", key); + let binding = event_destination_binding( + "case-operations", + "https://events.example/", + "/hooks/registry", + "secret:file/event-hmac-key", + 4_000, + 4, + ); + let runtime = parse_runtime_config_with_env( + &runtime_with_event_destinations(&fixture, &binding), + env_lookup, + ) + .expect("valid destination configuration"); + let error = runtime + .activate_event_destinations(&compiled_webhooks(&[("case-operations", 5_000, 5)])) + .expect_err("invalid key length") + .to_string(); + assert!( + error.contains("destinations.hooks.case-operations.hmacSha256KeyRef"), + "{error}" + ); + assert!(error.contains(expected), "{error}"); +} + +fn destination_key_config(id: &str) -> String { + event_destination_binding( + id, + "https://events.example/", + "/hooks/registry", + "secret:file/event-hmac-key", + 4_000, + 4, + ) +} + +fn previous_destination_key(binding: &str, reference: &str) -> String { + binding.replace( + " deliveryCeilings:", + &format!(" previousHmacSha256KeyRef: {reference}\n deliveryCeilings:"), + ) +} + +#[test] +fn two_destinations_sharing_key_bytes_are_refused_naming_both_paths() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("event-hmac-key", &[1; 32]); + fixture.write_secret("second-key", &[1; 32]); + let config = format!( + "{}{}", + destination_key_config("alpha"), + destination_key_config("bravo") + .replace("secret:file/event-hmac-key", "secret:file/second-key") + ); + let runtime = parse_runtime_config_with_env( + &runtime_with_event_destinations(&fixture, &config), + env_lookup, + ) + .unwrap(); + let error = runtime + .activate_event_destinations(&compiled_webhooks(&[ + ("alpha", 5000, 5), + ("bravo", 5000, 5), + ])) + .unwrap_err(); + assert_eq!(error.to_string(), "destinations.hooks.alpha.hmacSha256KeyRef and destinations.hooks.bravo.hmacSha256KeyRef resolve to the same key bytes. Give destinations.hooks.bravo.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."); +} + +#[test] +fn a_previous_destination_key_equal_to_the_current_key_is_refused() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("event-hmac-key", &[1; 32]); + fixture.write_secret("previous", &[1; 32]); + let config = previous_destination_key(&destination_key_config("alpha"), "secret:file/previous"); + let runtime = parse_runtime_config_with_env( + &runtime_with_event_destinations(&fixture, &config), + env_lookup, + ) + .unwrap(); + let error = runtime + .activate_event_destinations(&compiled_webhooks(&[("alpha", 5000, 5)])) + .unwrap_err(); + assert_eq!(error.to_string(), "destinations.hooks.alpha.previousHmacSha256KeyRef holds the same bytes as destinations.hooks.alpha.hmacSha256KeyRef. To rotate, write 32 new random bytes to the secret destinations.hooks.alpha.hmacSha256KeyRef references and keep the old bytes behind destinations.hooks.alpha.previousHmacSha256KeyRef."); +} + +#[test] +fn an_explicit_null_previous_destination_key_is_refused() { + let fixture = RuntimeFixture::new(); + let config = previous_destination_key(&destination_key_config("alpha"), "null"); + assert!(parse_runtime_config_with_env( + &runtime_with_event_destinations(&fixture, &config), + env_lookup, + ) + .is_err()); +} + +#[test] +fn a_previous_destination_key_leaves_the_binding_digest_unchanged() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("event-hmac-key", &[1; 32]); + fixture.write_secret("previous", &[2; 32]); + let compiled = compiled_webhooks(&[("alpha", 5000, 5)]); + let binding = destination_key_config("alpha"); + let activate = |config: &str| { + parse_runtime_config_with_env( + &runtime_with_event_destinations(&fixture, config), + env_lookup, + ) + .unwrap() + .activate_event_destinations(&compiled) + .unwrap() + }; + let first = activate(&binding); + let second = activate(&previous_destination_key(&binding, "secret:file/previous")); + assert_eq!(first.binding_digest(), second.binding_digest()); + assert_eq!( + first.lookup("alpha").unwrap().binding_digest(), + second.lookup("alpha").unwrap().binding_digest() + ); +} + +fn completion_binding(id: &str, recipient: &str) -> String { + format!("{} completion:\n recipientBinding: {recipient}\n hmacSha256KeyRef: secret:file/review-key\n", review_authority_binding(id)) +} + +#[test] +fn a_completion_token_names_its_replacement() { + let fixture = RuntimeFixture::new(); + let raw = format!( + "{}reviewAuthorities:\n{} completionTokenRef: secret:file/old-token\n", + valid_runtime(&fixture.secret_root, &fixture.package_root), + review_authority_binding("casework") + ); + let error = parse_runtime_config_with_env(&raw, env_lookup) + .unwrap_err() + .render_human(None); + assert!( + error.contains("Replace completionTokenRef with completion.hmacSha256KeyRef."), + "{error}" + ); +} + +#[test] +fn a_completion_recipient_names_its_replacement() { + let fixture = RuntimeFixture::new(); + let raw = format!( + "{}reviewAuthorities:\n{} completionRecipient: registry\n", + valid_runtime(&fixture.secret_root, &fixture.package_root), + review_authority_binding("casework") + ); + let error = parse_runtime_config_with_env(&raw, env_lookup) + .unwrap_err() + .render_human(None); + assert!( + error.contains("Move completionRecipient to completion.recipientBinding."), + "{error}" + ); +} + +#[test] +fn a_completion_block_without_a_key_is_refused() { + let fixture = RuntimeFixture::new(); + let raw = format!( + "{}reviewAuthorities:\n{} completion:\n recipientBinding: registry\n", + valid_runtime(&fixture.secret_root, &fixture.package_root), + review_authority_binding("casework") + ); + let error = parse_runtime_config_with_env(&raw, env_lookup) + .unwrap_err() + .render_human(None); + assert!(error.contains("hmacSha256KeyRef"), "{error}"); +} + +#[test] +fn a_completion_key_equal_to_a_destination_key_is_refused_naming_both_paths() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("event-hmac-key", &[1; 32]); + fixture.write_secret("review-key", &[1; 32]); + fixture.write_secret("review-token", b"outgoing-review-token"); + let raw = format!( + "{}reviewAuthorities:\n{}", + runtime_with_event_destinations(&fixture, &destination_key_config("alpha")), + completion_binding("casework", "registry") + ); + let compiled = compiled_webhooks(&[("alpha", 5000, 5)]); + let runtime = parse_runtime_config_with_env(&raw, env_lookup).unwrap(); + let error = runtime.activate_event_destinations(&compiled).unwrap_err(); + assert_eq!(error.to_string(), "destinations.hooks.alpha.hmacSha256KeyRef and reviewAuthorities.casework.completion.hmacSha256KeyRef resolve to the same key bytes. Give reviewAuthorities.casework.completion.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."); +} + +#[tokio::test] +async fn a_runtime_file_activates_a_previous_completion_key() { + use registry_breg::postgres::{ConnectionConfig, PoolBounds}; + use registry_breg::review_store::ReviewCompletionReceiver; + use registry_platform_crypto::delivery_signature::{ + self, DeliveryKey, DeliveryKeys, SignedContent, + }; + use std::os::unix::fs::PermissionsExt as _; + + let fixture = RuntimeFixture::new(); + let previous = [ + uuid::Uuid::new_v4().as_bytes().as_slice(), + uuid::Uuid::new_v4().as_bytes(), + ] + .concat(); + fixture.write_secret("review-key", &[1; 32]); + fixture.write_secret("previous", &previous); + fixture.write_secret("review-token", b"outgoing-review-token"); + let path = fixture.path("runtime.yaml"); + fs::write( + &path, + format!( + "{}reviewAuthorities:\n{} previousHmacSha256KeyRef: secret:file/previous\n", + valid_runtime(&fixture.secret_root, &fixture.package_root), + completion_binding("casework", "registry"), + ), + ) + .unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + let config = load_runtime_config_with_env(&path, env_lookup).unwrap(); + let authorities = config + .activate_review_authorities(&compiled_webhooks(&[])) + .unwrap() + .unwrap(); + let timeout = Duration::from_millis(50); + let ca = rcgen::generate_simple_self_signed(vec!["db.example.invalid".to_owned()]).unwrap(); + let pool = ConnectionConfig::require_tls_with_custom_ca( + "postgresql://registry_runtime@db.example.invalid/registry", + ca.cert.der(), + PoolBounds::new(1, timeout, timeout, timeout).unwrap(), + ) + .unwrap() + .build_pool() + .unwrap(); + let receiver = ReviewCompletionReceiver::new(pool, authorities); + let now = UNIX_EPOCH + Duration::from_secs(1_800_000_000); + let id = uuid::Uuid::new_v4().to_string(); + let body = b"{}"; + let keys = DeliveryKeys::new(DeliveryKey::new(&previous).unwrap(), None).unwrap(); + let signature = delivery_signature::sign(&keys, &id, 1_800_000_000, body).unwrap(); + assert_eq!( + receiver + .verify_completion( + "registry", + SignedContent { + id: &id, + timestamp: "1800000000", + signature: &signature, + body, + }, + now + ) + .unwrap(), + ("casework", 7), + ); +} + +#[test] +fn completion_key_refusals_render_each_sentence_once() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("review-token", b"outgoing-review-token"); + fixture.write_secret("review-key", &[1; 32]); + fixture.write_secret("short", &[2; 31]); + fixture.write_secret("previous", &[1; 32]); + let current = "reviewAuthorities.casework.completion.hmacSha256KeyRef"; + let previous = "reviewAuthorities.casework.completion.previousHmacSha256KeyRef"; + for (binding, field, reason, action) in [ + ( + completion_binding("casework", "registry").replace("file/review-key", "file/short"), + "hmacSha256KeyRef", + format!("{current} has 31 bytes (trailing newline: false)."), + "Supply 32 to 64 exact key bytes.".to_owned(), + ), + ( + completion_binding("casework", "registry").replace("file/review-key", "file/missing"), + "hmacSha256KeyRef", + format!("{current} could not be resolved: the referenced secret is unavailable."), + "Create the secret under the configured provider, or correct the name.".to_owned(), + ), + ( + format!("{} previousHmacSha256KeyRef: secret:file/previous\n", completion_binding("casework", "registry")), + "previousHmacSha256KeyRef", + format!("{previous} holds the same bytes as {current}."), + format!("To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}."), + ), + ] { + let raw = format!("{}reviewAuthorities:\n{binding}", valid_runtime(&fixture.secret_root, &fixture.package_root)); + let config = parse_runtime_config_with_env(&raw, env_lookup).unwrap(); + let error = config.activate_review_authorities(&compiled_webhooks(&[])).err().expect("key is refused"); + assert_eq!(error.to_string(), format!("{reason} {action}")); + assert_eq!( + error.render_human(None), + format!("error[breg.runtime.invalid-delivery-key] /reviewAuthorities/casework/completion/{field}\n {reason}\n next: {action}\n1 error, 0 warnings in 1 file\n"), + ); + } +} + +#[test] +fn completion_authorities_with_distinct_references_to_equal_keys_are_refused() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("review-key", &[1; 32]); + fixture.write_secret("second-key", &[1; 32]); + let raw = format!( + "{}reviewAuthorities:\n{}{}", + valid_runtime(&fixture.secret_root, &fixture.package_root), + completion_binding("casework-a", "registry-a"), + completion_binding("casework-b", "registry-b") + .replace("secret:file/review-key", "secret:file/second-key"), + ); + let runtime = parse_runtime_config_with_env(&raw, env_lookup).unwrap(); + let error = runtime + .activate_event_destinations(&compiled_webhooks(&[])) + .unwrap_err(); + assert_eq!(error.to_string(), "reviewAuthorities.casework-a.completion.hmacSha256KeyRef and reviewAuthorities.casework-b.completion.hmacSha256KeyRef resolve to the same key bytes. Give reviewAuthorities.casework-b.completion.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."); +} + +#[test] +fn two_authorities_sharing_a_recipient_binding_are_refused() { + let fixture = RuntimeFixture::new(); + fixture.write_secret("review-token", b"outgoing-review-token"); + fixture.write_secret("review-key", &[1; 32]); + let raw = format!( + "{}reviewAuthorities:\n{}{}", + valid_runtime(&fixture.secret_root, &fixture.package_root), + completion_binding("casework-a", "registry"), + completion_binding("casework-b", "registry") + ); + let compiled = compiled_webhooks(&[]); + let runtime = parse_runtime_config_with_env(&raw, env_lookup).unwrap(); + let error = runtime + .activate_review_authorities(&compiled) + .err() + .expect("duplicate recipient refused") + .to_string(); + assert!(error.contains("reviewAuthorities.casework-a.completion.recipientBinding and reviewAuthorities.casework-b.completion.recipientBinding"), "{error}"); +} + #[test] fn event_destination_missing_oversized_and_unsafe_secrets_fail_value_free() { const SECRET_CANARY: &str = "event-secret-reference-canary"; @@ -4815,7 +5294,14 @@ fn event_destination_missing_oversized_and_unsafe_secrets_fail_value_free() { let error = config .activate_event_destinations(&compiled) .expect_err("missing secret refused"); - assert_eq!(error, EventDestinationActivationError::Secret); + if tls.is_empty() { + assert!(matches!( + error, + EventDestinationActivationError::SigningKeyUnavailable { .. } + )); + } else { + assert_eq!(error, EventDestinationActivationError::Secret); + } assert!(!format!("{error:?} {error}").contains(SECRET_CANARY)); } @@ -4836,12 +5322,12 @@ fn event_destination_missing_oversized_and_unsafe_secrets_fail_value_free() { env_lookup, ) .expect("oversized secret ref parses"); - assert_eq!( + assert!(matches!( oversized .activate_event_destinations(&compiled) .expect_err("oversized secret refused by the shared loader"), - EventDestinationActivationError::Secret - ); + EventDestinationActivationError::SigningKeyUnavailable { .. } + )); #[cfg(unix)] { @@ -4868,12 +5354,12 @@ fn event_destination_missing_oversized_and_unsafe_secrets_fail_value_free() { env_lookup, ) .expect("unsafe secret ref parses"); - assert_eq!( + assert!(matches!( unsafe_file .activate_event_destinations(&compiled) .expect_err("unsafe secret file refused by the shared loader"), - EventDestinationActivationError::Secret - ); + EventDestinationActivationError::SigningKeyUnavailable { .. } + )); } } @@ -4916,7 +5402,7 @@ async fn production_event_policy_refuses_literal_metadata_and_unallowed_private_ .expect("compiled destination is active"); let request = destination .request_template() - .render_event(event_headers(), br#"{"label":"value"}"#.to_vec()) + .render_signed_event(event_headers(), br#"{"label":"value"}"#.to_vec()) .expect("event request renders"); let error = destination .policy() diff --git a/crates/registry-breg/tests/startup_http.rs b/crates/registry-breg/tests/startup_http.rs index ca3ed08f9e..9a3f94be44 100644 --- a/crates/registry-breg/tests/startup_http.rs +++ b/crates/registry-breg/tests/startup_http.rs @@ -35,7 +35,9 @@ use registry_breg::startup::{ }; use registry_breg::{compile_project, parse_project_yaml, CompileProfile, CompiledRegistry}; use registry_platform_crypto::PrivateJwk; -use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifierConfig}; +use registry_platform_oidc::{ + JwksFetcher, JwksFetcherConfig, StaticJwksError, TokenVerifierConfig, +}; use registry_platform_testing::{fixtures, jwks_from_private_jwk, sign_ed25519_compact_jwt}; use serde_json::{json, Value}; use tower::ServiceExt as _; @@ -507,7 +509,9 @@ async fn request_operational_log_has_only_closed_value_free_fields() { /// A description the audit writer gives for a torn audit file. const AUDIT_DESTINATION_REASON: &str = "the audit file could not be opened: audit file has an incomplete final entry; archive it and restart with a fresh path"; -fn startup_errors() -> [StartupError; 40] { +const EVENT_DESTINATION_REASON: &str = "the configured delivery key file is unavailable"; + +fn startup_errors() -> [StartupError; 41] { [ // The wrapped cause never changes the rendered operational message: it // only lets `bregctl doctor` name it. Any `RuntimeConfigError` variant @@ -553,9 +557,13 @@ fn startup_errors() -> [StartupError; 40] { StartupError::ExternalSources, StartupError::ExternalProjectionRoleMode, StartupError::Oidc, + StartupError::StaticKeySet(StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }), StartupError::Authentication, StartupError::AuthenticationClientsUnlisted, - StartupError::EventDestinations, + StartupError::EventDestinations(EVENT_DESTINATION_REASON.to_owned()), StartupError::RetainedHookBindings { retained_deliveries: 2, }, @@ -833,12 +841,14 @@ fn expected_startup_error(error: StartupError) -> &'static str { StartupError::ExternalProjectionRoleMode => { "indexed external projections require separate migration and runtime PostgreSQL roles" } - StartupError::Oidc => "the Registry OIDC key source was refused", + StartupError::Oidc | StartupError::StaticKeySet(_) => { + "the Registry OIDC key source was refused" + } StartupError::Authentication => "the Registry authentication profile was refused", StartupError::AuthenticationClientsUnlisted => { "the project names clients that authentication.oidc.allowedClients does not list; list each client named in requesterClients, trusted actors, or consent recipients there" } - StartupError::EventDestinations => "the Registry event destination bindings were refused", + StartupError::EventDestinations(_) => "the Registry event destination bindings were refused", StartupError::RetainedHookBindings { .. } => { "retained hook deliveries require superseded bindings; run `bregctl doctor` to name the recovery" } @@ -1051,8 +1061,16 @@ async fn every_operational_event_renders_exact_closed_value_free_json_fields() { _ => None, }; let reason = match &event { - OperationalEvent::StoppedWithError(StartupError::AuditDestination(reason)) => { - Some(reason.clone()) + OperationalEvent::StoppedWithError( + StartupError::AuditDestination(reason) | StartupError::EventDestinations(reason), + ) => Some(reason.clone()), + OperationalEvent::StoppedWithError(StartupError::StaticKeySet(cause)) => { + let reason = cause.to_string(); + assert!( + reason.contains("private-key member \"d\""), + "the reason names the rule: {reason}" + ); + Some(reason) } _ => None, }; diff --git a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs index 9bd0c2fa0e..d26583d06b 100644 --- a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs +++ b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs @@ -188,7 +188,7 @@ impl PilotHarness { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::ZERO, }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let prepared = prepare_with_connection_and_key_source_for_test( &config_path, diff --git a/crates/registry-breg/tests/token_characterisation.rs b/crates/registry-breg/tests/token_characterisation.rs new file mode 100644 index 0000000000..b7e32fe313 --- /dev/null +++ b/crates/registry-breg/tests/token_characterisation.rs @@ -0,0 +1,443 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the token fixture corpus through BReg's real authentication path and +//! asserts each result against the `breg` column of `expected.yaml`. +//! +//! The access-token verifier profile and the authority claim mapping come from +//! a runtime file parsed by `parse_runtime_config`, as at startup. The key set +//! is the signer's static public key set. A token that authenticates is sent +//! through the authenticated router to a compiled access profile, so a profile +//! refusal is observed where a request meets it. A token the verifier refuses +//! is sent through the router too, and the check it failed is read from +//! `breg_request_refusals_total`, the counter an operator reads. + +#![cfg(feature = "runtime")] + +use std::collections::BTreeSet; +use std::sync::Arc; + +use axum::body::Body; +use axum::http::header::AUTHORIZATION; +use axum::http::{Request, StatusCode}; +use registry_breg::api::{ + authenticated_router, HeldReadResponse, HttpService, ReadRuntimeIdentity, ReadServiceError, + ReadinessProbe, RecordReadRequest, RecordReadService, ServiceFuture, +}; +use registry_breg::auth::{AuthenticationConfigError, AuthenticationError, RegistryAuthenticator}; +use registry_breg::cursor::CursorCodec; +use registry_breg::metrics::{metrics_app, Metrics}; +use registry_breg::runtime_config::parse_runtime_config; +use registry_breg::{compile_project, parse_project_yaml, CompileProfile}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenFixture, + TokenSigner, +}; +use serde_json::{json, Value}; +use tower::ServiceExt as _; +use zeroize::Zeroizing; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:breg:test"; +const RECORD_ID: &str = "00000000-0000-4000-8000-000000000001"; +/// The client a default configuration lists when the fixture names none, so a +/// token without a client claim meets a list that does not include it. +const LISTED_CLIENT: &str = "journey-app"; +/// The scope a profile requires when the fixture carries none. +const FALLBACK_SCOPE: &str = "records:get"; + +#[tokio::test] +async fn breg_token_characterisation() { + let corpus = TokenCorpus::load().expect("the corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("breg", &signer, ISSUER, AUDIENCE, observe) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran, so the test proves nothing" + ); + report.assert_matches(); +} + +/// What a configuration changes in the runtime file's `authentication.oidc` +/// block, derived from the fixture the way `expected.yaml` describes. +struct Shape { + algorithm: &'static str, + access_token_type: String, + scope_claim: &'static str, + /// Empty writes `allowedClients: unrestricted`. + clients: Vec, + /// The scope the compiled access profile requires. + scope: String, + /// The client a people-only profile serves. + profile_client: String, +} + +impl Shape { + fn of(case: &FixtureCase) -> Self { + let fixture = &case.fixture; + let header = fixture.header.as_ref(); + let algorithm = match header.map(|header| header.alg.as_str()) { + Some("ES256") => "ES256", + Some("EdDSA") => "EdDSA", + _ => "RS256", + }; + let recipe = case.configuration == Configuration::Recipe; + let access_token_type = match case.configuration { + Configuration::Recipe => header + .and_then(|header| header.typ.clone()) + .unwrap_or_else(|| "at+jwt".to_owned()), + Configuration::JwtAccepted => "JWT".to_owned(), + Configuration::Default => "at+jwt".to_owned(), + }; + let scope_claim = if recipe && fixture.claims.contains_key("scp") { + "scp" + } else { + "scope" + }; + let client = literal_text(fixture, "client_id").or_else(|| literal_text(fixture, "azp")); + let clients = match (&client, recipe) { + (Some(client), _) => vec![client.clone()], + (None, true) => Vec::new(), + (None, false) => vec![LISTED_CLIENT.to_owned()], + }; + let scope = fixture + .read_scope(scope_claim) + .unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); + Self { + algorithm, + access_token_type, + scope_claim, + clients, + scope, + profile_client: client.unwrap_or_else(|| LISTED_CLIENT.to_owned()), + } + } + + fn runtime_yaml(&self, case: &FixtureCase) -> String { + let clients = if self.clients.is_empty() { + "unrestricted".to_owned() + } else { + json!(self.clients).to_string() + }; + format!( + r#" +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:8080 +identity: + environment: production + instanceId: registry-primary + databaseId: registry-db + databaseInitializationEnvironment: production +secretProviders: + environment: {{}} + file: + root: /var/lib/breg/secrets +database: + runtimeUrlRef: secret:env/BREG_DATABASE_URL + migrationUrlRef: secret:env/BREG_MIGRATION_DATABASE_URL + pool: + maximumConnections: 4 + waitTimeoutMilliseconds: 1000 + createTimeoutMilliseconds: 1000 + recycleTimeoutMilliseconds: 1000 + roles: + migration: registry_migration + runtime: registry_runtime +package: + root: /var/lib/breg/package +authentication: + oidc: + issuer: {issuer} + audience: {audience} + allowedAlgorithm: {algorithm} + accessTokenType: "{access_token_type}" + scopeClaim: {scope_claim} + scopeSeparator: " " + allowedClients: {clients} + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 60000 + authorityClaims: + principal: sub +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/breg/audit/audit.jsonl +cursor: + secretRef: secret:file/cursor-key + maximumAgeSeconds: 300 +destinations: + hooks: {{}} +operationalTimeouts: + httpRequestMilliseconds: 10000 + shutdownGraceMilliseconds: 30000 + recordLockMilliseconds: 5000 + migrationLockMilliseconds: 30000 + migrationStatementMilliseconds: 60000 +"#, + issuer = case.issuer, + audience = case.audience, + algorithm = self.algorithm, + access_token_type = self.access_token_type, + scope_claim = self.scope_claim, + ) + } + + /// A project with the one access profile the row is read against: a + /// default profile for any actor, or a profile for people only. Each + /// requires the fixture's first scope. A people-only profile names the + /// requester clients it serves, as the compiler demands. + fn project_yaml(&self, against: Against) -> String { + let profile = match against { + Against::PlainRead => format!( + " reader:\n default: true\n principalClaim: sub\n requiredScopes: [{}]\n", + self.scope + ), + Against::HumanOnlyProfile => format!( + " people:\n default: true\n principalClaim: sub\n actorKind: human\n requesterClients: [{}]\n requiredScopes: [{}]\n", + self.profile_client, self.scope + ), + }; + format!( + r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {{id: token-characterisation, version: 0.1.0, defaultLanguage: en, canonicalBaseIri: https://authoring.example.test}} +recordTypes: + case: + primaryDataset: test-dataset + route: cases + mutationMode: mutable + tombstone: false + classification: public + fields: + - {{id: label, type: string, required: true, maximumLength: 100, classification: public}} +datasets: + test-dataset: {{}} +accessProfiles: +{profile} permissions: + records: + - {{recordType: case, operations: [get], readableFields: [label], rowBoundaries: unrestricted}} +"# + ) + } +} + +fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +async fn observe(case: FixtureCase) -> Outcome { + let shape = Shape::of(&case); + let config = parse_runtime_config(&shape.runtime_yaml(&case)) + .expect("the runtime file for this row parses"); + let registry = Arc::new( + compile_project( + &parse_project_yaml(shape.project_yaml(case.against).as_bytes()) + .expect("project parses"), + &[], + CompileProfile::Authoring, + ) + .expect("project compiles"), + ); + let keys = Arc::new(JwksFetcher::new_static( + serde_json::from_value(case.jwks.clone()).expect("the key set parses"), + JwksFetcherConfig::defaults(), + )); + let authenticator = match RegistryAuthenticator::new( + ®istry, + config.authentication().oidc().token_verifier_config(), + keys, + config.authentication().authority_claim_config(), + ) { + Ok(authenticator) => Arc::new(authenticator), + // A profile that names requester clients cannot be served by a file + // that leaves the clients unrestricted: BReg refuses to start. + Err(AuthenticationConfigError::NamedClientNotListed) => return Outcome::None, + Err(error) => panic!("the authentication block is invalid for the project: {error}"), + }; + + let token = case.token.expose(); + let claims = authenticator.authenticate(token).await; + let claims = match claims { + Ok(claims) => claims, + Err( + AuthenticationError::VerificationRefused | AuthenticationError::MalformedCredential, + ) => { + return refused_stage(®istry, &authenticator, token) + .await + .map_or(Outcome::Unknown, Outcome::Refused); + } + Err(AuthenticationError::MissingActorKind | AuthenticationError::InvalidClaims) => { + return Outcome::Refused(Stage::Claims); + } + }; + let kind = actor_kind_of(&format!("{claims:?}")); + + let profile = match case.against { + Against::PlainRead => "reader", + Against::HumanOnlyProfile => "people", + }; + let status = request_record(®istry, &authenticator, token, profile).await; + if status == StatusCode::OK { + Outcome::Admitted(Some(kind)) + } else { + Outcome::Refused(Stage::Profile) + } +} + +/// The stage a refused token failed at: the check the request boundary counted +/// when the token was sent through the router, mapped onto the corpus's +/// stages. `None` when the boundary counted nothing or something else. +async fn refused_stage( + registry: &Arc, + authenticator: &Arc, + token: &str, +) -> Option { + let before = refusal_counts().await; + request_record(registry, authenticator, token, "reader").await; + let after = refusal_counts().await; + let counted: Vec<&str> = after + .iter() + .filter(|(check, count)| **count > before.get(*check).copied().unwrap_or(0)) + .map(|(check, _)| check.as_str()) + .collect(); + match counted.as_slice() { + ["credential-malformed"] => Some(Stage::Header), + ["token-algorithm"] => Some(Stage::Algorithm), + ["token-type"] => Some(Stage::TokenType), + ["token-key"] => Some(Stage::Key), + ["token-signature"] => Some(Stage::Signature), + ["token-issuer"] => Some(Stage::Issuer), + ["token-audience"] => Some(Stage::Audience), + ["token-time"] => Some(Stage::Time), + ["token-client" | "token-assertion-issuer"] => Some(Stage::Client), + ["key-source-unavailable"] => Some(Stage::Unavailable), + _ => None, + } +} + +/// The refusal counter as the metrics listener serves it. +async fn refusal_counts() -> std::collections::BTreeMap { + let response = metrics_app(Arc::new(Metrics::without_pool_for_test())) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .expect("scrape request"), + ) + .await + .expect("the metrics listener responds"); + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("metrics body"); + String::from_utf8(bytes.to_vec()) + .expect("metrics are UTF-8") + .lines() + .filter_map(|line| line.strip_prefix("breg_request_refusals_total{check=\"")) + .map(|rest| { + let (check, count) = rest.split_once("\"} ").expect("sample line"); + (check.to_owned(), count.parse().expect("counter value")) + }) + .collect() +} + +/// The actor kind in a `VerifiedRequestClaims` debug rendering, which prints +/// the kind and redacts every value. +fn actor_kind_of(rendered: &str) -> String { + let after = rendered + .split("actor_kind: Some(") + .nth(1) + .expect("an authenticated request carries an actor kind"); + after + .split(')') + .next() + .expect("the actor kind is closed") + .to_ascii_lowercase() +} + +async fn request_record( + registry: &Arc, + authenticator: &Arc, + token: &str, + profile: &str, +) -> StatusCode { + let service = Arc::new(HttpService::new( + Arc::clone(registry), + ReadRuntimeIdentity { + package_revision: "package-token-test".to_owned(), + schema_fingerprint: "schema-token-test".to_owned(), + }, + Arc::new(OneRecord), + Arc::new(Ready), + Arc::new( + CursorCodec::new( + Zeroizing::new(vec![0x43; 32]), + std::time::Duration::from_secs(300), + ) + .expect("the cursor key is valid"), + ), + )); + let app = authenticated_router(service, Arc::clone(authenticator)); + let request = Request::builder() + .uri(format!( + "/v1/records/cases/{RECORD_ID}?accessProfile={profile}" + )) + .header(AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("request"); + app.oneshot(request) + .await + .expect("the router responds") + .status() +} + +struct OneRecord; + +impl RecordReadService for OneRecord { + fn get( + &self, + request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + let fields: BTreeSet = request.selected_fields; + Box::pin(async move { + let data: serde_json::Map = fields + .into_iter() + .map(|field| (field, json!("visible"))) + .collect(); + let record = json!({"id": RECORD_ID, "revision": 1, "data": data}); + Ok(Some( + HeldReadResponse::from_json(&record).expect("the record serializes"), + )) + }) + } + + fn list( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result> { + Box::pin(async { + Ok(HeldReadResponse::from_json(&json!({"items": []})).expect("the list serializes")) + }) + } + + fn lookup( + &self, + _request: RecordReadRequest, + ) -> ServiceFuture<'_, Result, ReadServiceError>> { + Box::pin(async { Ok(None) }) + } +} + +struct Ready; + +impl ReadinessProbe for Ready { + fn is_ready(&self) -> ServiceFuture<'_, bool> { + Box::pin(async { true }) + } +} diff --git a/crates/registry-bregctl/Cargo.toml b/crates/registry-bregctl/Cargo.toml index d71fceb5d3..f1b2c8bd3d 100644 --- a/crates/registry-bregctl/Cargo.toml +++ b/crates/registry-bregctl/Cargo.toml @@ -21,6 +21,11 @@ required-features = ["schema"] name = "wasm_test_lifecycle" required-features = ["wasm"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [lints] workspace = true @@ -29,6 +34,9 @@ default = ["wasm"] # Forwarded so a `wasm`-feature build of the compiler can also run through # bregctl; bregctl itself adds no WASM surface of its own. wasm = ["registry-breg/wasm"] +# Builds the PostgreSQL provisioning proof, which needs a TLS server named by +# `PROVISION_TEST_DATABASE_URL` and `PROVISION_TEST_DATABASE_CA`. +postgres-test = [] # Derives the JSON Schemas of the tool files bregctl reads, for the # `tool-schema` generator and its drift check. schema = [ @@ -58,6 +66,7 @@ registry-platform-config.workspace = true registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-platform-hooks.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-httputil.workspace = true registry-platform-httpsec = { workspace = true, default-features = false } registry-thunderid-tooling = { workspace = true, features = ["session"] } @@ -88,7 +97,8 @@ url.workspace = true [dev-dependencies] registry-breg.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server"] } rustls.workspace = true tokio-postgres.workspace = true tokio-postgres-rustls.workspace = true diff --git a/crates/registry-bregctl/README.md b/crates/registry-bregctl/README.md index 6b921471c0..16e2fbcf04 100644 --- a/crates/registry-bregctl/README.md +++ b/crates/registry-bregctl/README.md @@ -102,7 +102,7 @@ destination identifiers and governed delivery policy, never deployed URLs, secret references, or secret values. `bregctl hook sample PROJECT --event ID` compiles the authoring -project and renders a deterministic CloudEvents HTTP request with typed +project and renders a deterministic Standard Webhooks HTTP request with typed synthetic projection values. The request target and signature are explicit placeholders because this offline command does not load deployment configuration or secrets. diff --git a/crates/registry-bregctl/src/apply_lifecycle.rs b/crates/registry-bregctl/src/apply_lifecycle.rs index 88e7d4abef..eee75ec620 100644 --- a/crates/registry-bregctl/src/apply_lifecycle.rs +++ b/crates/registry-bregctl/src/apply_lifecycle.rs @@ -34,7 +34,7 @@ pub(crate) enum ApplyLifecycleError { found: String, }, Uninitialized, - EventDestinations, + EventDestinations(String), FieldEncryptionConfiguration, FieldEncryptionCustody, DatabaseConfiguration, @@ -234,10 +234,18 @@ fn execute( identity.instance_id(), identity.database_id(), ); - // A plan learns from the database whether the package would be the first, - // so it resolves database authority first; an apply is told by --initial - // and checks everything the package and the runtime file decide before - // any database authority is resolved. + // A plan can verify delivery bindings before opening database authority. + let planned_destinations = if mode == LifecycleMode::Plan { + Some( + config + .activate_event_destinations(target.registry()) + .map_err(|error| ApplyLifecycleError::EventDestinations(error.to_string()))?, + ) + } else { + None + }; + // The plan reads the activation ledger to learn whether this is the + // first package. Apply receives that decision through --initial. let mut access = None; let initial = match mode { LifecycleMode::Apply => request.initial, @@ -291,9 +299,21 @@ fn execute( .map(|_| config.secret_resolver()) .transpose() .map_err(|_| ApplyLifecycleError::FieldEncryptionConfiguration)?; - let activated_event_destinations = config - .activate_event_destinations(target.registry()) - .map_err(|_| ApplyLifecycleError::EventDestinations)?; + let (review_authorities, activated_event_destinations) = match planned_destinations { + Some(destinations) => (None, destinations), + None => { + let authorities = config + .activate_review_authorities(target.registry()) + .map_err(ApplyLifecycleError::RuntimeConfig)?; + let destinations = config + .activate_event_destinations_with_review_authorities( + target.registry(), + authorities.as_deref(), + ) + .map_err(|error| ApplyLifecycleError::EventDestinations(error.to_string()))?; + (authorities, destinations) + } + }; let event_destination_compatibility = activated_event_destinations.compatibility_inventory(); let DatabaseAccess { @@ -342,9 +362,14 @@ fn execute( // Planning never activates service bindings or performs Review HTTP. The // Apply proof uses only already accepted immutable Request/Result reads. let proposal_compatibility = match (mode, current_identity.as_ref()) { - (LifecycleMode::Apply, Some(current)) => runtime.block_on( - prepare_proposal_compatibility(&config, &connection, current, &target), - )?, + (LifecycleMode::Apply, Some(current)) => { + runtime.block_on(prepare_proposal_compatibility( + &connection, + current, + &target, + review_authorities.as_deref(), + ))? + } _ => None, }; let backup_evidence = backup_arguments @@ -441,15 +466,12 @@ fn execute( } async fn prepare_proposal_compatibility( - config: &RuntimeConfig, connection: &ConnectionConfig, current: &ExpectedRegistryIdentity, target: &VerifiedPackage, + authorities: Option<®istry_breg::review_store::ReviewAuthorityRegistry>, ) -> Result, ApplyLifecycleError> { - let Some(authorities) = config - .activate_review_authorities(target.registry()) - .map_err(ApplyLifecycleError::RuntimeConfig)? - else { + let Some(authorities) = authorities else { if target.registry().actions().actions.iter().any(|action| matches!( &action.execution, registry_breg::model::CompiledActionExecution::Proposal { proposal } @@ -466,7 +488,7 @@ async fn prepare_proposal_compatibility( &pool, current, target, - &authorities, + authorities, std::time::Duration::from_secs(30), ) .await diff --git a/crates/registry-bregctl/src/data_lifecycle.rs b/crates/registry-bregctl/src/data_lifecycle.rs index 67fdb9ea25..1f429c508c 100644 --- a/crates/registry-bregctl/src/data_lifecycle.rs +++ b/crates/registry-bregctl/src/data_lifecycle.rs @@ -32,7 +32,7 @@ use registry_platform_canonical_json::{canonicalize_json, parse_json_strict}; use registry_platform_httputil::client::{ build_client, OutboundOptions, ServiceBaseUrl, DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use registry_platform_yaml::{ ApiVersion, Diagnostic, Document, EnvelopeRule, Expect, FormatSpec, Reader, Report, RetiredApiVersion, @@ -1166,7 +1166,7 @@ async fn dispatch_http( .await .map_err(|_| ())?; let status = response.status().as_u16(); - validate_response_headers(response.headers()).map_err(|_| ())?; + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| ())?; let content_type = response .headers() .get(CONTENT_TYPE) diff --git a/crates/registry-bregctl/src/dev/config.rs b/crates/registry-bregctl/src/dev/config.rs index 38e0d7cad0..21d11cafcb 100644 --- a/crates/registry-bregctl/src/dev/config.rs +++ b/crates/registry-bregctl/src/dev/config.rs @@ -9,6 +9,9 @@ use registry_breg::literal_text::{ LiteralText, WRITE_THE_VALUE, WRITE_THE_VALUE_OR_A_SECRET_REFERENCE, }; use registry_platform_config::{SecretProvidersConfig, SecretReference}; +use registry_platform_crypto::delivery_signature::{ + distinct_delivery_keys, DeliveryKey, DeliveryKeyError, +}; use registry_platform_yaml::{ ApiVersion, Diagnostic, Document, EnvelopeRule, Expect, FormatSpec, Reader, RemovedKey, Report, Severity, @@ -20,7 +23,7 @@ use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, fs, - path::Path, + path::{Path, PathBuf}, }; use zeroize::Zeroizing; @@ -82,7 +85,15 @@ pub(crate) const DEV_CLIENTS_FORMAT: FormatSpec<'static> = FormatSpec { }, RemovedKey { pointer: "/reviewAuthorities/*/completionTokenFile", - replacement: "Use `completionTokenRef`: write a secret reference (secret:file/name or secret:env/NAME) and enable its provider under secretProviders.", + replacement: "Use `completion.hmacSha256KeyRef`: write a secret reference (secret:file/name or secret:env/NAME) and enable its provider under secretProviders.", + }, + RemovedKey { + pointer: "/reviewAuthorities/*/completionTokenRef", + replacement: "Replace completionTokenRef with completion.hmacSha256KeyRef. Casework signs review completions with Standard Webhooks.", + }, + RemovedKey { + pointer: "/reviewAuthorities/*/completionRecipient", + replacement: "Move completionRecipient to completion.recipientBinding.", }, RemovedKey { pointer: "/issuer/interactiveApplications/*/clientSecretFile", @@ -294,9 +305,41 @@ pub(super) struct LocalReviewAuthority { /// into the private runtime secret tree and is never written to this file. pub client: String, #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_token_ref: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_recipient: Option, + pub completion: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct LocalReviewCompletion { + pub recipient_binding: String, + pub hmac_sha256_key_ref: SecretReference, + #[serde( + default, + deserialize_with = "present_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, +} + +fn present_key_reference<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + SecretReference::deserialize(deserializer).map(Some) +} + +impl LocalReviewCompletion { + fn references(&self) -> impl Iterator { + std::iter::once(("hmacSha256KeyRef", "key", &self.hmac_sha256_key_ref)).chain( + self.previous_hmac_sha256_key_ref + .as_ref() + .map(|reference| ("previousHmacSha256KeyRef", "previous-key", reference)), + ) + } } #[derive(Clone, Debug, Deserialize, Serialize)] @@ -531,7 +574,6 @@ const ASSERTION_KEY_BYTES: usize = 16 * 1024; const CLIENT_SECRET_BYTES: usize = 1024; const PASSWORD_BYTES: usize = 1024; const HMAC_KEY_BYTES: usize = 1024; -const COMPLETION_TOKEN_BYTES: usize = 4096; const EVIDENCE_TOKEN_BYTES: usize = 16 * 1024; const EVIDENCE_DOCUMENT_BYTES: usize = 64 * 1024; @@ -735,9 +777,7 @@ fn resolve_secret( registry_platform_config::SecretError::Unavailable => { "create the file under secretProviders.file.root, or set the environment variable the reference names" } - registry_platform_config::SecretError::UnsafeFile => { - "make it a regular file you own, with mode 0400 or 0600 and a single link" - } + registry_platform_config::SecretError::UnsafeFile(check) => check.suggested_action(), registry_platform_config::SecretError::InvalidValue => { "store a non-empty value without NUL bytes, at most 64 KiB" } @@ -813,6 +853,59 @@ pub(crate) fn check(document: &Document) -> Result, Report> { }) } +fn delivery_secret( + clients: &Clients, + secrets: Secrets, + member: &str, + reference: &SecretReference, +) -> Result>>> { + if secrets == Secrets::Declared { + return secret(clients, secrets, member, reference, HMAC_KEY_BYTES); + } + let providers = clients.secret_providers.as_ref().with_context(|| { + format!("{member} names a secret, but the clients file declares no secretProviders") + })?; + let resolver = providers.resolver().map_err(|_| { + anyhow::anyhow!( + "secretProviders cannot resolve {member}; declare a configured secret provider" + ) + })?; + let value = resolver + .resolve_binary_reference(reference) + .map_err(|error| { + anyhow::anyhow!( + "{member} could not be resolved: {error}. {}", + error.suggested_action() + ) + })?; + Ok(Some(Zeroizing::new(value.expose_secret().to_vec()))) +} + +fn checked_delivery_key( + clients: &Clients, + secrets: Secrets, + path: &str, + reference: &SecretReference, +) -> Result> { + delivery_secret(clients, secrets, path, reference)? + .map(|bytes| { + DeliveryKey::new(&bytes).map_err(|error| { + let action = match error { + DeliveryKeyError::SecretText => { + "Supply the exact key bytes without the whsec_ encoding." + } + _ => "Supply 32 to 64 exact key bytes.", + }; + anyhow::anyhow!( + "{path} has {} bytes (trailing newline: {}). {action}", + bytes.len(), + bytes.ends_with(b"\n"), + ) + }) + }) + .transpose() +} + fn validate(clients: Clients, secrets: Secrets) -> Result { if let Some(providers) = &clients.secret_providers { providers.check().map_err(|error| { @@ -967,6 +1060,8 @@ fn validate(clients: Clients, secrets: Secrets) -> Result { ); } } + let mut delivery_keys = Vec::new(); + let mut completion_recipients = BTreeMap::new(); for (id, authority) in &clients.review_authorities { let endpoint = reqwest::Url::parse(&authority.endpoint) .context("local review authority endpoint must be an exact loopback HTTP URL")?; @@ -997,30 +1092,33 @@ fn validate(clients: Clients, secrets: Secrets) -> Result { "local review authorities need bounded IDs, exact loopback endpoints, producer bindings, recovery windows, and declared clients" ); } - match ( - &authority.completion_token_ref, - &authority.completion_recipient, - ) { - (None, None) => (), - (Some(reference), Some(recipient)) - if !recipient.trim().is_empty() - && recipient.len() <= 128 - && !recipient.chars().any(char::is_control) => - { - let token = secret( - &clients, - secrets, - &format!("reviewAuthorities.{id}.completionTokenRef"), - reference, - COMPLETION_TOKEN_BYTES, - )?; - if token.is_some_and(|token| !token.iter().all(|byte| byte.is_ascii_graphic())) { - bail!("local review completion tokens must be bounded visible ASCII"); + if let Some(completion) = &authority.completion { + let block = format!("reviewAuthorities.{id}.completion"); + if !registry_breg::review_store::valid_completion_recipient( + &completion.recipient_binding, + ) { + bail!("{block}.recipientBinding must contain 1 to 256 visible ASCII characters"); + } + if let Some(first) = completion_recipients.insert(&completion.recipient_binding, id) { + bail!("reviewAuthorities.{first}.completion.recipientBinding and {block}.recipientBinding select the same completion recipient"); + } + let start = delivery_keys.len(); + for (member, _, reference) in completion.references() { + let path = format!("{block}.{member}"); + if let Some(key) = checked_delivery_key(&clients, secrets, &path, reference)? { + delivery_keys.push((path, key)); + } + } + if let [(current, current_key), (previous, previous_key)] = &delivery_keys[start..] { + if distinct_delivery_keys([ + (current.as_str(), current_key), + (previous.as_str(), previous_key), + ]) + .is_err() + { + bail!("{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}."); } } - _ => bail!( - "local review completionTokenRef and completionRecipient must be declared together" - ), } } for (id, provider) in &clients.evidence_providers { @@ -1268,17 +1366,18 @@ fn validate(clients: Clients, secrets: Secrets) -> Result { )?; } for (id, destination) in &clients.destinations.hooks { - let key = secret( - &clients, - secrets, - &format!("destinations.hooks.{id}.hmacSha256KeyRef"), - &destination.hmac_sha256_key_ref, - HMAC_KEY_BYTES, - )?; - if key.is_some_and(|key| key.len() < 32) { - bail!("local event destination {id} needs at least 32 HMAC key bytes"); + let path = format!("destinations.hooks.{id}.hmacSha256KeyRef"); + if let Some(key) = + checked_delivery_key(&clients, secrets, &path, &destination.hmac_sha256_key_ref)? + { + delivery_keys.push((path, key)); } } + distinct_delivery_keys(delivery_keys.iter().map(|(path, key)| (path.as_str(), key))) + .map_err(|error| anyhow::anyhow!( + "{} and {} resolve to the same key bytes. Give {} its own key by writing 32 new random bytes to another secret and referencing it there.", + error.first(), error.second(), error.second(), + ))?; let mut seeds = BTreeSet::new(); for seed in &clients.seed { if !identifier(&seed.id) @@ -1445,12 +1544,13 @@ pub(super) fn prepare(root: &Path, state: &State, clients: &Clients) -> Result<( )?; } for (id, destination) in &clients.destinations.hooks { - let key = resolve_secret( + let key = delivery_secret( clients, + Secrets::Resolve, &format!("destinations.hooks.{id}.hmacSha256KeyRef"), &destination.hmac_sha256_key_ref, - HMAC_KEY_BYTES, - )?; + )? + .expect("resolve mode returns the secret"); private::create(&root.join("secrets").join(format!("webhook-{id}")), &key)?; } for (id, provider) in &clients.evidence_providers { @@ -1476,19 +1576,22 @@ pub(super) fn prepare(root: &Path, state: &State, clients: &Clients) -> Result<( let bytes = Zeroizing::new(private::read(&source, maximum)?); private::create(&root.join("secrets").join(name), &bytes)?; } - if let Some(reference) = &authority.completion_token_ref { - let bytes = resolve_secret( - clients, - &format!("reviewAuthorities.{id}.completionTokenRef"), - reference, - COMPLETION_TOKEN_BYTES, - )?; - private::create( - &root - .join("secrets") - .join(format!("review-completion-{id}-token")), - &bytes, - )?; + if let Some(completion) = &authority.completion { + for (member, suffix, reference) in completion.references() { + let bytes = delivery_secret( + clients, + Secrets::Resolve, + &format!("reviewAuthorities.{id}.completion.{member}"), + reference, + )? + .expect("resolve mode returns the secret"); + private::create( + &root + .join("secrets") + .join(format!("review-completion-{id}-{suffix}")), + &bytes, + )?; + } } } @@ -1521,9 +1624,6 @@ pub(super) fn prepare(root: &Path, state: &State, clients: &Clients) -> Result<( let encoded = Zeroizing::new(URL_SAFE_NO_PAD.encode(bytes.as_ref())); private::create(&root.join("secrets").join(filename), encoded.as_bytes())?; } - if state.webhook_port.is_some() { - webhook_secret(root)?; - } let password = Zeroizing::new(uuid::Uuid::new_v4().simple().to_string()); private::create( &root.join("database/postgres.env"), @@ -2077,7 +2177,7 @@ pub(super) fn runtime(root: &Path, state: &State, clients: &Clients, test: bool) } let destinations = if state.webhook_port.is_some() || !clients.destinations.hooks.is_empty() { if let Some(port) = state.webhook_port { - event_destinations(&compiled, port) + event_destinations(root, &compiled, port, false)? } else { external_event_destinations(&compiled, &clients.destinations.hooks)? } @@ -2228,10 +2328,12 @@ fn local_review_authorities(state: &State, clients: &Clients) -> BTreeMap Result<()> { +pub(super) fn inbox_key_path(root: &Path, destination_id: &str) -> PathBuf { + root.join("secrets") + .join(format!("inbox-key-{destination_id}")) +} + +pub(super) const INBOX_KEY_BYTES: u64 = 43; + +fn ensure_inbox_key(root: &Path, destination_id: &str, repair: bool) -> Result<()> { + let path = inbox_key_path(root, destination_id); + match fs::symlink_metadata(&path) { + Ok(metadata) => { + private::check_metadata(&metadata, false)?; + if metadata.len() == INBOX_KEY_BYTES { + return Ok(()); + } + if !repair { + bail!("The local inbox key is incomplete. Run bregctl dev stop --remove and start again."); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), + Err(error) => return Err(error.into()), + } let mut bytes = Zeroizing::new([0u8; 32]); getrandom::fill(bytes.as_mut()).context("cannot generate local webhook secret")?; let encoded = Zeroizing::new(URL_SAFE_NO_PAD.encode(bytes.as_ref())); - private::create(&root.join("secrets/webhook-key"), encoded.as_bytes()) + private::replace(&path, encoded.as_bytes()) +} + +#[cfg(test)] +#[test] +fn an_interrupted_inbox_key_write_requires_a_new_session() { + let root = tempfile::tempdir().unwrap(); + let secrets = root.path().join("secrets"); + private::directory(&secrets).unwrap(); + let path = inbox_key_path(root.path(), "local-hook"); + private::create(&path, b"unfinished").unwrap(); + let error = ensure_inbox_key(root.path(), "local-hook", false).unwrap_err(); + assert_eq!( + error.to_string(), + "The local inbox key is incomplete. Run bregctl dev stop --remove and start again." + ); + ensure_inbox_key(root.path(), "local-hook", true).unwrap(); + assert_eq!(fs::metadata(path).unwrap().len(), INBOX_KEY_BYTES); } /// Use the same compiled inventory as `explain events`. Shared destinations /// use the tightest attempt ceilings and the highest projected classification. -fn event_destinations(compiled: ®istry_breg::CompiledRegistry, port: u16) -> Value { +fn event_destinations( + root: &Path, + compiled: ®istry_breg::CompiledRegistry, + port: u16, + repair_keys: bool, +) -> Result { let mut destinations = BTreeMap::new(); for delivery in &compiled.event_deliveries().deliveries { // A local handler holds a reviewed program instead of a destination @@ -2332,15 +2477,48 @@ fn event_destinations(compiled: ®istry_breg::CompiledRegistry, port: u16) -> *timeout = (*timeout).min(delivery.attempt_timeout_ms); *attempts = (*attempts).min(delivery.maximum_attempts); } - Value::Object(destinations.into_iter().map(|(id, (classification, timeout, attempts))| { - (id.clone(), json!({ + destinations.into_iter().map(|(id, (classification, timeout, attempts))| { + ensure_inbox_key(root, id, repair_keys)?; + Ok((id.clone(), json!({ "origin":format!("http://127.0.0.1:{port}"),"path":"/events", "networkProfile":"loopback-development-http","dnsFamily":"dual-stack-strict", - "allowedPrivateCidrs":[],"hmacSha256KeyRef":"secret:file/webhook-key", + "allowedPrivateCidrs":[],"hmacSha256KeyRef":format!("secret:file/inbox-key-{id}"), "classificationCeiling":classification, "deliveryCeilings":{"attemptTimeoutMilliseconds":timeout,"maximumAttempts":attempts} - })) - }).collect()) + }))) + }).collect::>().map(Value::Object) +} + +/// Restore the inbox bindings after the operator has removed the retained database. +pub(super) fn repair_inbox(root: &Path, port: u16) -> Result<()> { + let Ok(compiled) = crate::compile(&root.join("project"), crate::ProfileArg::Production, "dev") + else { + // Database and receipt removal does not depend on the captured project. + return Ok(()); + }; + let hooks = event_destinations(root, &compiled, port, true)?; + for name in ["runtime.yaml", "runtime-test.yaml"] { + let path = root.join(name); + if path.try_exists()? { + let mut runtime = Reader::new(name) + .scan(&private::read(&path, MAX_BYTES)?) + .map_err(|report| anyhow::anyhow!("{report}"))? + .with_context(|| format!("{name} is empty"))? + .to_json_value(); + let destinations = runtime + .as_object_mut() + .with_context(|| format!("{name} must hold a runtime configuration"))? + .entry("destinations") + .or_insert_with(|| json!({})) + .as_object_mut() + .with_context(|| format!("{name} destinations must be a map"))?; + if destinations.get("hooks") != Some(&hooks) { + destinations.insert("hooks".to_owned(), hooks.clone()); + private::replace(&path, serde_norway::to_string(&runtime)?.as_bytes())?; + } + } + } + Ok(()) } pub(super) fn write_yaml(path: &Path, value: &Value) -> Result<()> { diff --git a/crates/registry-bregctl/src/dev/events.rs b/crates/registry-bregctl/src/dev/events.rs index 4cfb795884..561d2d5827 100644 --- a/crates/registry-bregctl/src/dev/events.rs +++ b/crates/registry-bregctl/src/dev/events.rs @@ -6,15 +6,15 @@ use anyhow::{bail, Context, Result}; use axum::{ body::{to_bytes, Body}, extract::{Request, State}, - http::{HeaderMap, StatusCode}, + http::StatusCode, routing::post, Router, }; use registry_breg::model::{CompiledEventDelivery, CompiledRegistry}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_hooks::{ - receiver::{verify_delivery, DeliveryFreshness, SignedDelivery}, - EnvelopeLimits, EventSubject, HookEnvelope, + receiver::{verify_hook_delivery, DeliveryFreshness, HookDelivery}, + DeliveryKey, DeliveryKeys, EventSubject, HookEnvelope, }; use serde_json::{json, Value}; use std::{ @@ -34,6 +34,8 @@ use zeroize::Zeroizing; const MAX_BODY: usize = 1024 * 1024; const MAX_STORAGE: u64 = 16 * 1024 * 1024; +type DeliveryMap = BTreeMap<(String, String), Delivery>; + pub(super) struct Receiver { stop: Option>, thread: Option>, @@ -41,8 +43,8 @@ pub(super) struct Receiver { struct Inbox { root: PathBuf, - key: Zeroizing>, - deliveries: BTreeMap<(String, String), Delivery>, + keys: BTreeMap, + deliveries: DeliveryMap, } struct Delivery { @@ -90,6 +92,36 @@ impl Delivery { } } +pub(super) fn check_destination_keys(root: &Path) -> Result<()> { + let compiled = crate::compile(&root.join("project"), crate::ProfileArg::Production, "dev") + .map_err(|_| anyhow::anyhow!("captured event project no longer compiles"))?; + for destination in compiled + .event_deliveries() + .deliveries + .iter() + .filter_map(|delivery| delivery.destination_id.as_deref()) + { + check_destination_key(&super::config::inbox_key_path(root, destination))?; + } + Ok(()) +} + +fn check_destination_key(path: &Path) -> Result<()> { + match fs::symlink_metadata(path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + bail!("This development session predates per-destination keys. Run bregctl dev stop --remove and start again."); + } + Err(error) => Err(error.into()), + Ok(metadata) => { + private::check_metadata(&metadata, false)?; + if metadata.len() != super::config::INBOX_KEY_BYTES { + bail!("The local inbox key is incomplete. Run bregctl dev stop --remove and start again."); + } + Ok(()) + } + } +} + impl Receiver { pub(super) fn start(root: &Path, port: u16, instance_id: &str) -> Result { let compiled = crate::compile(&root.join("project"), crate::ProfileArg::Production, "dev") @@ -97,7 +129,7 @@ impl Receiver { // The local receiver stands in for a remote destination, so it holds // the url deliveries only; a local handler runs inside the engine and // never reaches an HTTP receiver. - let mut deliveries: BTreeMap<(String, String), Delivery> = BTreeMap::new(); + let mut deliveries: DeliveryMap = BTreeMap::new(); for delivery in compiled .event_deliveries() .deliveries @@ -146,18 +178,25 @@ impl Receiver { Self::start_with_deliveries(root, port, deliveries) } - fn start_with_deliveries( - root: &Path, - port: u16, - deliveries: BTreeMap<(String, String), Delivery>, - ) -> Result { + fn start_with_deliveries(root: &Path, port: u16, deliveries: DeliveryMap) -> Result { private::check(root, true)?; - // Runtime secret:file resolution uses the exact file bytes as the HMAC - // key. Generated base64url text is key material, not a transport encoding - // for the receiver to decode independently. - let key = Zeroizing::new(private::read(&root.join("secrets/webhook-key"), 64 * 1024)?); - if key.len() < 32 { - bail!("local webhook key must contain at least 32 bytes"); + let mut keys = BTreeMap::new(); + for delivery in deliveries.values() { + for destination in std::iter::once(&delivery.destination_id) + .chain(delivery.matching.iter().map(|(_, destination)| destination)) + { + if let std::collections::btree_map::Entry::Vacant(entry) = + keys.entry(destination.clone()) + { + let path = super::config::inbox_key_path(root, destination); + check_destination_key(&path)?; + // Use the 43-character base64url text as the key bytes as written. + let bytes = Zeroizing::new(private::read(&path, 64 * 1024)?); + let key = DeliveryKey::new(&bytes) + .with_context(|| format!("invalid local inbox key for {destination}"))?; + entry.insert(DeliveryKeys::new(key, None).expect("one validated key")); + } + } } { let _lock = storage_lock(root)?; @@ -180,7 +219,7 @@ impl Receiver { }; let inbox = Arc::new(Inbox { root: root.to_path_buf(), - key, + keys, deliveries, }); let (stop, stopped) = oneshot::channel(); @@ -233,11 +272,30 @@ async fn receive( else { return (StatusCode::BAD_REQUEST, "invalid local webhook request"); }; - let Ok((mut record, document)) = verify(&inbox.key, &parts.headers, &body) else { - return ( - StatusCode::UNAUTHORIZED, - "local webhook verification refused", - ); + let refused = ( + StatusCode::UNAUTHORIZED, + "local webhook verification refused", + ); + let freshness = DeliveryFreshness::default_at(SystemTime::now()); + let Some((destination, verified)) = inbox.keys.iter().find_map(|(destination, keys)| { + let request = HookDelivery { + headers: parts + .headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())), + body: &body, + keys, + }; + verify_hook_delivery(request, freshness) + .ok() + .map(|verified| (destination, verified)) + }) else { + return refused; + }; + let source = verified.envelope.source.clone(); + let data_schema = verified.envelope.dataschema.clone(); + let Ok((mut record, document)) = receipt(verified.envelope) else { + return refused; }; let Some(delivery) = inbox.deliveries.get(&( record["eventType"].as_str().unwrap_or_default().to_owned(), @@ -255,31 +313,31 @@ async fn receive( // Validate the complete body against the same generated contract that // supplies its signed schema identity, including nullable projected fields // and the closed request metadata on lifecycle events. - if header(&parts.headers, "ce-dataschema").ok() != Some(delivery.data_schema.as_str()) - || header(&parts.headers, "ce-source").ok() != Some(delivery.source.as_str()) + if data_schema != delivery.data_schema + || source != delivery.source || !delivery.schema.is_valid(&document) { - return ( - StatusCode::UNAUTHORIZED, - "local webhook verification refused", - ); + return refused; } - if delivery.matching.is_empty() { - record["deliveryId"] = Value::String(delivery.id.clone()); - record["destinationId"] = Value::String(delivery.destination_id.clone()); - } else { - // The signed transport identifies the event, not its subscription. - // Keep the candidate subscriptions instead of guessing which sent it. - let matching = std::iter::once((&delivery.id, &delivery.destination_id)) - .chain( - delivery - .matching - .iter() - .map(|(id, destination)| (id, destination)), - ) - .map(|(id, destination)| json!({"deliveryId":id,"destinationId":destination})) - .collect::>(); - record["matchingDeliveries"] = json!(matching); + let matching = std::iter::once((&delivery.id, &delivery.destination_id)) + .chain( + delivery + .matching + .iter() + .map(|(id, destination)| (id, destination)), + ) + .filter(|(_, candidate)| *candidate == destination) + .collect::>(); + record["destinationId"] = json!(destination); + match matching.as_slice() { + [] => return refused, + [(id, _)] => record["deliveryId"] = json!(id), + _ => { + record["matchingDeliveries"] = json!(matching + .into_iter() + .map(|(id, destination)| json!({"deliveryId":id,"destinationId":destination})) + .collect::>()); + } } match append(&inbox.root, &record) { Ok(()) => (StatusCode::NO_CONTENT, ""), @@ -290,30 +348,6 @@ async fn receive( } } -fn header<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str> { - let mut values = headers.get_all(name).iter(); - let value = values - .next() - .context("webhook metadata is missing")? - .to_str() - .map_err(|_| anyhow::anyhow!("webhook metadata must be ASCII"))?; - if values.next().is_some() - || value.is_empty() - || value.len() > 1024 - || !value.bytes().all(|byte| byte.is_ascii_graphic()) - { - bail!("webhook metadata is ambiguous or exceeds its bound"); - } - Ok(value) -} - -fn positive(value: &str) -> Result { - if value.starts_with('0') || !value.bytes().all(|byte| byte.is_ascii_digit()) { - bail!("webhook counter is invalid"); - } - value.parse().context("webhook counter exceeds its bound") -} - fn digest(value: &str) -> bool { value.strip_prefix("sha256:").is_some_and(|hex| { hex.len() == 64 @@ -323,59 +357,17 @@ fn digest(value: &str) -> bool { }) } -fn verify(key: &[u8], headers: &HeaderMap, body: &[u8]) -> Result<(Value, Value)> { - // Authenticity is the shared Version 1 receiver's reading; what follows is - // this inbox's local policy over the verified attributes. - let verified = verify_delivery( - SignedDelivery { - method: "POST", - request_target: "/events", - headers: headers - .iter() - .map(|(name, value)| (name.as_str(), value.as_bytes())), - body, - key, - }, - DeliveryFreshness::Within { - now: SystemTime::now(), - skew: Duration::from_secs(30), - }, - ) - .map_err(|error| anyhow::anyhow!("webhook verification refused: {error}"))?; - if verified.content_type != "application/json" - || header(headers, "accept")? != "application/json" - || body.is_empty() - { - bail!("webhook profile is invalid"); - } +fn receipt(envelope: HookEnvelope) -> Result<(Value, Value)> { let event_id = - uuid::Uuid::parse_str(verified.id).context("webhook event identity is invalid")?; - if event_id.to_string() != verified.id { + uuid::Uuid::parse_str(&envelope.id).context("webhook event identity is invalid")?; + if event_id.to_string() != envelope.id { bail!("webhook event identity must be canonical"); } - let event_time = - OffsetDateTime::parse(verified.time, &Rfc3339).context("webhook event time is invalid")?; - let generation = positive(verified.generation)?; - let attempt = positive(verified.attempt)?; - let idempotency_key = verified.idempotency_key; - if !digest(idempotency_key) { - bail!("webhook idempotency key is invalid"); - } - let envelope = HookEnvelope::from_canonical_bytes(body, &EnvelopeLimits::default()) - .map_err(|_| anyhow::anyhow!("webhook envelope is invalid"))?; - if envelope.id != verified.id - || envelope.event_type != verified.event_type - || envelope.source != verified.source - || envelope.dataschema != verified.data_schema - || envelope.time != event_time - { - bail!("webhook envelope does not match its signed delivery attributes"); - } let data = envelope.data; let object = data .as_object() .context("webhook envelope data must be an object")?; - let registry = verified + let registry = envelope .source .strip_prefix("urn:registrystack:registry:") .and_then(|source| source.split_once(":instance:")) @@ -399,7 +391,7 @@ fn verify(key: &[u8], headers: &HeaderMap, body: &[u8]) -> Result<(Value, Value) bail!("webhook Proposal event subject shape is invalid"); }; if !SCHEMA.is_valid(&data) - || verified.event_type + || envelope.event_type != format!( "proposal.{}", data["transition"].as_str().unwrap_or_default() @@ -411,9 +403,9 @@ fn verify(key: &[u8], headers: &HeaderMap, body: &[u8]) -> Result<(Value, Value) { bail!("webhook Proposal event data shape is invalid"); } - let record = json!({"eventId":verified.id,"eventType":verified.event_type,"actionId":data["actionId"], + let record = json!({"eventId":envelope.id,"eventType":envelope.event_type,"actionId":data["actionId"], "trigger":"proposal-lifecycle","transition":data["transition"],"deliveryId":null, - "idempotencyKey":idempotency_key,"generation":generation,"attempt":attempt,"status":"received", + "webhookId":envelope.id,"status":"received", "receivedAt":OffsetDateTime::now_utc().format(&Rfc3339)?,"payload":data}); return Ok((record, data)); } @@ -458,19 +450,18 @@ fn verify(key: &[u8], headers: &HeaderMap, body: &[u8]) -> Result<(Value, Value) data["recordType"] .as_str() .context("webhook entity is invalid")?, - verified.event_type + envelope.event_type ); - if !verified - .data_schema + if !envelope + .dataschema .strip_prefix(&prefix) .is_some_and(digest) { bail!("webhook schema does not match event metadata"); } let record = json!({ - "eventId":verified.id,"eventType":verified.event_type,"recordType":data["recordType"], - "trigger":data["trigger"],"deliveryId":null,"idempotencyKey":idempotency_key, - "generation":generation,"attempt":attempt,"status":"received", + "eventId":envelope.id,"eventType":envelope.event_type,"recordType":data["recordType"], + "trigger":data["trigger"],"deliveryId":null,"webhookId":envelope.id,"status":"received", "receivedAt":OffsetDateTime::now_utc().format(&Rfc3339)?,"payload":data["values"] }); Ok((record, data)) @@ -515,19 +506,30 @@ fn append(root: &Path, record: &Value) -> Result<()> { let _lock = storage_lock(root)?; let path = root.join("events.jsonl"); let mut bytes = private::read(&path, MAX_STORAGE)?; + if !bytes.is_empty() && !bytes.ends_with(b"\n") { + bail!("local event inbox has an incomplete record"); + } + for line in bytes + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + { + let received = parse_json_strict(line).context("local event inbox record is invalid")?; + if received["destinationId"] == record["destinationId"] + && received["webhookId"] == record["webhookId"] + { + return Ok(()); + } + } let line = serde_json::to_vec(record)?; if bytes.len() as u64 + line.len() as u64 + 1 > MAX_STORAGE { bail!( "local event inbox reached its 16 MiB bound; stop the session and move the journal to an owner-only location before restarting" ); } - if !bytes.is_empty() && !bytes.ends_with(b"\n") { - bail!("local event inbox has an incomplete record"); - } bytes.extend_from_slice(&line); bytes.push(b'\n'); // Atomic replacement under the stable lock prevents partial reports and - // acknowledges only a durable complete record, including repeated attempts. + // acknowledges only a durable complete record. private::replace(&path, &bytes) } @@ -584,9 +586,7 @@ pub(super) fn report(root: &Path, include_payload: bool) -> Result { | "trigger" | "deliveryId" | "destinationId" - | "idempotencyKey" - | "generation" - | "attempt" + | "webhookId" | "status" | "receivedAt" ) @@ -601,22 +601,12 @@ pub(super) fn report(root: &Path, include_payload: bool) -> Result { #[cfg(test)] mod tests { use super::*; + use axum::http::HeaderMap; use axum::http::HeaderValue; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; - use hmac::{Hmac, KeyInit, Mac}; - use sha2::Sha256; + use registry_platform_crypto::delivery_signature; + use registry_platform_hooks::EnvelopeLimits; - const SIGNED_HEADERS: [&str; 9] = [ - "ce-specversion", - "ce-id", - "ce-source", - "ce-type", - "ce-time", - "ce-dataschema", - "x-registry-event-generation", - "x-registry-delivery-attempt", - "x-registry-delivery-time", - ]; use registry_breg::{ compiler::{compile_project, CompileProfile}, contract::{parse_project_json, EventTrigger}, @@ -632,6 +622,15 @@ mod tests { trigger: EventTrigger, vocabulary: bool, ) -> (tempfile::TempDir, u16, Receiver) { + let (root, port, deliveries) = captured_inbox(trigger, vocabulary); + let receiver = Receiver::start_with_deliveries(root.path(), port, deliveries).unwrap(); + (root, port, receiver) + } + + fn captured_inbox( + trigger: EventTrigger, + vocabulary: bool, + ) -> (tempfile::TempDir, u16, DeliveryMap) { let mut field = json!({"id":"label", "type":"string", "maximumLength":64, "classification":"internal"}); if vocabulary { @@ -665,54 +664,41 @@ mod tests { fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap(); private::directory(&root.path().join("secrets")).unwrap(); private::create( - &root.path().join("secrets/webhook-key"), + &root.path().join("secrets/inbox-key-local-hook"), URL_SAFE_NO_PAD.encode([7; 32]).as_bytes(), ) .unwrap(); + private::create( + &root.path().join("secrets/inbox-key-second-hook"), + URL_SAFE_NO_PAD.encode([8; 32]).as_bytes(), + ) + .unwrap(); + delivery + .matching + .push(("test-second-delivery".to_owned(), "second-hook".to_owned())); let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let port = listener.local_addr().unwrap().port(); drop(listener); - let receiver = Receiver::start_with_deliveries( - root.path(), - port, - BTreeMap::from([(("record-created-v1".into(), "record".into()), delivery)]), - ) - .unwrap(); - (root, port, receiver) + let deliveries = + BTreeMap::from([(("record-created-v1".into(), "record".into()), delivery)]); + (root, port, deliveries) } - /// The capture instant the delivery headers and the envelope share. Whole - /// milliseconds, the precision the envelope's wire form spells. const EVENT_TIME: &str = "2026-01-01T00:00:00.123Z"; + const EVENT_ID: &str = "00000000-0000-4000-8000-000000000001"; + const EVENT_SOURCE: &str = "urn:registrystack:registry:example:instance:local"; + const EVENT_SCHEMA_PREFIX: &str = + "urn:breg:event-schema:example:record:record-created-v1:sha256:"; - fn event_headers(attempt: u64, generation: u64) -> HeaderMap { - let now = OffsetDateTime::now_utc().format(&Rfc3339).unwrap(); + fn event_headers() -> HeaderMap { let mut headers = HeaderMap::new(); - for (name, value) in [ - ("accept", "application/json".into()), - ("content-type", "application/json".into()), - ("ce-specversion", "1.0".into()), - ("ce-id", "00000000-0000-4000-8000-000000000001".into()), - ( - "ce-source", - "urn:registrystack:registry:example:instance:local".into(), - ), - ("ce-type", "record-created-v1".into()), - ("ce-time", EVENT_TIME.to_owned()), - ( - "ce-dataschema", - format!( - "urn:breg:event-schema:example:record:record-created-v1:sha256:{}", - "0".repeat(64) - ), - ), - ("x-registry-event-generation", generation.to_string()), - ("x-registry-delivery-attempt", attempt.to_string()), - ("x-registry-delivery-time", now), - ("idempotency-key", format!("sha256:{}", "1".repeat(64))), - ] { - headers.insert(name, HeaderValue::from_str(&value).unwrap()); - } + headers.insert("accept", HeaderValue::from_static("application/json")); + headers.insert("content-type", HeaderValue::from_static("application/json")); + headers.insert("webhook-id", HeaderValue::from_static(EVENT_ID)); + headers.insert( + "webhook-timestamp", + HeaderValue::from_str(&OffsetDateTime::now_utc().unix_timestamp().to_string()).unwrap(), + ); headers } @@ -725,37 +711,29 @@ mod tests { }) } - /// The canonical envelope bytes a delivery with `headers` would carry. - fn envelope_bytes(headers: &HeaderMap, data: Value) -> Vec { - envelope_bytes_with_subject(headers, data, EventSubject::record("0".repeat(63) + "2", 1)) - } - - fn envelope_bytes_with_subject( - headers: &HeaderMap, - data: Value, - subject: EventSubject, - ) -> Vec { + fn envelope(data: Value) -> HookEnvelope { HookEnvelope { - id: headers["ce-id"].to_str().unwrap().to_owned(), - event_type: headers["ce-type"].to_str().unwrap().to_owned(), - source: headers["ce-source"].to_str().unwrap().to_owned(), - time: OffsetDateTime::parse(headers["ce-time"].to_str().unwrap(), &Rfc3339).unwrap(), - subject, - dataschema: headers["ce-dataschema"].to_str().unwrap().to_owned(), + id: EVENT_ID.to_owned(), + event_type: "record-created-v1".to_owned(), + source: EVENT_SOURCE.to_owned(), + time: OffsetDateTime::parse(EVENT_TIME, &Rfc3339).unwrap(), + subject: EventSubject::record("0".repeat(63) + "2", 1), + dataschema: format!("{EVENT_SCHEMA_PREFIX}{}", "0".repeat(64)), data, - causation: registry_platform_hooks::Causation::root(headers["ce-id"].to_str().unwrap()), + causation: registry_platform_hooks::Causation::root(EVENT_ID), } - .to_canonical_bytes(&EnvelopeLimits::default()) - .unwrap() } - fn signed(attempt: u64, generation: u64) -> (HeaderMap, Vec) { - signed_data(attempt, generation, event_data()) + fn signed() -> (HeaderMap, Vec) { + signed_envelope(envelope(event_data())) } - fn signed_data(attempt: u64, generation: u64, data: Value) -> (HeaderMap, Vec) { - let mut headers = event_headers(attempt, generation); - let body = envelope_bytes(&headers, data); + fn signed_envelope(envelope: HookEnvelope) -> (HeaderMap, Vec) { + let mut headers = event_headers(); + headers.insert("webhook-id", HeaderValue::from_str(&envelope.id).unwrap()); + let body = envelope + .to_canonical_bytes(&EnvelopeLimits::default()) + .unwrap(); sign(&mut headers, &body); (headers, body) } @@ -765,32 +743,21 @@ mod tests { } fn sign_with_key(headers: &mut HeaderMap, body: &[u8], key: &[u8]) { - // Independently construct the documented wire message, like the demo - // verifier, rather than calling the receiver's verification routine. - let mut input = b"breg-webhook-signature-v1".to_vec(); - for value in SIGNED_HEADERS - .iter() - .map(|name| headers[*name].as_bytes()) - .chain([ - b"POST".as_slice(), - b"/events".as_slice(), - b"application/json".as_slice(), - headers["idempotency-key"].as_bytes(), - body, - ]) - { - input.extend_from_slice(&(value.len() as u64).to_be_bytes()); - input.extend_from_slice(value); - } - let mut mac = Hmac::::new_from_slice(key).unwrap(); - mac.update(&input); + let keys = DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap(); + let signature = delivery_signature::sign( + &keys, + headers["webhook-id"].to_str().unwrap(), + headers["webhook-timestamp"] + .to_str() + .unwrap() + .parse() + .unwrap(), + body, + ) + .unwrap(); headers.insert( - "x-registry-signature", - HeaderValue::from_str(&format!( - "v1={}", - URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()) - )) - .unwrap(), + "webhook-signature", + HeaderValue::from_str(&signature).unwrap(), ); } @@ -817,12 +784,30 @@ mod tests { } #[test] - fn signed_receipts_preserve_attempts_and_generation_and_redact_values() { + fn a_session_missing_a_destination_key_explains_how_to_restart() { + let (root, port, deliveries) = captured_inbox(EventTrigger::Created, false); + fs::remove_file(root.path().join("secrets/inbox-key-second-hook")).unwrap(); + let error = Receiver::start_with_deliveries(root.path(), port, deliveries) + .err() + .expect("missing key prevents receiver startup"); + assert_eq!(error.to_string(), "This development session predates per-destination keys. Run bregctl dev stop --remove and start again."); + } + + #[test] + fn signed_receipts_record_the_webhook_id_and_destination_and_redact_values() { let (root, port, receiver) = fixture(); - for (attempt, generation) in [(1, 1), (2, 1), (1, 2)] { - let (headers, body) = signed(attempt, generation); + for _ in 0..3 { + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); } + let (mut headers, body) = signed(); + headers.insert( + "webhook-timestamp", + HeaderValue::from_str(&(OffsetDateTime::now_utc().unix_timestamp() + 10).to_string()) + .unwrap(), + ); + sign(&mut headers, &body); + assert_eq!(request(port, headers, body), 204); assert!(!receiver.exited()); let metadata = report(root.path(), false).unwrap(); assert!(!metadata.to_string().contains("projected-value-canary")); @@ -830,9 +815,8 @@ mod tests { .to_string() .contains("00000000-0000-4000-8000-000000000002")); let records = metadata["deliveries"].as_array().unwrap(); - assert_eq!(records.len(), 3); - assert_eq!(records[1]["attempt"], 2); - assert_eq!(records[2]["generation"], 2); + assert_eq!(records.len(), 1); + assert!(records.iter().all(|record| record["webhookId"] == EVENT_ID)); assert_eq!(records[0]["status"], "received"); assert_eq!( records[0]["deliveryId"], @@ -858,18 +842,47 @@ mod tests { .as_array() .unwrap() .len(), - 3 + 1 + ); + } + + #[test] + fn a_delivery_is_attributed_to_the_destination_whose_key_verifies() { + let (root, port, _receiver) = fixture(); + let (headers, body) = signed(); + assert_eq!(request(port, headers, body), 204); + let (mut headers, body) = signed(); + sign_with_key( + &mut headers, + &body, + URL_SAFE_NO_PAD.encode([8; 32]).as_bytes(), ); + assert_eq!(request(port, headers, body), 204); + let metadata = report(root.path(), false).unwrap(); + let records = metadata["deliveries"].as_array().unwrap(); + assert_eq!(records.len(), 2); + assert_eq!(records[0]["destinationId"], "local-hook"); + assert_eq!(records[1]["destinationId"], "second-hook"); + assert_eq!(records[1]["deliveryId"], "test-second-delivery"); + } + + #[test] + fn a_delivery_no_destination_key_verifies_is_refused_and_not_recorded() { + let (root, port, _receiver) = fixture(); + let (mut headers, body) = signed(); + sign_with_key(&mut headers, &body, &[9; 32]); + assert_eq!(request(port, headers, body), 401); + assert_eq!(report(root.path(), false).unwrap()["deliveries"], json!([])); } #[test] fn configured_raw_key_bytes_match_runtime_and_decoded_key_is_refused() { let (root, port, _receiver) = fixture(); - let key = private::read(&root.path().join("secrets/webhook-key"), 128).unwrap(); - let (mut headers, body) = signed(1, 1); + let key = private::read(&root.path().join("secrets/inbox-key-local-hook"), 128).unwrap(); + let (mut headers, body) = signed(); sign_with_key(&mut headers, &body, &key); assert_eq!(request(port, headers, body), 204); - let (mut headers, body) = signed(2, 1); + let (mut headers, body) = signed(); let decoded = URL_SAFE_NO_PAD.decode(&key).unwrap(); sign_with_key(&mut headers, &body, &decoded); assert_eq!(request(port, headers, body), 401); @@ -885,23 +898,24 @@ mod tests { #[test] fn tampered_stale_duplicate_and_noncanonical_packets_are_refused() { let (root, port, _receiver) = fixture(); - let (headers, mut body) = signed(1, 1); + let (headers, mut body) = signed(); body.push(b' '); assert_eq!(request(port, headers, body), 401); - let (mut headers, body) = signed(1, 1); - headers.insert("x-registry-delivery-attempt", HeaderValue::from_static("2")); + let (mut headers, body) = signed(); + headers.insert("webhook-timestamp", HeaderValue::from_static("1")); assert_eq!(request(port, headers, body), 401); - let (mut headers, body) = signed(1, 1); - headers.append("ce-type", HeaderValue::from_static("record-created-v1")); + let (mut headers, body) = signed(); + headers.append("webhook-id", HeaderValue::from_static(EVENT_ID)); assert_eq!(request(port, headers, body), 401); - let (mut headers, body) = signed(1, 1); + let (mut headers, body) = signed(); headers.insert( - "x-registry-delivery-time", - HeaderValue::from_static("2020-01-01T00:00:00Z"), + "webhook-timestamp", + HeaderValue::from_str(&(OffsetDateTime::now_utc().unix_timestamp() - 301).to_string()) + .unwrap(), ); sign(&mut headers, &body); assert_eq!(request(port, headers, body), 401); - let (mut headers, mut body) = signed(1, 1); + let (mut headers, mut body) = signed(); body.push(b' '); sign(&mut headers, &body); assert_eq!(request(port, headers, body), 401); @@ -920,28 +934,24 @@ mod tests { "extra projection", "missing projection", ] { - let mut headers = event_headers(1, 1); - let mut data = event_data(); + let mut delivery = envelope(event_data()); match change { - "trigger" => data["trigger"] = json!("patched"), + "trigger" => delivery.data["trigger"] = json!("patched"), "schema" => { - headers.insert( - "ce-dataschema", - HeaderValue::from_str(&format!( - "urn:breg:event-schema:example:record:record-created-v1:sha256:{}", - "f".repeat(64) - )) - .unwrap(), - ); + delivery.dataschema = format!("{EVENT_SCHEMA_PREFIX}{}", "f".repeat(64)) + } + "extra projection" => { + delivery.data["values"]["undeclared"] = json!("extra-value-canary") } - "extra projection" => data["values"]["undeclared"] = json!("extra-value-canary"), "missing projection" => { - data["values"].as_object_mut().unwrap().remove("label"); + delivery.data["values"] + .as_object_mut() + .unwrap() + .remove("label"); } _ => unreachable!(), } - let body = envelope_bytes(&headers, data); - sign(&mut headers, &body); + let (headers, body) = signed_envelope(delivery); assert_eq!(request(port, headers, body), 401, "{change}"); assert_eq!( report(root.path(), true).unwrap()["deliveries"], @@ -949,7 +959,7 @@ mod tests { "{change}" ); } - let (headers, body) = signed(1, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); assert_eq!( report(root.path(), false).unwrap()["deliveries"] @@ -963,7 +973,7 @@ mod tests { #[test] fn a_pre_envelope_body_is_refused_and_never_recorded() { let (root, port, _receiver) = fixture(); - let mut headers = event_headers(1, 1); + let mut headers = event_headers(); let body = canonicalize_json(&event_data()).unwrap(); sign(&mut headers, &body); assert_eq!( @@ -975,36 +985,27 @@ mod tests { } #[test] - fn an_envelope_that_disagrees_with_its_signed_attributes_is_refused() { + fn an_envelope_that_disagrees_with_its_webhook_id_is_refused() { let (root, port, _receiver) = fixture(); - let mut headers = event_headers(1, 1); - let mut other = event_headers(1, 1); - other.insert( - "ce-source", - HeaderValue::from_static("urn:registrystack:registry:example:instance:other"), + let (mut headers, body) = signed(); + headers.insert( + "webhook-id", + HeaderValue::from_static("00000000-0000-4000-8000-000000000003"), ); - let body = envelope_bytes(&other, event_data()); sign(&mut headers, &body); - assert_eq!( - request(port, headers, body), - 401, - "an envelope source that differs from the signed header is refused" - ); + assert_eq!(request(port, headers, body), 401); assert_eq!(report(root.path(), true).unwrap()["deliveries"], json!([])); } #[test] fn signed_source_must_match_the_configured_registry_instance() { let (root, port, _receiver) = fixture(); - let (mut headers, body) = signed(1, 1); - headers.insert( - "ce-source", - HeaderValue::from_static("urn:registrystack:registry:example:instance:other"), - ); - sign(&mut headers, &body); + let mut delivery = envelope(event_data()); + delivery.source = "urn:registrystack:registry:example:instance:other".to_owned(); + let (headers, body) = signed_envelope(delivery); assert_eq!(request(port, headers, body), 401); assert_eq!(report(root.path(), true).unwrap()["deliveries"], json!([])); - let (headers, body) = signed(1, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); assert_eq!( report(root.path(), false).unwrap()["deliveries"] @@ -1020,7 +1021,7 @@ mod tests { let (root, port, _receiver) = fixture(); let mut data = event_data(); data["values"]["label"] = Value::Null; - let (headers, body) = signed_data(1, 1, data); + let (headers, body) = signed_envelope(envelope(data)); assert_eq!(request(port, headers, body), 204); assert_eq!( report(root.path(), true).unwrap()["deliveries"][0]["payload"], @@ -1039,11 +1040,11 @@ mod tests { for value in invalid { let mut data = event_data(); data["values"]["label"] = value; - let (headers, body) = signed_data(1, 1, data); + let (headers, body) = signed_envelope(envelope(data)); assert_eq!(request(port, headers, body), 401); assert_eq!(report(root.path(), true).unwrap()["deliveries"], json!([])); } - let (headers, body) = signed(1, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); } } @@ -1053,11 +1054,11 @@ mod tests { let (root, port, _receiver) = fixture(); let path = root.path().join("events.jsonl"); fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); - let (headers, body) = signed(1, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 503); assert!(report(root.path(), false).is_err()); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); - let (headers, body) = signed(2, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); OpenOptions::new() .write(true) @@ -1065,7 +1066,7 @@ mod tests { .unwrap() .set_len(MAX_STORAGE) .unwrap(); - let (headers, body) = signed(1, 2); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 503); assert_eq!(fs::metadata(&path).unwrap().len(), MAX_STORAGE); } @@ -1105,8 +1106,11 @@ mod tests { })); } }); - for attempt in 1..=5 { - let (headers, body) = signed(attempt, 1); + for _ in 0..5 { + let mut event = envelope(event_data()); + event.id = uuid::Uuid::new_v4().to_string(); + event.causation = registry_platform_hooks::Causation::root(&event.id); + let (headers, body) = signed_envelope(event); assert_eq!(request(port, headers, body), 204); } reader.join().unwrap(); @@ -1122,9 +1126,9 @@ mod tests { #[test] fn clearing_received_payloads_is_idempotent_and_preserves_local_keys() { let (root, port, receiver) = fixture(); - let key_path = root.path().join("secrets/webhook-key"); + let key_path = root.path().join("secrets/inbox-key-local-hook"); let key = private::read(&key_path, 128).unwrap(); - let (headers, body) = signed(1, 1); + let (headers, body) = signed(); assert_eq!(request(port, headers, body), 204); drop(receiver); assert_eq!( @@ -1162,51 +1166,37 @@ mod tests { #[test] fn native_proposal_receipts_verify_the_fixed_contract_and_exact_transition() { - let mut headers = event_headers(1, 1); - headers.insert("ce-type", HeaderValue::from_static("proposal.submitted")); - headers.insert( - "ce-dataschema", - HeaderValue::from_static(registry_breg::proposal_hooks::PROPOSAL_EVENT_SCHEMA), - ); let data = json!({"actionId":"correct-name","actionRevision":format!("sha256:{}","a".repeat(64)), "proposalId":"00000000-0000-4000-8000-000000000002","submissionVersion":1,"revision":1, "fromState":"draft","state":"submitted","transition":"submitted","effectDigest":null, "authorityKind":"caller","systemApplyGrantRevision":null,"turn":"official"}); - let key = URL_SAFE_NO_PAD.encode([7; 32]); - let proposal_subject = + let proposal = |data, subject| HookEnvelope { + event_type: "proposal.submitted".to_owned(), + dataschema: registry_breg::proposal_hooks::PROPOSAL_EVENT_SCHEMA.to_owned(), + subject, + ..envelope(data) + }; + let subject = EventSubject::proposal("/v1/proposals/00000000-0000-4000-8000-000000000002", 1); - let body = envelope_bytes_with_subject(&headers, data.clone(), proposal_subject.clone()); - sign(&mut headers, &body); - let (record, projection) = verify(key.as_bytes(), &headers, &body).unwrap(); + let (record, projection) = receipt(proposal(data.clone(), subject.clone())).unwrap(); assert_eq!(record["actionId"], "correct-name"); assert!(record.get("recordType").is_none()); assert_eq!(projection, data); for member in ["input", "context", "attachments", "actor"] { let mut widened = data.clone(); widened[member] = json!("private-canary"); - let body = envelope_bytes_with_subject(&headers, widened, proposal_subject.clone()); - sign(&mut headers, &body); - assert!(verify(key.as_bytes(), &headers, &body).is_err()); + assert!(receipt(proposal(widened, subject.clone())).is_err()); } - let retired = envelope_bytes(&headers, data.clone()); - sign(&mut headers, &retired); - assert!( - verify(key.as_bytes(), &headers, &retired).is_err(), - "a Proposal event cannot retain the Record subject family" - ); - let mismatched = envelope_bytes_with_subject( - &headers, + assert!(receipt(proposal( data.clone(), - EventSubject::proposal("/v1/proposals/00000000-0000-4000-8000-000000000003", 1), - ); - sign(&mut headers, &mismatched); - assert!( - verify(key.as_bytes(), &headers, &mismatched).is_err(), - "a Proposal subject must name the event data's Proposal" - ); - headers.insert("ce-type", HeaderValue::from_static("proposal.applied")); - let body = envelope_bytes_with_subject(&headers, data, proposal_subject); - sign(&mut headers, &body); - assert!(verify(key.as_bytes(), &headers, &body).is_err()); + EventSubject::record("0".repeat(63) + "2", 1) + )) + .is_err()); + let mismatched = + EventSubject::proposal("/v1/proposals/00000000-0000-4000-8000-000000000003", 1); + assert!(receipt(proposal(data.clone(), mismatched)).is_err()); + let mut applied = proposal(data, subject); + applied.event_type = "proposal.applied".to_owned(); + assert!(receipt(applied).is_err()); } } diff --git a/crates/registry-bregctl/src/dev/mod.rs b/crates/registry-bregctl/src/dev/mod.rs index 574cedffb0..d58a149f92 100644 --- a/crates/registry-bregctl/src/dev/mod.rs +++ b/crates/registry-bregctl/src/dev/mod.rs @@ -1194,13 +1194,22 @@ fn start(args: StartArgs) -> Result { source_revision, } = capture(&project, &client_bytes)?; bind_journey_profiles(&files["tests/journeys.yaml"], &clients)?; - // The source pin protects the records a session retains. Once `dev stop - // --remove` has discarded them, changed inputs start a fresh session on - // the ports and clients file the previous one used. + // The source pin protects retained records. Once `dev stop --remove` + // discards a successor database, the next start builds an initial package + // from the current project. A successor cannot initialize an empty database. let mut previous = None; let existing = match existing { Some(state) - if digest != state.source_digest + if (state.container_id.is_none() + && (state.sequence > 1 + || (state.webhook_port.is_some() + && crate::compile( + &root.join("project"), + crate::ProfileArg::Production, + "dev", + ) + .is_err()))) + || digest != state.source_digest || args.breg_port.is_some_and(|p| p != state.breg_port) || args.issuer_port.is_some_and(|p| p != state.issuer_port) || requested_issuer @@ -1229,6 +1238,9 @@ fn start(args: StartArgs) -> Result { let mut state = if let Some(state) = existing { private::validate_tree(&root.join("credentials"))?; private::validate_tree(&root.join("secrets"))?; + if state.webhook_port.is_some() { + events::check_destination_keys(&root)?; + } if control(&root, "status").is_ok_and(|status| status == "ready") { borrowed_owner(&state)?; return state.report(); @@ -1334,11 +1346,6 @@ fn start(args: StartArgs) -> Result { first_start_ports = Some(selected_ports); read_state(&root)? }; - if state.sequence > 1 && state.container_id.is_none() { - bail!( - "the retained successor database was explicitly removed; a successor package cannot initialize empty records. Remove the project's .breg/dev directory, then run bregctl dev start to begin a fresh session" - ); - } let breg = match managed_breg { Some(path) => path, None => executable("breg", args.breg_bin.as_deref())?, @@ -1569,7 +1576,11 @@ fn reclaim(docker: &Path, state: &mut State) -> Result<()> { )?; events::clear(&state.root())?; reclaimed(state); - state.save() + state.save()?; + if let Some(port) = state.webhook_port.filter(|_| state.sequence == 1) { + config::repair_inbox(&state.root(), port)?; + } + Ok(()) } /// Forget the reclaimed database while keeping the ownership identifier, ports, diff --git a/crates/registry-bregctl/src/dev/tests.rs b/crates/registry-bregctl/src/dev/tests.rs index a464521b2e..fd857cf42b 100644 --- a/crates/registry-bregctl/src/dev/tests.rs +++ b/crates/registry-bregctl/src/dev/tests.rs @@ -3571,6 +3571,69 @@ fn start_without_binaries(project: &Path) -> Result { }) } +#[test] +fn reclaimed_successor_with_missing_inbox_key_starts_a_fresh_session() { + let (_temporary, state) = retained_inbox_session(2); + let root = state.root(); + fs::remove_file(config::inbox_key_path(&root, "local-hook")).unwrap(); + let refused = start_without_binaries(&state.project) + .unwrap_err() + .to_string(); + assert_eq!(refused, "This development session predates per-destination keys. Run bregctl dev stop --remove and start again."); + + // A successful empty Docker listing models a manually removed container. + stop(&state.project, true, Some(Path::new("/usr/bin/true"))).unwrap(); + let refusal = start_without_binaries(&state.project).unwrap_err(); + assert!(!refusal.to_string().contains("stop --remove"), "{refusal}"); + let fresh = read_state(&root).unwrap(); + assert_eq!(fresh.sequence, 1); + assert_ne!(fresh.owner, state.owner); + events::check_destination_keys(&root).unwrap(); +} + +#[test] +fn stop_remove_reclaims_an_uncompilable_captured_inbox_project() { + let (_temporary, state) = retained_inbox_session(1); + let root = state.root(); + fs::write(root.join("project/registry.yaml"), "not a registry").unwrap(); + let report = stop(&state.project, true, Some(Path::new("/usr/bin/true"))).unwrap(); + assert_eq!(report["status"], "stopped"); + let removed = read_state(&root).unwrap(); + assert!(removed.container_id.is_none()); + assert!(!removed.activated); + let refusal = start_without_binaries(&state.project).unwrap_err(); + assert!( + !refusal.to_string().contains("no longer compiles"), + "{refusal}" + ); + let fresh = read_state(&root).unwrap(); + assert_ne!(fresh.owner, state.owner); + events::check_destination_keys(&root).unwrap(); +} + +fn retained_inbox_session(sequence: u64) -> (tempfile::TempDir, State) { + let (temporary, project) = write_retained_project(); + let file = project.join("registry.yaml"); + let mut source: Value = serde_norway::from_slice(&fs::read(&file).unwrap()).unwrap(); + source["recordTypes"]["record"]["hooks"] = json!([ + {"phase":"after","id":"record-created-v1","trigger":"created","projection":["code"],"handler":{"type":"url","destinationId":"local-hook"}} + ]); + fs::write(&file, serde_norway::to_string(&source).unwrap()).unwrap(); + let mut state = retained_session(&project, Some("c".repeat(64))); + let ports = unused_ports(); + state.breg_port = ports[0]; + state.issuer_port = ports[1]; + state.database_port = ports[2]; + state.webhook_port = Some(receiver_port(&state).unwrap()); + state.sequence = sequence; + if sequence > 1 { + state.baseline_runtime = Some(state.root().join("baseline-1/runtime.yaml")); + } + state.save().unwrap(); + config::repair_inbox(&state.root(), state.webhook_port.unwrap()).unwrap(); + (temporary, state) +} + #[test] fn a_first_start_reads_the_projects_dev_clients_without_a_flag() { let (_temporary, project) = write_retained_project(); @@ -4164,24 +4227,25 @@ fn export_client_reuses_readable_nonexecutable_credentials_only() { } #[test] -fn removed_successor_database_is_refused_before_any_prerequisite_or_recreation() { +fn removed_successor_database_restarts_from_an_initial_package() { let (_temporary, project) = write_retained_project(); let mut state = retained_session(&project, Some("a".repeat(64))); + let ports = unused_ports(); + state.breg_port = ports[0]; + state.issuer_port = ports[1]; + state.database_port = ports[2]; state.sequence = 2; state.baseline_runtime = Some(state.root().join("baseline-1/runtime.yaml")); reclaimed(&mut state); state.save().unwrap(); - let before = private::read(&state.root().join("state.json"), MAX_BYTES).unwrap(); + let error = start_without_binaries(&project).unwrap_err().to_string(); - assert!( - error.contains("successor database was explicitly removed"), - "{error}" - ); - assert_eq!( - private::read(&state.root().join("state.json"), MAX_BYTES).unwrap(), - before - ); - assert!(read_state(&state.root()).unwrap().container_id.is_none()); + assert!(!error.contains("successor database"), "{error}"); + let fresh = read_state(&state.root()).unwrap(); + assert_ne!(fresh.owner, state.owner); + assert_eq!(fresh.sequence, 1); + assert!(fresh.baseline_runtime.is_none()); + assert!(fresh.container_id.is_none()); } #[test] @@ -4309,7 +4373,11 @@ fn declared_events_receive_exact_private_bindings_in_rehearsal_and_runtime() { let value: Value = serde_norway::from_slice(&fs::read(root.join(filename)).unwrap()).unwrap(); assert_eq!(value["destinations"]["hooks"].as_object().unwrap().len(), 2); - for binding in value["destinations"]["hooks"].as_object().unwrap().values() { + for (id, binding) in value["destinations"]["hooks"].as_object().unwrap() { + assert_eq!( + binding["hmacSha256KeyRef"], + format!("secret:file/inbox-key-{id}") + ); assert_eq!(binding["origin"], "http://127.0.0.1:18996"); assert_eq!(binding["networkProfile"], "loopback-development-http"); assert_eq!(binding["classificationCeiling"], "internal"); @@ -4320,6 +4388,16 @@ fn declared_events_receive_exact_private_bindings_in_rehearsal_and_runtime() { ); } } + let missing = config::inbox_key_path(&root, "second-hook"); + fs::remove_file(&missing).unwrap(); + let error = events::check_destination_keys(&root).unwrap_err(); + assert_eq!(error.to_string(), "This development session predates per-destination keys. Run bregctl dev stop --remove and start again."); + config::repair_inbox(&root, 18996).unwrap(); + events::check_destination_keys(&root).unwrap(); + assert_eq!( + fs::metadata(missing).unwrap().len(), + config::INBOX_KEY_BYTES + ); private::validate_tree(&root).unwrap(); let saved = read_state(&root).unwrap(); assert_eq!(saved.webhook_port, Some(18996)); @@ -4329,6 +4407,43 @@ fn declared_events_receive_exact_private_bindings_in_rehearsal_and_runtime() { assert!(read_state(&root).is_err()); } +#[test] +fn a_retained_session_gains_a_key_for_a_new_destination_and_keeps_existing_keys() { + let (_project_temp, project) = write_retained_project(); + let module = project.join("registry.yaml"); + let mut source: Value = serde_norway::from_slice(&fs::read(&module).unwrap()).unwrap(); + source["recordTypes"]["record"]["hooks"] = json!([ + {"phase":"after","id":"record-created-v1","trigger":"created","projection":["code"],"handler":{"type":"url","destinationId":"local-hook"}} + ]); + fs::write(&module, serde_norway::to_string(&source).unwrap()).unwrap(); + let bytes = fs::read(project.join("dev-clients.yaml")).unwrap(); + let clients = config::clients("dev-clients.yaml", &bytes).unwrap(); + let captured = capture(&project, &bytes).unwrap(); + let (_temp, mut state, _, _) = fixture(); + state.webhook_port = Some(18996); + let root = state.root(); + initialize(&root, &state, &clients, &captured.files).unwrap(); + let original = config::inbox_key_path(&root, "local-hook"); + let bytes = private::read(&original, 64).unwrap(); + let added = config::inbox_key_path(&root, "second-hook"); + assert!(!added.exists()); + source["recordTypes"]["record"]["hooks"].as_array_mut().unwrap().push(json!({ + "phase":"after","id":"record-second-v1","trigger":"created","projection":["code"],"handler":{"type":"url","destinationId":"second-hook"} + })); + private::replace( + &root.join("project/registry.yaml"), + serde_norway::to_string(&source).unwrap().as_bytes(), + ) + .unwrap(); + private::directory(&root.join("build")).unwrap(); + private::directory(&root.join("build/package")).unwrap(); + config::runtime(&root, &state, &clients, false).unwrap(); + assert_eq!(private::read(&original, 64).unwrap(), bytes); + let new_key = private::read(&added, 64).unwrap(); + assert_eq!(new_key.len(), 43); + assert_ne!(new_key, bytes); +} + #[test] fn explicit_local_event_destinations_bind_exact_compiled_inventory() { let (_project_temp, project) = write_retained_project(); @@ -4373,6 +4488,31 @@ fn explicit_local_event_destinations_bind_exact_compiled_inventory() { serde_norway::from_slice(&fs::read(root.join("runtime-test.yaml")).unwrap()).unwrap(); assert_eq!(runtime["destinations"]["hooks"], bindings); assert!(config::external_event_destinations(&compiled, &BTreeMap::new()).is_err()); + let validate = |clients: &config::Clients| { + config::clients( + "dev-clients.yaml", + serde_norway::to_string(clients).unwrap().as_bytes(), + ) + .unwrap_err() + .to_string() + }; + let distinct = clients.destinations.hooks["openfn"].clone(); + clients + .destinations + .hooks + .insert("second".to_owned(), distinct); + assert_eq!(validate(&clients), "destinations.hooks.openfn.hmacSha256KeyRef and destinations.hooks.second.hmacSha256KeyRef resolve to the same key bytes. Give destinations.hooks.second.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."); + clients + .destinations + .hooks + .get_mut("second") + .unwrap() + .hmac_sha256_key_ref = file_secret(&secrets, "short-event-key", &[5; 31]); + let error = validate(&clients); + assert!( + error.contains("destinations.hooks.second.hmacSha256KeyRef has 31 bytes"), + "{error}" + ); } #[test] @@ -4491,11 +4631,7 @@ fn local_event_destinations_refuse_hmac_key_bytes_the_runtime_cannot_load() { let mut clients = config::clients("dev-clients.yaml", &bytes).unwrap(); fs::set_permissions(&project, fs::Permissions::from_mode(0o700)).unwrap(); let secrets = secret_root(&project, &mut clients); - // The runtime resolves this key through the shared secret resolver, which - // refuses any value carrying a NUL byte. A randomly generated key holds one - // about one time in eight. The clients file resolves its reference through - // the same resolver, so it refuses the value before a start rather than - // leaving it to a failed one. + // A binary key may contain a NUL byte. Both readers use the exact bytes. let mut material = b"synthetic-local-event-key-for-tes".to_vec(); material[8] = 0; let key = file_secret(&secrets, "event-key", &material); @@ -4507,28 +4643,28 @@ fn local_event_destinations_refuse_hmac_key_bytes_the_runtime_cannot_load() { hmac_sha256_key_ref: key, }, ); - let refusal = config::clients( + config::clients( "dev-clients.yaml", &serde_norway::to_string(&clients).unwrap().into_bytes(), ) - .unwrap_err() - .to_string(); - assert!( - refusal.contains("destinations.hooks.openfn.hmacSha256KeyRef could not be resolved") - && refusal.contains("without NUL bytes"), - "{refusal}" - ); + .expect("a NUL byte is valid in a binary signing key"); private::replace( &secrets.join("event-key"), - b"synthetic-local-event-key-for-test", + b"whsec_synthetic-signing-key-canary", ) .unwrap(); - config::clients( + let refusal = config::clients( "dev-clients.yaml", &serde_norway::to_string(&clients).unwrap().into_bytes(), ) - .unwrap(); + .unwrap_err() + .to_string(); + assert!( + refusal.contains("destinations.hooks.openfn.hmacSha256KeyRef") + && refusal.contains("Supply the exact key bytes without the whsec_ encoding."), + "{refusal}" + ); } #[test] @@ -4698,8 +4834,8 @@ fn local_review_authority_uses_refreshing_logical_client_without_exposing_creden let secrets = secret_root(&state.project, &mut clients); let completion = file_secret( &secrets, - "review-completion-token", - b"synthetic-completion-token", + "review-completion-key", + b"synthetic-completion-key-32-bytes", ); clients.review_authorities.insert( "casework-a".into(), @@ -4709,8 +4845,11 @@ fn local_review_authority_uses_refreshing_logical_client_without_exposing_creden producer_id: "registry-producer".into(), recovery_days: 7, client: "operator".into(), - completion_token_ref: Some(completion.clone()), - completion_recipient: Some("registry-breg".into()), + completion: Some(config::LocalReviewCompletion { + recipient_binding: "registry-breg".into(), + hmac_sha256_key_ref: completion.clone(), + previous_hmac_sha256_key_ref: None, + }), }, ); config::clients( @@ -4741,10 +4880,10 @@ fn local_review_authority_uses_refreshing_logical_client_without_exposing_creden "secret:file/review-authority-casework-a-client-assertion-key" ); assert_eq!( - authority["completionTokenRef"], - "secret:file/review-completion-casework-a-token" + authority["completion"]["hmacSha256KeyRef"], + "secret:file/review-completion-casework-a-key" ); - assert_eq!(authority["completionRecipient"], "registry-breg"); + assert_eq!(authority["completion"]["recipientBinding"], "registry-breg"); assert!(authority.get("tokenRef").is_none()); assert_eq!( @@ -4756,26 +4895,25 @@ fn local_review_authority_uses_refreshing_logical_client_without_exposing_creden fs::read(root.join("credentials/operator/assertion-key.jwk")).unwrap() ); assert_eq!( - fs::read(root.join("secrets/review-completion-casework-a-token")).unwrap(), - b"synthetic-completion-token" + fs::read(root.join("secrets/review-completion-casework-a-key")).unwrap(), + b"synthetic-completion-key-32-bytes" ); let rendered = String::from_utf8(runtime_bytes).unwrap(); - assert!(!rendered.contains("synthetic-completion-token")); + assert!(!rendered.contains("synthetic-completion-key-32-bytes")); assert!(!rendered.contains(completion.as_str())); registry_breg::runtime_config::load_runtime_config(&root.join("runtime-test.yaml")).unwrap(); } #[test] fn local_review_authorities_are_closed_and_bounded() { - let (_temp, state, mut clients, _files) = fixture(); + let (_temp, _state, mut clients, _files) = fixture(); let binding = config::LocalReviewAuthority { endpoint: "http://127.0.0.1:18096/".into(), profile: "integration-requester".into(), producer_id: "registry-producer".into(), recovery_days: 7, client: "operator".into(), - completion_token_ref: None, - completion_recipient: None, + completion: None, }; clients .review_authorities @@ -4849,25 +4987,28 @@ fn local_review_authorities_are_closed_and_bounded() { ) .is_err()); - let secrets = secret_root(&state.project, &mut clients); - let completion = file_secret( - &secrets, - "review-completion-token", - b"synthetic-completion-token", - ); clients.review_authorities.clear(); - let mut mismatched = binding; - mismatched.completion_token_ref = Some(completion); clients .review_authorities - .insert("casework-a".into(), mismatched); - let refusal = config::clients( - "dev-clients.yaml", - &serde_norway::to_string(&clients).unwrap().into_bytes(), - ) - .unwrap_err() - .to_string(); - assert!(refusal.contains("declared together"), "{refusal}"); + .insert("casework-a".into(), binding); + for (key, replacement) in [ + ("completionTokenRef", "completion.hmacSha256KeyRef"), + ("completionRecipient", "completion.recipientBinding"), + ] { + let mut raw = serde_json::to_value(&clients).unwrap(); + raw["reviewAuthorities"]["casework-a"][key] = json!("canary-old-value"); + let refusal = config::clients( + "dev-clients.yaml", + &serde_norway::to_string(&raw).unwrap().into_bytes(), + ) + .unwrap_err() + .to_string(); + assert!(refusal.contains(replacement), "{refusal}"); + assert!( + !refusal.contains("canary-old-value"), + "the refusal for {key} repeats the old reference value" + ); + } } #[test] @@ -5047,7 +5188,15 @@ fn event_free_sessions_keep_working_without_receiver_state() { assert_eq!(state.webhook_port, None); initialize(&state.root(), &state, &clients, &files).unwrap(); assert_eq!(read_state(&state.root()).unwrap().webhook_port, None); - assert!(!state.root().join("secrets/webhook-key").exists()); + assert!(fs::read_dir(state.root().join("secrets")) + .unwrap() + .all(|entry| { + !entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("inbox-key-") + })); let report = events::report(&state.root(), false).unwrap(); assert_eq!(report["deliveries"], json!([])); } @@ -5442,7 +5591,6 @@ reviewAuthorities: recoveryDays: 7 client: operator completionTokenFile: /private/completion-token - completionRecipient: registry-breg issuer: interactiveApplications: - id: portal @@ -5501,7 +5649,7 @@ issuer: ), ( "/reviewAuthorities/casework-a/completionTokenFile", - "completionTokenRef", + "completion.hmacSha256KeyRef", ), ( "/issuer/interactiveApplications/0/clientSecretFile", @@ -5572,8 +5720,8 @@ fn a_secret_reference_needs_a_declared_provider() { let secrets = secret_root(&state.project, &mut clients); let completion = file_secret( &secrets, - "review-completion-token", - b"synthetic-completion-token", + "review-completion-key", + b"synthetic-completion-key-32-bytes", ); clients.review_authorities.insert( "casework-a".into(), @@ -5583,8 +5731,11 @@ fn a_secret_reference_needs_a_declared_provider() { producer_id: "registry-producer".into(), recovery_days: 7, client: "operator".into(), - completion_token_ref: Some(completion.clone()), - completion_recipient: Some("registry-breg".into()), + completion: Some(config::LocalReviewCompletion { + recipient_binding: "registry-breg".into(), + hmac_sha256_key_ref: completion.clone(), + previous_hmac_sha256_key_ref: None, + }), }, ); config::clients( @@ -5604,7 +5755,7 @@ fn a_secret_reference_needs_a_declared_provider() { .unwrap_err() ); assert!( - refusal.contains("reviewAuthorities.casework-a.completionTokenRef names a secret") + refusal.contains("reviewAuthorities.casework-a.completion.hmacSha256KeyRef names a secret") && refusal.contains("declares no secretProviders"), "{refusal}" ); @@ -5617,8 +5768,11 @@ fn a_secret_reference_needs_a_declared_provider() { .review_authorities .get_mut("casework-a") .unwrap() - .completion_token_ref = - Some(SecretReference::parse("secret:env/BREGCTL_DEV_UNSET_SECRET").unwrap()); + .completion + .as_mut() + .unwrap() + .hmac_sha256_key_ref = + SecretReference::parse("secret:env/BREGCTL_DEV_UNSET_SECRET").unwrap(); let refusal = format!( "{:#}", config::clients( @@ -5628,8 +5782,8 @@ fn a_secret_reference_needs_a_declared_provider() { .unwrap_err() ); assert!( - refusal.contains("completionTokenRef could not be resolved") - && refusal.contains("declare the provider the reference names under secretProviders"), + refusal.contains("completion.hmacSha256KeyRef could not be resolved") + && refusal.contains("Enable the reference's provider under secretProviders"), "{refusal}" ); assert!(!refusal.contains("BREGCTL_DEV_UNSET_SECRET"), "{refusal}"); @@ -5640,8 +5794,8 @@ fn an_environment_reference_resolves_through_the_declared_provider() { // Cargo sets its package variables in the environment of every test it // runs, so the test reads one without writing the process environment. assert_eq!( - std::env::var("CARGO_PKG_NAME").as_deref(), - Ok(env!("CARGO_PKG_NAME")) + std::env::var("CARGO_PKG_REPOSITORY").as_deref(), + Ok(env!("CARGO_PKG_REPOSITORY")) ); let (_temp, state, mut clients, files) = fixture(); clients.secret_providers = Some(SecretProvidersConfig { @@ -5654,8 +5808,11 @@ fn an_environment_reference_resolves_through_the_declared_provider() { producer_id: "registry-producer".into(), recovery_days: 7, client: "operator".into(), - completion_token_ref: Some(SecretReference::parse("secret:env/CARGO_PKG_NAME").unwrap()), - completion_recipient: Some("registry-breg".into()), + completion: Some(config::LocalReviewCompletion { + recipient_binding: "registry-breg".into(), + hmac_sha256_key_ref: SecretReference::parse("secret:env/CARGO_PKG_REPOSITORY").unwrap(), + previous_hmac_sha256_key_ref: None, + }), }; clients .review_authorities @@ -5670,15 +5827,15 @@ fn an_environment_reference_resolves_through_the_declared_provider() { fs::read( state .root() - .join("secrets/review-completion-casework-a-token") + .join("secrets/review-completion-casework-a-key") ) .unwrap(), - env!("CARGO_PKG_NAME").as_bytes() + env!("CARGO_PKG_REPOSITORY").as_bytes() ); let mut unset = binding; - unset.completion_token_ref = - Some(SecretReference::parse("secret:env/BREGCTL_DEV_UNSET_SECRET").unwrap()); + unset.completion.as_mut().unwrap().hmac_sha256_key_ref = + SecretReference::parse("secret:env/BREGCTL_DEV_UNSET_SECRET").unwrap(); clients .review_authorities .insert("casework-a".into(), unset); @@ -5691,8 +5848,8 @@ fn an_environment_reference_resolves_through_the_declared_provider() { .unwrap_err() ); assert!( - refusal.contains("completionTokenRef could not be resolved") - && refusal.contains("set the environment variable the reference names"), + refusal.contains("completion.hmacSha256KeyRef could not be resolved") + && refusal.contains("Create the secret under the configured provider"), "{refusal}" ); assert!(!refusal.contains("BREGCTL_DEV_UNSET_SECRET"), "{refusal}"); diff --git a/crates/registry-bregctl/src/doctor.rs b/crates/registry-bregctl/src/doctor.rs index b9e5933b86..9d761b3c97 100644 --- a/crates/registry-bregctl/src/doctor.rs +++ b/crates/registry-bregctl/src/doctor.rs @@ -246,6 +246,15 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { if let StartupError::PackageEnvelopeRefused(cause) = error { return diagnostic("startup.package.refused", "package", &cause); } + // The shared key set rule names the rule and the key's position, never a + // key value. + if let StartupError::StaticKeySet(cause) = error { + return diagnostic( + "startup.oidc.refused", + "authentication.oidc", + &format!("the OIDC key set was refused: {cause}"), + ); + } // The writer's own refusal names the rule and the recovery step, and // never a path or a secret. if let StartupError::AuditDestination(reason) = error { @@ -255,12 +264,21 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { &format!("the audit destination was refused: {reason}"), ); } + if let StartupError::EventDestinations(reason) = error { + let path = reason + .split_whitespace() + .next() + .filter(|path| path.starts_with("reviewAuthorities.")) + .unwrap_or("destinations.hooks"); + return diagnostic("startup.hook-destinations.refused", path, &reason); + } let (code, path, message) = match error { StartupError::RuntimeConfig(_) => { unreachable!("startup_refusal reports every runtime configuration diagnostic") } StartupError::PackageRefused(_) | StartupError::PackageEnvelopeRefused(_) + | StartupError::StaticKeySet(_) | StartupError::AuditDestination(_) => { unreachable!("handled above") } @@ -366,11 +384,7 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { "authentication", "the project names clients in requesterClients, trusted actors, or consent recipients that authentication.oidc.allowedClients does not list; list each of them in allowedClients, because the keyword unrestricted lists none", ), - StartupError::EventDestinations => ( - "startup.hook-destinations.refused", - "destinations.hooks", - "the event destination bindings were refused", - ), + StartupError::EventDestinations(_) => unreachable!("handled above"), StartupError::RetainedHookBindings { .. } => { unreachable!("retained hook binding diagnostics return before the generic mapping") } @@ -488,7 +502,9 @@ mod tests { StartupError::Cursor, StartupError::Oidc, StartupError::Authentication, - StartupError::EventDestinations, + StartupError::EventDestinations( + "the event destination bindings were refused".to_owned(), + ), StartupError::FieldEncryption, StartupError::FieldEncryptionCustody, StartupError::ReviewBindings, @@ -743,10 +759,23 @@ mod tests { "authentication", ), ( - StartupError::EventDestinations, + StartupError::EventDestinations( + "the event destination bindings were refused".to_owned(), + ), "startup.hook-destinations.refused", "destinations.hooks", ), + ( + StartupError::EventDestinations( + registry_breg::event_destination::EventDestinationActivationError::RepeatedSigningKey { + first: "reviewAuthorities.alpha.completion.hmacSha256KeyRef".to_owned(), + second: "reviewAuthorities.beta.completion.hmacSha256KeyRef".to_owned(), + } + .to_string(), + ), + "startup.hook-destinations.refused", + "reviewAuthorities.alpha.completion.hmacSha256KeyRef", + ), ( StartupError::FieldEncryption, "startup.field-encryption.refused", @@ -986,6 +1015,13 @@ mod tests { "/operationalTimeouts", ), (RuntimeConfigError::Secret, "breg.runtime.secret", ""), + ( + RuntimeConfigError::SecretFile( + registry_platform_config::SecretFileCheck::HardLinked, + ), + "breg.runtime.secret", + "", + ), ]; for (cause, expected_code, expected_path) in cases { @@ -1030,6 +1066,25 @@ mod tests { .all(|diagnostic| diagnostic.message.contains("; next: "))); } + #[test] + fn a_refused_static_key_set_keeps_the_key_source_code_and_names_the_rule() { + let diagnostic = startup_diagnostic(StartupError::StaticKeySet( + registry_breg::startup::StaticJwksError::PrivateKeyMember { + key: 0, + member: "d", + }, + )); + assert_eq!(diagnostic.code, "startup.oidc.refused"); + assert_eq!(diagnostic.path, "authentication.oidc"); + assert!( + diagnostic + .message + .contains("key 0 carries the private-key member \"d\""), + "{}", + diagnostic.message + ); + } + #[test] fn authentication_dependency_refusals_name_the_causes_an_operator_checks() { let key_source = startup_diagnostic(StartupError::Oidc); diff --git a/crates/registry-bregctl/src/explain_report.rs b/crates/registry-bregctl/src/explain_report.rs index 0d3b74d036..51cef5e916 100644 --- a/crates/registry-bregctl/src/explain_report.rs +++ b/crates/registry-bregctl/src/explain_report.rs @@ -167,12 +167,20 @@ pub(crate) fn actions(value: &Value, lines: &mut Lines) { } } if let Some(comparison) = guard.get("currentDate") { - let offset = guard["currentDateOffsetDays"] - .as_i64() - .filter(|days| *days != 0); + let offset = [ + ("currentDateOffsetDays", "days"), + ("currentDateOffsetMonths", "months"), + ] + .into_iter() + .find_map(|(key, unit)| { + guard[key] + .as_i64() + .filter(|amount| *amount != 0) + .map(|amount| (amount, unit)) + }); terms.push(match (comparison.as_str(), offset) { - (Some(comparison), Some(days)) => { - format!("current date {comparison} ({days:+} days)") + (Some(comparison), Some((amount, unit))) => { + format!("current date {comparison} ({amount:+} {unit})") } _ => format!("current date {comparison}"), }); @@ -639,6 +647,27 @@ mod tests { ); } + #[test] + fn action_summary_names_a_current_date_month_offset() { + let value = json!([{ + "id":"renew", "execution":{"mode":"immediate"}, "inputs":[], + "plan":{"effects":[]}, + "commitGuards":[{ + "input":"licence", "field":"valid-through", "revisionUnchanged":false, + "currentDate":"on-or-before", "currentDateOffsetMonths":-3 + }], + "permissions":[] + }]); + let mut lines = Lines::new(); + actions(&value, &mut lines); + let rendered = lines.finish(); + let text = rendered.split_whitespace().collect::>().join(" "); + assert!( + text.contains("current date on-or-before (-3 months)"), + "{rendered}" + ); + } + #[test] fn permission_gates_quote_literal_identifiers_and_label_empty_lists() { for identifiers in [ diff --git a/crates/registry-bregctl/src/hook_lifecycle.rs b/crates/registry-bregctl/src/hook_lifecycle.rs index fcfb7a1b08..b1c1ab0fbb 100644 --- a/crates/registry-bregctl/src/hook_lifecycle.rs +++ b/crates/registry-bregctl/src/hook_lifecycle.rs @@ -29,10 +29,8 @@ const SAMPLE_RECORD_REFERENCE: &str = const SAMPLE_TIME: &str = "2026-01-01T00:00:00Z"; const SAMPLE_PACKAGE_REVISION: &str = "sha256:0000000000000000000000000000000000000000000000000000000000000000"; -const SAMPLE_IDEMPOTENCY_KEY: &str = - "sha256:0000000000000000000000000000000000000000000000000000000000000000"; const SAMPLE_REQUEST_TARGET: &str = ""; -const SAMPLE_SIGNATURE: &str = "v1="; +const SAMPLE_SIGNATURE: &str = "v1,"; const MAX_SCHEMA_SYNTHESIS_DEPTH: usize = 16; #[derive(Clone, Debug, Eq, PartialEq)] @@ -40,6 +38,7 @@ pub(crate) enum HookLifecycleError { Event, Sample, Operator, + EventDestinations(String), /// The configured active package does not match the runtime file's /// `package.expectedDigest` pin. PackagePinMismatch(PackageDigestMismatch), @@ -193,8 +192,8 @@ pub(crate) fn sample( ); let envelope = HookEnvelope { id: SAMPLE_EVENT_ID.to_owned(), - event_type: event_type.clone(), - source: source.clone(), + event_type, + source, time: sample_time()?, subject, dataschema: delivery.data_schema.clone(), @@ -211,28 +210,11 @@ pub(crate) fn sample( String::from_utf8(canonical_body_bytes).map_err(|_| HookLifecycleError::Sample)?; let body = serde_json::to_value(&envelope).map_err(|_| HookLifecycleError::Sample)?; let headers = BTreeMap::from([ - ("Accept".to_owned(), "application/json".to_owned()), - ("Content-Type".to_owned(), "application/json".to_owned()), - ( - "Idempotency-Key".to_owned(), - SAMPLE_IDEMPOTENCY_KEY.to_owned(), - ), - ("X-Registry-Delivery-Attempt".to_owned(), "1".to_owned()), - ( - "X-Registry-Delivery-Time".to_owned(), - SAMPLE_TIME.to_owned(), - ), - ("X-Registry-Event-Generation".to_owned(), "1".to_owned()), - ( - "X-Registry-Signature".to_owned(), - SAMPLE_SIGNATURE.to_owned(), - ), - ("ce-dataschema".to_owned(), delivery.data_schema.clone()), - ("ce-id".to_owned(), SAMPLE_EVENT_ID.to_owned()), - ("ce-source".to_owned(), source), - ("ce-specversion".to_owned(), "1.0".to_owned()), - ("ce-time".to_owned(), SAMPLE_TIME.to_owned()), - ("ce-type".to_owned(), event_type), + ("accept".to_owned(), "application/json".to_owned()), + ("content-type".to_owned(), "application/json".to_owned()), + ("webhook-id".to_owned(), SAMPLE_EVENT_ID.to_owned()), + ("webhook-timestamp".to_owned(), "1767225600".to_owned()), + ("webhook-signature".to_owned(), SAMPLE_SIGNATURE.to_owned()), ]); Ok(HookSampleOutcome { event_id: delivery.event_id.clone(), @@ -388,13 +370,15 @@ fn discard_with( }) } -/// A package pin mismatch keeps both digests; every other operator failure -/// stays the one value-free refusal. +/// Keep package identities and actionable event destination refusals. fn operator_failure(error: HookOperatorError) -> HookLifecycleError { match error { HookOperatorError::PackagePinMismatch(mismatch) => { HookLifecycleError::PackagePinMismatch(mismatch) } + HookOperatorError::EventDestinations(error) => { + HookLifecycleError::EventDestinations(error.to_string()) + } HookOperatorError::Unavailable => HookLifecycleError::Operator, } } @@ -849,7 +833,7 @@ mod tests { #[test] fn sample_placeholders_never_claim_a_deployed_target_or_secret() { assert!(SAMPLE_REQUEST_TARGET.starts_with('<')); - assert_eq!(SAMPLE_SIGNATURE, "v1="); + assert_eq!(SAMPLE_SIGNATURE, "v1,"); assert!(!SAMPLE_SIGNATURE.contains("secret")); } diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 227251dd71..85868684d6 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -59,10 +59,12 @@ mod identity_facts; mod import_authority_lifecycle; mod init_from_model; mod instance_claim_lifecycle; +mod migration_draft; mod module_lock_patch; mod package_inspection; mod package_lifecycle; mod proposal_retention; +mod provision; mod reconcile_lifecycle; mod report; mod review_recovery; @@ -252,6 +254,15 @@ enum Command { /// Status reads as the migration role in one read-only transaction and takes no apply lock, /// so it answers while an apply runs. Status(StatusArgs), + /// Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file. + /// + /// The runtime file's two database URLs name both roles, the database and both passwords. + /// The administrator URL comes from a file or an environment variable, never from the command + /// line. The command grants the runtime role CONNECT on the database: apply grants the rest. + /// With --package, a package that needs PostGIS also gets its schema, extension and + /// bounding-box role, which CREATE EXTENSION postgis needs a superuser for, and both roles + /// get USAGE on the PostGIS schema. + Provision(ProvisionCommand), /// Inspect and operate native Record timers through bounded audited commands. Timer(timer_operator_lifecycle::TimerArgs), /// Verify configured startup dependencies without binding a listener. @@ -894,6 +905,16 @@ struct PlanArgs { expected_digest: Option, } +#[derive(Debug, Args)] +struct ProvisionCommand { + #[command(flatten)] + shared: registry_platform_provision::ProvisionArgs, + + /// Absolute target package directory; a package that needs PostGIS adds the PostGIS steps. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + package: Option, +} + #[derive(Debug, Args)] struct StatusArgs { /// Runtime configuration file. @@ -940,7 +961,7 @@ struct ProposalRetentionArgs { #[derive(Debug, Subcommand)] enum HookCommand { - /// Render one deterministic exact CloudEvents request with synthetic values. + /// Render one deterministic Standard Webhooks request with synthetic values. Sample(HookSampleArgs), /// List bounded value-free delivery metadata, including superseded bindings. List(HookListArgs), @@ -1573,6 +1594,19 @@ enum MigrationCommand { /// Assess a Registry pinned by a failed activation, and execute only the safe transition it names. Reconcile(MigrationReconcileArgs), + + /// Write the reviewed migration directory for a successor whose changes need no SQL. + /// + /// Covers every access or disclosure change against the baseline package. + /// Compatible-additive changes, such as an optional field, may sit beside + /// them and stay uncovered: the registry applies those through its own + /// additive plan. Any other change is refused. Measures the candidate on + /// the disposable database the runtime configuration names, and writes + /// descriptor.json and rehearsal.json + /// under /modules//migrations/. Pass as + /// --reviewed-migrations to test and package. Never overwrites an existing + /// migration. + Draft(MigrationDraftArgs), } #[derive(Debug, Subcommand)] @@ -1610,6 +1644,33 @@ struct MigrationReconcileArgs { execute: bool, } +#[derive(Debug, Args)] +struct MigrationDraftArgs { + /// Base Registry Engine project directory. + #[arg(value_name = "PROJECT")] + project: PathBuf, + + /// Absolute directory of the chain tip package the successor follows. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + baseline_package: PathBuf, + + /// Runtime configuration file of the disposable schema-test database. + #[arg(long, value_name = "ABSOLUTE_FILE")] + runtime_config: PathBuf, + + /// Absolute reviewed-migrations directory the draft is written under. + #[arg(long, value_name = "ABSOLUTE_DIRECTORY")] + output: PathBuf, + + /// Module the migration directory belongs to. + #[arg(long, value_name = "LOCAL_ID")] + module: String, + + /// Identifier of the migration, also its directory name. + #[arg(long, value_name = "LOCAL_ID")] + id: String, +} + #[derive(Debug, Args)] struct HistoryEraseArgs { /// Runtime configuration file. @@ -2165,6 +2226,21 @@ struct MigrationExplainSuccessReport { plan: MigrationInspectionSummary, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MigrationDraftSuccessReport { + ok: bool, + command: &'static str, + /// The migration directory, relative to --output. + directory: String, + change_class: registry_breg::package::CompiledRegistryChangeClass, + covers: Vec, + plan_digest: String, + prior_package_digest: String, + final_schema_fingerprint: String, + postgres_major: u16, +} + #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct MigrationReconcileSuccessReport { @@ -3069,6 +3145,7 @@ where Err(refusal) => write_refusal(&refusal, format, stdout, stderr), }; } + Command::Provision(args) => return provision(&args, format), Command::Status(args) => { return match status(&args) { Ok(report) => write_status_success(&report, format, stdout, stderr), @@ -3143,6 +3220,12 @@ where Err(failure) => write_failure(&failure, format, stdout, stderr), }; } + MigrationCommand::Draft(args) => { + return match migration_draft(&args) { + Ok(report) => write_migration_draft_success(&report, format, stdout, stderr), + Err(refusal) => write_refusal(&refusal, format, stdout, stderr), + }; + } }, Command::History(args) => match args.command { HistoryCommand::Erase(args) => { @@ -5370,6 +5453,13 @@ fn hook_lifecycle_failure(command: &'static str, error: HookLifecycleError) -> F DiagnosticArtifact::HookSample, SuggestedAction::SelectHookEvent, ), + HookLifecycleError::EventDestinations(ref reason) => ( + "hook.operation.refused", + "destinations.hooks", + reason.as_str(), + DiagnosticArtifact::HookOperations, + SuggestedAction::CorrectRuntimeConfiguration, + ), HookLifecycleError::Operator => ( "hook.operation.refused", "hook", @@ -6475,6 +6565,23 @@ fn apply(args: &ApplyArgs) -> Result { }) } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: &ProvisionCommand, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "bregctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args.shared, + shared, + |runtime_config| provision::load(runtime_config, args.package.as_deref()), + ) +} + fn plan(args: &PlanArgs) -> Result { let outcome = apply_lifecycle::plan(PlanLifecycleRequest { runtime_config: &args.runtime_config, @@ -6730,10 +6837,16 @@ fn schema_test_runtime_setup_failure( "destinations.hooks", "configure exactly the logical destination bindings required by the candidate event deliveries before retrying", ), - SchemaTestRuntimeSetupError::EventDestinations(_) => ( + SchemaTestRuntimeSetupError::EventDestinations(cause) => ( "test.hook-destinations.activation-failed", "destinations.hooks", - "check the destination bindings, delivery ceilings, and referenced secret, signing, and TLS material before retrying", + match cause { + EventDestinationActivationError::SigningKeyUnavailable { .. } + | EventDestinationActivationError::InvalidSigningKey { .. } + | EventDestinationActivationError::RepeatedSigningKey { .. } + | EventDestinationActivationError::PreviousEqualsCurrent { .. } => "", + _ => "check the destination bindings, delivery ceilings, and referenced secret, signing, and TLS material before retrying", + }, ), SchemaTestRuntimeSetupError::Evidence => ( "test.evidence-providers.activation-failed", @@ -6745,17 +6858,27 @@ fn schema_test_runtime_setup_failure( "reviewAuthorities", "bind every review authority the candidate's Proposal Actions name, and check the referenced credentials, before retrying", ), + SchemaTestRuntimeSetupError::ReviewAuthorityKey(_) => ( + "test.review-authorities.activation-failed", + "reviewAuthorities", + "", + ), SchemaTestRuntimeSetupError::WasmExecution => ( "test.wasm-execution.setup-failed", "wasmExecution", "check the WASM execution budgets and backend support before retrying", ), }; + let message = match (&error, recovery) { + (SchemaTestRuntimeSetupError::EventDestinations(cause), "") => cause.to_string(), + (SchemaTestRuntimeSetupError::ReviewAuthorityKey(_), "") => error.to_string(), + _ => format!("{error}; {recovery}"), + }; FailureReport { ok: false, command: "test", diagnostics: vec![tool_diagnostic( - diagnostic(code, path, &format!("{error}; {recovery}")), + diagnostic(code, path, &message), DiagnosticArtifact::RuntimeConfiguration, SuggestedAction::CorrectRuntimeConfiguration, )], @@ -7214,10 +7337,10 @@ fn lifecycle_failure(command: &'static str, error: ApplyLifecycleError) -> Failu DiagnosticArtifact::PackageActivation, SuggestedAction::VerifyMigrationAuthority, ), - ApplyLifecycleError::EventDestinations => ( + ApplyLifecycleError::EventDestinations(ref reason) => ( "apply.hook-destinations.refused", "destinations.hooks", - "the event destination bindings were refused", + reason.as_str(), DiagnosticArtifact::RuntimeConfiguration, SuggestedAction::CorrectRuntimeConfiguration, ), @@ -7826,6 +7949,28 @@ fn migration_explain( }) } +fn migration_draft(args: &MigrationDraftArgs) -> Result { + let drafted = migration_draft::run(&migration_draft::DraftRequest { + project: &args.project, + baseline_package: &args.baseline_package, + runtime_config: &args.runtime_config, + output: &args.output, + module: &args.module, + id: &args.id, + })?; + Ok(MigrationDraftSuccessReport { + ok: true, + command: migration_draft::COMMAND, + directory: drafted.directory, + change_class: registry_breg::package::CompiledRegistryChangeClass::AccessOrDisclosureChange, + covers: drafted.covers, + plan_digest: drafted.plan_digest, + prior_package_digest: drafted.prior_package_digest, + final_schema_fingerprint: drafted.final_schema_fingerprint, + postgres_major: drafted.postgres_major, + }) +} + fn migration_reconcile( args: &MigrationReconcileArgs, ) -> Result { @@ -8283,11 +8428,12 @@ fn runtime_config_diagnostics(error: &RuntimeConfigError) -> Vec { .diagnostics(None) .into_iter() .map(|reader| { - diagnostic( - &reader.code, - &reader.path, - &format!("{}; next: {}", reader.message, reader.suggested_action), - ) + let message = if matches!(error, RuntimeConfigError::InvalidDeliveryKey { .. }) { + format!("{} {}", reader.message, reader.suggested_action) + } else { + format!("{}; next: {}", reader.message, reader.suggested_action) + }; + diagnostic(&reader.code, &reader.path, &message) }) .collect() } @@ -14167,6 +14313,58 @@ fn write_migration_explain_success( } } +fn write_migration_draft_success( + report: &MigrationDraftSuccessReport, + format: OutputFormat, + stdout: &mut dyn Write, + stderr: &mut dyn Write, +) -> ExitCode { + let result = if format == OutputFormat::Json { + write_ctl_report(&mut *stdout, report) + .map_err(io::Error::other) + .and_then(|()| writeln!(stdout)) + } else { + write_migration_draft_human(report, stdout) + }; + write_result(result, stderr) +} + +fn write_migration_draft_human( + report: &MigrationDraftSuccessReport, + stdout: &mut dyn Write, +) -> io::Result<()> { + let mut lines = report::Lines::new(); + lines.lead(&format!( + "Drafted a reviewed migration covering {}.", + report::counted(report.covers.len(), "change") + )); + lines.pairs(&[ + ("directory", report.directory.clone()), + ("plan digest", report.plan_digest.clone()), + ("prior package digest", report.prior_package_digest.clone()), + ( + "final schema fingerprint", + report.final_schema_fingerprint.clone(), + ), + ("postgres major", report.postgres_major.to_string()), + ]); + for cover in &report.covers { + let target = [ + cover.target.record_type_id.as_deref(), + cover.target.member_id.as_deref(), + ] + .into_iter() + .flatten() + .collect::>() + .join("."); + lines.pairs(&[( + "covers", + format!("{} at {target}", change_code_name(cover.code)), + )]); + } + stdout.write_all(lines.finish().as_bytes()) +} + fn write_migration_reconcile_success( report: &MigrationReconcileSuccessReport, format: OutputFormat, @@ -17176,6 +17374,7 @@ mod tests { "apply", "plan", "status", + "provision", "timer", "doctor", "verify", diff --git a/crates/registry-bregctl/src/migration_draft.rs b/crates/registry-bregctl/src/migration_draft.rs new file mode 100644 index 0000000000..e19981cf38 --- /dev/null +++ b/crates/registry-bregctl/src/migration_draft.rs @@ -0,0 +1,614 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `bregctl migration draft`: write the reviewed migration directory for a +//! successor whose changes need no SQL. +//! +//! The descriptor covers exactly the changes that are not compatible-additive, +//! and the rehearsal receipt binds the predecessor package, the descriptor's +//! digest, and the fingerprint and PostgreSQL major the candidate measures on +//! the disposable database. The package validator still decides coverage and +//! evidence when the directory is passed as `--reviewed-migrations`. +//! +//! Every refusal that depends only on the arguments, the project, and the +//! baseline package happens before the runtime configuration is read or any +//! database is opened. + +use std::collections::BTreeSet; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use registry_breg::migration_plan::{ + covers_are_metadata_only, read_migration_descriptor, read_rehearsal_receipt, + MigrationRehearsalReceipt, ReviewedChangeCover, ReviewedMigrationDescriptor, + ReviewedMigrationRecovery, +}; +use registry_breg::package::{CompiledRegistryChange, CompiledRegistryChangeClass}; +use registry_platform_canonical_json::canonicalize_json; +use registry_platform_yaml::LocalId; +use sha2::{Digest, Sha256}; + +use crate::safe_path::{SafeDir, SafeEntry, SafePathError}; +use crate::{ + baseline_package_failure, candidate_failure, canonicalize_project_path, + capture_resolved_project_source, compile_captured_project, has_parent_component, + inspect_baseline_package, rendered_changes, test_lifecycle, DiagnosticArtifact, FailureReport, + PackageCandidateArgs, ProfileArg, Refusal, SuggestedAction, +}; + +pub(crate) const COMMAND: &str = "migration draft"; + +const DESCRIPTOR_FILE: &str = "descriptor.json"; +const RECEIPT_FILE: &str = "rehearsal.json"; +const LOCK_TIMEOUT_MILLISECONDS: u64 = 1_000; +const STATEMENT_TIMEOUT_MILLISECONDS: u64 = 60_000; + +pub(crate) struct DraftRequest<'a> { + pub project: &'a Path, + pub baseline_package: &'a Path, + pub runtime_config: &'a Path, + pub output: &'a Path, + pub module: &'a str, + pub id: &'a str, +} + +/// What was written, for the success report. +#[derive(Debug)] +pub(crate) struct Drafted { + pub directory: String, + pub covers: Vec, + pub plan_digest: String, + pub prior_package_digest: String, + pub final_schema_fingerprint: String, + pub postgres_major: u16, +} + +/// Why the changes cannot be drafted. +#[derive(Debug, Eq, PartialEq)] +enum CoverRefusal { + NothingToReview, + Unsupported(String), + SqlRequired(String), +} + +/// The two documents of one drafted migration, as canonical JSON. +#[derive(Debug)] +struct Documents { + descriptor: Vec, + receipt: Vec, + plan_digest: String, +} + +struct Measured<'a> { + prior_package_digest: &'a str, + prior_schema_fingerprint: &'a str, + final_schema_fingerprint: &'a str, + postgres_major: u16, +} + +pub(crate) fn run(request: &DraftRequest<'_>) -> Result { + let (module, id) = checked_identifiers(request)?; + let output = preflight_output(request.output, &module, &id)?; + let selected_project = canonicalize_project_path(request.project).map_err(|diagnostic| { + crate::source_failure( + COMMAND, + diagnostic, + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + })?; + let source = capture_resolved_project_source(&selected_project).map_err(|diagnostic| { + crate::source_failure( + COMMAND, + diagnostic, + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + })?; + let compiled = compile_captured_project(&source, ProfileArg::Production, COMMAND)?; + if !source + .modules + .iter() + .any(|captured| captured.id.as_str() == module) + { + return Err(candidate_failure( + COMMAND, + "migration.draft.module-unknown", + "module", + &format!("the project has no module `{module}`; name one of its modules with --module"), + DiagnosticArtifact::CommandArguments, + SuggestedAction::CorrectCommandUsage, + ) + .into()); + } + let baseline = inspect_baseline_package(request.baseline_package) + .map_err(|error| baseline_package_failure(COMMAND, error))?; + if baseline.package_id() != compiled.registry_id() { + return Err(candidate_failure( + COMMAND, + "package.baseline.identity", + "baselinePackage", + "the baseline package belongs to another registry; name this registry's chain tip package directory with --baseline-package", + DiagnosticArtifact::VerifiedPackage, + SuggestedAction::CorrectPackageBuild, + ) + .into()); + } + let changes = registry_breg::package::compiled_registry_change_set_from_baseline( + baseline.migration_baseline(), + &compiled, + baseline.package_digest(), + ); + let covers = plan_covers(&changes.changes).map_err(|refusal| cover_failure(&refusal))?; + + // A fresh install of the same project measures the fingerprint and + // PostgreSQL major the receipt records, the way `test --fingerprint-only` + // does. + let candidate = crate::capture_candidate( + &PackageCandidateArgs { + project: request.project.to_path_buf(), + baseline_package: None, + reviewed_migrations: None, + }, + COMMAND, + false, + false, + )?; + if candidate.registry().revision() != compiled.revision() { + return Err(candidate_failure( + COMMAND, + "migration.draft.project-changed", + "project", + "the project changed while the draft was being prepared; run the command again", + DiagnosticArtifact::RegistryProject, + SuggestedAction::CorrectAuthoringSource, + ) + .into()); + } + let measurement = + test_lifecycle::measure(candidate, request.runtime_config).map_err(|error| { + let mut failure = crate::test_lifecycle_failure(error); + failure.command = COMMAND; + failure + })?; + + let documents = build_documents( + &module, + &id, + &covers, + &Measured { + prior_package_digest: baseline.package_digest(), + prior_schema_fingerprint: baseline.schema_fingerprint(), + final_schema_fingerprint: &measurement.schema_fingerprint, + postgres_major: measurement.postgres_major, + }, + ) + .map_err(|message| { + candidate_failure( + COMMAND, + "migration.draft.document-refused", + "output", + &message, + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::CorrectPackageBuild, + ) + })?; + publish(&output, &module, &id, &documents)?; + Ok(Drafted { + directory: relative_directory(&module, &id), + covers, + plan_digest: documents.plan_digest, + prior_package_digest: baseline.package_digest().to_owned(), + final_schema_fingerprint: measurement.schema_fingerprint, + postgres_major: measurement.postgres_major, + }) +} + +fn relative_directory(module: &str, id: &str) -> String { + format!("modules/{module}/migrations/{id}") +} + +fn checked_identifiers(request: &DraftRequest<'_>) -> Result<(String, String), FailureReport> { + let local_id = |value: &str, path: &str, flag: &str| { + LocalId::new(value).map(LocalId::into_string).map_err(|_| { + candidate_failure( + COMMAND, + "migration.draft.id-invalid", + path, + &format!( + "{flag} must be a local identifier: lowercase letters, digits, `-` and `_`, starting with a letter, at most 64 characters" + ), + DiagnosticArtifact::CommandArguments, + SuggestedAction::CorrectCommandUsage, + ) + }) + }; + Ok(( + local_id(request.module, "module", "--module")?, + local_id(request.id, "id", "--id")?, + )) +} + +/// The changes the descriptor covers, or the reason they cannot be drafted. +/// A draft has no steps, no assertions, and no backup binding, so it can only +/// review access and disclosure changes that alter no table, column, or +/// index. Compatible-additive changes may sit beside them: BReg applies those +/// through its own additive plan, so a reviewed migration never covers them. +fn plan_covers( + changes: &[CompiledRegistryChange], +) -> Result, CoverRefusal> { + let describe = + |change: &CompiledRegistryChange| rendered_changes(std::slice::from_ref(change), |_| true); + if let Some(change) = changes + .iter() + .find(|change| change.class == CompiledRegistryChangeClass::Unsupported) + { + return Err(CoverRefusal::Unsupported(describe(change))); + } + let reviewable = changes + .iter() + .filter(|change| change.class != CompiledRegistryChangeClass::CompatibleAdditive) + .collect::>(); + if reviewable.is_empty() { + return Err(CoverRefusal::NothingToReview); + } + for change in &reviewable { + let needs_more = change.class != CompiledRegistryChangeClass::AccessOrDisclosureChange + || !covers_are_metadata_only(&[ReviewedChangeCover::from(*change)]); + if needs_more { + return Err(CoverRefusal::SqlRequired(describe(change))); + } + } + Ok(reviewable + .into_iter() + .map(ReviewedChangeCover::from) + .collect::>() + .into_iter() + .collect()) +} + +fn cover_failure(refusal: &CoverRefusal) -> FailureReport { + match refusal { + CoverRefusal::NothingToReview => candidate_failure( + COMMAND, + "migration.draft.nothing-to-review", + "candidate", + "every change against the baseline is compatible-additive, so no reviewed migration is needed; run test and package without --reviewed-migrations", + DiagnosticArtifact::CompiledDiff, + SuggestedAction::ReviewCompiledDiff, + ), + CoverRefusal::Unsupported(change) => candidate_failure( + COMMAND, + "migration.change.unsupported", + "candidate", + &format!( + "the migration planner does not support this successor change: {change}. Inspect diff and revise the candidate. Reviewed artifacts cannot authorize unsupported changes" + ), + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::CorrectPackageBuild, + ), + CoverRefusal::SqlRequired(change) => candidate_failure( + COMMAND, + "migration.draft.sql-required", + "candidate", + &format!( + "this change needs a migration written by hand, with authored SQL, a backup binding, or a descriptor of its own class: {change}. A draft only covers access and disclosure changes that alter no table, column, or index, beside any compatible-additive changes" + ), + DiagnosticArtifact::DatabaseMigration, + SuggestedAction::ReviewCompiledDiff, + ), + } +} + +fn build_documents( + module: &str, + id: &str, + covers: &[ReviewedChangeCover], + measured: &Measured<'_>, +) -> Result { + let directory = relative_directory(module, id); + let descriptor = ReviewedMigrationDescriptor { + id: id.to_owned(), + change_class: CompiledRegistryChangeClass::AccessOrDisclosureChange, + covers: covers.to_vec(), + recovery: ReviewedMigrationRecovery::ExactTargetResume, + lock_timeout_ms: LOCK_TIMEOUT_MILLISECONDS, + statement_timeout_ms: STATEMENT_TIMEOUT_MILLISECONDS, + steps: Vec::new(), + pre_assertions: Vec::new(), + post_assertions: Vec::new(), + rehearsal_receipt_path: format!("{directory}/{RECEIPT_FILE}"), + backup_binding_path: None, + history: None, + }; + let descriptor_bytes = canonical_bytes(&descriptor)?; + let plan_digest = sha256_digest(&descriptor_bytes); + let receipt = MigrationRehearsalReceipt { + prior_package_digest: measured.prior_package_digest.to_owned(), + prior_schema_fingerprint: measured.prior_schema_fingerprint.to_owned(), + plan_sha256: plan_digest.clone(), + sql_sha256: Vec::new(), + assertion_sha256: Vec::new(), + fixture_inventory: Vec::new(), + postgres_major: measured.postgres_major, + row_assertions: Vec::new(), + final_schema_fingerprint: measured.final_schema_fingerprint.to_owned(), + }; + let receipt_bytes = canonical_bytes(&receipt)?; + // The drafted files are read back through the readers the package + // validator uses, so a draft that would be refused is never written. + read_migration_descriptor(&format!("{directory}/{DESCRIPTOR_FILE}"), &descriptor_bytes) + .map_err(|_| "the drafted descriptor was refused by the descriptor reader".to_owned())?; + read_rehearsal_receipt(&format!("{directory}/{RECEIPT_FILE}"), &receipt_bytes) + .map_err(|_| "the drafted receipt was refused by the receipt reader".to_owned())?; + Ok(Documents { + descriptor: descriptor_bytes, + receipt: receipt_bytes, + plan_digest, + }) +} + +fn canonical_bytes(document: &impl serde::Serialize) -> Result, String> { + let value = serde_json::to_value(document) + .map_err(|_| "the drafted document does not serialize".to_owned())?; + canonicalize_json(&value).map_err(|_| "the drafted document does not canonicalize".to_owned()) +} + +fn sha256_digest(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + let mut text = String::with_capacity(71); + text.push_str("sha256:"); + for byte in digest { + text.push_str(&format!("{byte:02x}")); + } + text +} + +/// The migration directory's path under `output`, checked before anything is +/// measured: an unsafe or relative output, or an existing migration of the +/// same id, is refused with nothing written. +fn preflight_output(output: &Path, module: &str, id: &str) -> Result { + let invalid = |detail: &str| { + candidate_failure( + COMMAND, + "migration.draft.output-invalid", + "output", + &format!( + "--output must be an absolute directory path without parent traversal or symbolic links: {detail}" + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ) + }; + if !output.is_absolute() || has_parent_component(output) { + return Err(invalid("the path is relative or traverses a parent")); + } + let exists = candidate_failure( + COMMAND, + "migration.draft.output-exists", + "output", + &format!( + "{} already exists under --output; a draft never overwrites a reviewed migration. Choose another --id or review the existing directory", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ); + let mut directory = match SafeDir::resolve(output) { + Ok(directory) => directory, + // Nothing exists yet, so nothing can collide. Publication creates the + // missing directories. + Err(SafePathError::NotFound) => return Ok(output.to_path_buf()), + Err(_) => return Err(invalid("the path cannot be resolved safely")), + }; + for name in ["modules", module, "migrations"] { + match directory.open_directory(name.as_ref()) { + Ok(next) => directory = next, + Err(SafePathError::NotFound) => return Ok(output.to_path_buf()), + Err(_) => return Err(invalid("a component is not a plain directory")), + } + } + match directory.entry_exists(id.as_ref()) { + Ok(true) => Err(exists), + Ok(false) => Ok(output.to_path_buf()), + Err(_) => Err(invalid("the migration directory cannot be inspected")), + } +} + +/// Create `modules//migrations/` under `output` and write both +/// documents into it. The final directory is created exclusively, so a +/// concurrent draft of the same id is refused rather than overwritten. +fn publish( + output: &Path, + module: &str, + id: &str, + documents: &Documents, +) -> Result<(), FailureReport> { + let unwritable = |detail: &str| { + candidate_failure( + COMMAND, + "migration.draft.output-unavailable", + "output", + &format!( + "the drafted migration could not be written ({detail}). Remove {} if it was partly written, then run the command again", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + ) + }; + let entry = SafeEntry::resolve(output).map_err(|_| unwritable("the output path"))?; + let mut directory = entry + .parent() + .open_or_create_directory(entry.name(), 0o777) + .map_err(|_| unwritable("the output directory"))?; + for name in ["modules", module, "migrations"] { + directory = directory + .open_or_create_directory(name.as_ref(), 0o777) + .map_err(|_| unwritable("a parent directory"))?; + } + match directory.create_directory(id.as_ref(), 0o777) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + return Err(candidate_failure( + COMMAND, + "migration.draft.output-exists", + "output", + &format!( + "{} already exists under --output; a draft never overwrites a reviewed migration", + relative_directory(module, id) + ), + DiagnosticArtifact::SchemaTestOutput, + SuggestedAction::ChooseSafeOutputDirectory, + )); + } + Err(_) => return Err(unwritable("the migration directory")), + } + let migration = directory + .open_directory(id.as_ref()) + .map_err(|_| unwritable("the migration directory"))?; + for (name, bytes) in [ + (DESCRIPTOR_FILE, &documents.descriptor), + (RECEIPT_FILE, &documents.receipt), + ] { + let mut file = migration + .create_new(name.as_ref(), 0o666) + .map_err(|_| unwritable(name))?; + file.write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|_| unwritable(name))?; + } + migration.sync().map_err(|_| unwritable("the directory")) +} + +#[cfg(test)] +mod tests { + use super::*; + use registry_breg::package::{ + CompiledRegistryChangeCode, CompiledRegistryChangeTarget, CompiledRegistryChangeTargetKind, + }; + + const PRIOR_DIGEST: &str = + "sha256:1111111111111111111111111111111111111111111111111111111111111111"; + const PRIOR_FINGERPRINT: &str = + "sha256:2222222222222222222222222222222222222222222222222222222222222222"; + const FINAL_FINGERPRINT: &str = + "sha256:3333333333333333333333333333333333333333333333333333333333333333"; + + fn change( + class: CompiledRegistryChangeClass, + code: CompiledRegistryChangeCode, + member: &str, + ) -> CompiledRegistryChange { + CompiledRegistryChange { + class, + code, + target: CompiledRegistryChangeTarget { + kind: CompiledRegistryChangeTargetKind::RecordType, + record_type_id: Some("record".to_owned()), + member_id: Some(member.to_owned()), + }, + } + } + + fn access_change(member: &str) -> CompiledRegistryChange { + change( + CompiledRegistryChangeClass::AccessOrDisclosureChange, + CompiledRegistryChangeCode::AccessProfileChanged, + member, + ) + } + + fn measured() -> Measured<'static> { + Measured { + prior_package_digest: PRIOR_DIGEST, + prior_schema_fingerprint: PRIOR_FINGERPRINT, + final_schema_fingerprint: FINAL_FINGERPRINT, + postgres_major: 17, + } + } + + #[test] + fn covers_are_the_sorted_access_changes_and_skip_compatible_additive_ones() { + let additive = change( + CompiledRegistryChangeClass::CompatibleAdditive, + CompiledRegistryChangeCode::FieldAddedOptional, + "extra", + ); + let covers = plan_covers(&[access_change("zeta"), additive, access_change("alpha")]) + .expect("access changes are draftable"); + let members = covers + .iter() + .map(|cover| cover.target.member_id.as_deref().expect("member")) + .collect::>(); + assert_eq!(members, ["alpha", "zeta"]); + } + + #[test] + fn a_change_set_without_reviewable_changes_has_nothing_to_review() { + let additive = change( + CompiledRegistryChangeClass::CompatibleAdditive, + CompiledRegistryChangeCode::FieldAddedOptional, + "extra", + ); + assert_eq!(plan_covers(&[additive]), Err(CoverRefusal::NothingToReview)); + assert_eq!(plan_covers(&[]), Err(CoverRefusal::NothingToReview)); + } + + #[test] + fn a_change_outside_the_access_class_needs_a_handwritten_migration() { + let removed = change( + CompiledRegistryChangeClass::DestructiveOrIrreversible, + CompiledRegistryChangeCode::FieldRemoved, + "code", + ); + let Err(CoverRefusal::SqlRequired(named)) = plan_covers(&[access_change("alpha"), removed]) + else { + panic!("a removed field needs a hand-written migration"); + }; + assert!(named.contains("field-removed"), "{named}"); + } + + #[test] + fn descriptor_bytes_are_canonical_and_the_receipt_binds_their_digest() { + let covers = plan_covers(&[access_change("alpha")]).expect("draftable"); + let documents = + build_documents("core", "widen", &covers, &measured()).expect("documents build"); + + let descriptor: serde_json::Value = + serde_json::from_slice(&documents.descriptor).expect("descriptor is JSON"); + assert_eq!( + canonicalize_json(&descriptor).expect("canonicalizes"), + documents.descriptor, + "the descriptor file is its own canonical form" + ); + assert_eq!(documents.plan_digest, sha256_digest(&documents.descriptor)); + assert_eq!(descriptor["changeClass"], "access-or-disclosure-change"); + assert_eq!(descriptor["steps"], serde_json::json!([])); + assert_eq!(descriptor["preAssertions"], serde_json::json!([])); + assert_eq!(descriptor["postAssertions"], serde_json::json!([])); + assert_eq!( + descriptor["rehearsalReceiptPath"], + "modules/core/migrations/widen/rehearsal.json" + ); + + let receipt: serde_json::Value = + serde_json::from_slice(&documents.receipt).expect("receipt is JSON"); + assert_eq!(receipt["planDigest"], documents.plan_digest.as_str()); + assert_eq!(receipt["priorPackageDigest"], PRIOR_DIGEST); + assert_eq!(receipt["priorSchemaFingerprint"], PRIOR_FINGERPRINT); + assert_eq!(receipt["finalSchemaFingerprint"], FINAL_FINGERPRINT); + assert_eq!(receipt["postgresMajor"], 17); + assert_eq!( + canonicalize_json(&receipt).expect("canonicalizes"), + documents.receipt + ); + } + + #[test] + fn a_draft_is_deterministic() { + let covers = plan_covers(&[access_change("alpha")]).expect("draftable"); + let first = build_documents("core", "widen", &covers, &measured()).expect("first builds"); + let second = build_documents("core", "widen", &covers, &measured()).expect("second builds"); + assert_eq!(first.descriptor, second.descriptor); + assert_eq!(first.receipt, second.receipt); + } +} diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs new file mode 100644 index 0000000000..ad7783ffde --- /dev/null +++ b/crates/registry-bregctl/src/provision.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision`: the shared command over the Registry runtime file. +//! The file's two database URLs name the roles, the database and both +//! passwords, so nothing is written twice. With `--package` the command also +//! plans the PostGIS steps a spatial package needs. + +use std::path::Path; + +use registry_breg::generated_ddl::POSTGIS_EXTENSION_SCHEMA; +use registry_breg::package::load_package; +use registry_breg::postgres::{ + spatial_bbox_role, MANAGED_SCHEMAS, MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR, +}; +use registry_breg::runtime_config::{ + load_runtime_config, RuntimeConfig, RuntimeConfigError, RUNTIME_CONFIG_KIND, +}; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout, Spatial}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(RUNTIME_CONFIG_KIND.to_owned()); + Box::new(diagnostic) +} + +fn runtime_file_refused(file: &Path, error: &RuntimeConfigError) -> Box { + match error.diagnostics(Some(file)).into_iter().next() { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } +} + +/// The database a package needs from the server beyond the managed schemas: +/// PostGIS and the bounding-box role when the package stores polygons or +/// answers bounding-box queries. The role is named after the runtime role, as +/// the Registry runtime and `rstack dev` name it. +fn spatial(config: &RuntimeConfig, package: &Path) -> Result, Box> { + let verified = load_package(package, &config.package_load_context()).map_err(|error| { + refused( + "config.refused", + "arguments", + format!("the --package directory could not be loaded: {error}"), + "Pass --package as a package that bregctl package built, or run provision without it.", + ) + })?; + Ok(verified.registry().ddl().requires_postgis.then(|| Spatial { + schema: POSTGIS_EXTENSION_SCHEMA.to_owned(), + bbox_role: spatial_bbox_role(config.database().roles().runtime()) + .as_str() + .to_owned(), + minimum_postgis: (MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR), + })) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path, package: Option<&Path>) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = + load_runtime_config(&absolute).map_err(|error| runtime_file_refused(&absolute, &error))?; + // The same checks `apply` makes: each URL parses and logs in as the role + // the file names for it. + config + .migration_database_connection_config() + .and_then(|_| config.runtime_database_connection_config()) + .map_err(|error| runtime_file_refused(&absolute, &error))?; + let secrets = config + .secret_resolver() + .map_err(|error| runtime_file_refused(&absolute, &error))?; + let resolve = |member: &str, reference| { + secrets.resolve_reference(reference).map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} could not be read from its secret provider"), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let database = config.database(); + let migration_url = url("migrationUrlRef", database.migration_url_ref())?; + let runtime_url = url("runtimeUrlRef", database.runtime_url_ref())?; + let ca_pem = database + .ca_bundle_ref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + let spatial = package + .map(|package| spatial(&config, package)) + .transpose()? + .flatten(); + Ok(ProvisionInput { + product: ProductDatabase { + product: "breg", + layout: SchemaLayout::Owned(MANAGED_SCHEMAS.iter().map(|s| (*s).to_owned()).collect()), + btree_gist: true, + spatial, + }, + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-bregctl/src/reviewed_migrations.rs b/crates/registry-bregctl/src/reviewed_migrations.rs index a5496dfd02..07908e73d7 100644 --- a/crates/registry-bregctl/src/reviewed_migrations.rs +++ b/crates/registry-bregctl/src/reviewed_migrations.rs @@ -137,7 +137,7 @@ pub(crate) fn capture(root: &Path) -> Result { }); } let declared_schema_fingerprint = declared_schema_fingerprint.ok_or_else(|| - refusal("migration.review.receipt", "reviewedMigrations", "provide the referenced rehearsal.json; the CLI does not manufacture migration evidence"))?; + refusal("migration.review.receipt", "reviewedMigrations", "provide the referenced rehearsal.json; the CLI does not manufacture migration evidence for a migration with SQL. For a change that needs no SQL, `bregctl migration draft` writes the descriptor and its measured rehearsal receipt"))?; // Grouped by the bare directory, which can disagree with descriptor-path // order when one directory name is a strict prefix of another (`m0002` // and `m0002-funding-source`): `prepare_reviewed_migration_plan` requires @@ -355,4 +355,25 @@ mod ordering_tests { the key prepare_reviewed_migration_plan checks" ); } + + #[test] + fn a_missing_receipt_names_the_draft_command_for_changes_without_sql() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + let dir = root.join("modules/core/migrations/m0001"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("descriptor.json"), minimal_descriptor("m0001")).unwrap(); + + let CaptureRefusal::Tool(refused) = + capture(&root).expect_err("a descriptor without its receipt is refused") + else { + panic!("a missing receipt is the command's own diagnostic"); + }; + assert_eq!(refused.code, "migration.review.receipt"); + assert!( + refused.message.contains("bregctl migration draft"), + "{}", + refused.message + ); + } } diff --git a/crates/registry-bregctl/src/test_lifecycle.rs b/crates/registry-bregctl/src/test_lifecycle.rs index 8b19d5136a..40dfb1a673 100644 --- a/crates/registry-bregctl/src/test_lifecycle.rs +++ b/crates/registry-bregctl/src/test_lifecycle.rs @@ -75,6 +75,7 @@ pub(crate) struct TestLifecycleOutcome { pub(crate) struct SchemaMeasurement { pub registry_revision: String, pub schema_fingerprint: String, + pub postgres_major: u16, } /// The receipt destination, held as its resolved parent descriptor plus the @@ -341,11 +342,12 @@ pub(crate) fn measure( .enable_all() .build() .map_err(|_| TestLifecycleError::Runtime)?; - let schema_fingerprint = runtime.block_on(async { - startup::rehearse_schema_fingerprint(&config, candidate.registry()) + let installed = runtime.block_on(async { + startup::measure_schema_install(&config, candidate.registry()) .await .map_err(schema_preparation_error) })?; + let schema_fingerprint = installed.fingerprint; let prepared = candidate .prepare(schema_fingerprint.clone()) .map_err(|error| TestLifecycleError::Candidate { @@ -355,6 +357,7 @@ pub(crate) fn measure( Ok(SchemaMeasurement { registry_revision: prepared.registry().revision().to_owned(), schema_fingerprint, + postgres_major: installed.postgres_major, }) } @@ -1127,6 +1130,18 @@ bindings: ); } + #[test] + fn schema_test_destination_inventory_refusal_names_the_recovery() { + use registry_breg::event_destination::EventDestinationActivationError; + + let error = SchemaTestRuntimeSetupError::EventDestinations( + EventDestinationActivationError::InventoryMismatch, + ); + let report = + crate::test_lifecycle_failure(execution_error(FixtureError::RuntimeSetup(error))); + assert_eq!(report.diagnostics[0].message, "schema-test event destination activation requires an exact compiled binding set; configure exactly the logical destination bindings required by the candidate event deliveries before retrying"); + } + #[test] fn runtime_setup_failures_report_the_configuration_boundary_without_database_advice() { use registry_breg::event_destination::EventDestinationActivationError; @@ -1174,8 +1189,11 @@ bindings: EventDestinationActivationError::InvalidBinding, EventDestinationActivationError::DeliveryCeilingWidening, EventDestinationActivationError::Secret, - EventDestinationActivationError::InvalidSigningMaterial, EventDestinationActivationError::InvalidTlsMaterial, + EventDestinationActivationError::RepeatedSigningKey { + first: "destinations.hooks.receiver.hmacSha256KeyRef".to_owned(), + second: "reviewAuthorities.casework.completion.hmacSha256KeyRef".to_owned(), + }, ] { cases.push(( SchemaTestRuntimeSetupError::EventDestinations(error), @@ -1184,6 +1202,12 @@ bindings: )); } for (error, code, path) in cases { + let activation_message = match &error { + SchemaTestRuntimeSetupError::EventDestinations( + cause @ EventDestinationActivationError::RepeatedSigningKey { .. }, + ) => Some(cause.to_string()), + _ => None, + }; let report = crate::test_lifecycle_failure(execution_error(FixtureError::RuntimeSetup(error))); let diagnostic = &report.diagnostics[0]; @@ -1198,7 +1222,11 @@ bindings: crate::SuggestedAction::CorrectRuntimeConfiguration ); assert!(!diagnostic.message.contains("recreate")); - assert!(diagnostic.message.contains("before retrying")); + if let Some(activation_message) = activation_message { + assert_eq!(diagnostic.message, activation_message); + } else { + assert!(diagnostic.message.contains("before retrying")); + } let serialized = serde_json::to_string(&report).expect("failure report serializes"); assert!(!serialized.contains("recreate_disposable_database")); } diff --git a/crates/registry-bregctl/tests/cli.rs b/crates/registry-bregctl/tests/cli.rs index 729f89caea..5ad8d35364 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -2883,7 +2883,18 @@ fn facility_starter_checks_clean_with_warnings_denied() { .unwrap() .iter() .any(|operation| operation == "get")); - assert_eq!(operator["rowBoundaries"].as_array().unwrap().len(), 1); + // The template writes the boundary once, as a set, and the grant refers to it. + assert_eq!( + operator["rowBoundaries"], + json!({"rowBoundarySet": "same-jurisdiction"}) + ); + assert_eq!( + registry["rowBoundarySets"]["same-jurisdiction"] + .as_array() + .unwrap() + .len(), + 1 + ); let checked = bregctl(&[ "--format", @@ -9138,6 +9149,85 @@ fn bregctl_schema_test_with_unreachable_database(arguments: &[&str]) -> Output { .expect("bregctl starts") } +#[test] +fn apply_plan_and_hook_drain_refuse_a_key_shared_with_completion() { + use std::os::unix::fs::PermissionsExt as _; + + let mut module: Value = serde_json::from_slice(&package_module_bytes()).unwrap(); + module["recordTypes"]["record"]["hooks"] = json!([{ + "id": "record-created", + "phase": "after", + "trigger": "created", + "projection": ["code"], + "handler": {"type":"url", "destinationId":"receiver"} + }]); + let fixture = RuntimePackageFixture::production_with_module( + "127.0.0.1:1".parse().unwrap(), + canonicalize_json(&module).unwrap(), + ); + let key = [ + uuid::Uuid::new_v4().as_bytes().as_slice(), + uuid::Uuid::new_v4().as_bytes(), + ] + .concat(); + for (name, bytes) in [ + ("hook-key", key.as_slice()), + ("completion-key", key.as_slice()), + ("review-token", b"synthetic-review-token".as_slice()), + ] { + let path = fixture.directory.path().join("secrets").join(name); + fs::write(&path, bytes).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); + } + let raw = fs::read_to_string(&fixture.runtime_config).unwrap(); + fs::write( + &fixture.runtime_config, + format!( + "{raw}{}", + r#"destinations: + hooks: + receiver: + origin: https://receiver.example/ + path: /events + networkProfile: production-https + dnsFamily: ipv4-only + allowedPrivateCidrs: [] + hmacSha256KeyRef: secret:file/hook-key + classificationCeiling: internal + deliveryCeilings: + attemptTimeoutMilliseconds: 1000 + maximumAttempts: 1 +reviewAuthorities: + casework: + endpoint: https://casework.example/ + profile: producer + producerId: registry-producer + recoveryDays: 7 + tokenRef: secret:file/review-token + completion: + recipientBinding: registry + hmacSha256KeyRef: secret:file/completion-key +"# + ), + ) + .unwrap(); + + for command in [ + vec!["hook", "drain"], + vec!["plan", "--package", path(&fixture.package)], + vec!["apply", "--initial", "--package", path(&fixture.package)], + ] { + let arguments = ["--format", "json"] + .into_iter() + .chain(command) + .chain(["--runtime-config", path(&fixture.runtime_config)]) + .collect::>(); + let output = bregctl_with_unreachable_database(&arguments); + let report = json_stdout(&output); + assert_eq!(report["diagnostics"][0]["message"], "destinations.hooks.receiver.hmacSha256KeyRef and reviewAuthorities.casework.completion.hmacSha256KeyRef resolve to the same key bytes. Give reviewAuthorities.casework.completion.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there."); + } +} + #[test] fn apply_and_plan_refuse_a_package_other_than_the_expected_digest_before_database_contact() { let fixture = RuntimePackageFixture::production("127.0.0.1:1".parse().unwrap()); diff --git a/crates/registry-bregctl/tests/cli/file_check.rs b/crates/registry-bregctl/tests/cli/file_check.rs index a7214cee8e..c5a3b44d47 100644 --- a/crates/registry-bregctl/tests/cli/file_check.rs +++ b/crates/registry-bregctl/tests/cli/file_check.rs @@ -421,8 +421,9 @@ reviewAuthorities: producerId: registry-producer recoveryDays: 7 client: facility-operator - completionTokenRef: secret:file/completion-token - completionRecipient: registry-breg + completion: + hmacSha256KeyRef: secret:file/completion-key + recipientBinding: registry-breg ", scratch.path().join("no-secrets-here").display() ); @@ -437,14 +438,14 @@ reviewAuthorities: for (planted, code) in [ ( clients.replace( - "secret:file/completion-token", + "secret:file/completion-key", &format!("secret:vault/{MARKER}"), ), "config.invalid-value", ), ( clients.replace( - "secret:file/completion-token", + "secret:file/completion-key", &format!("secret:env/{}", MARKER.replace('-', "_")), ), "breg.dev-clients.refused", diff --git a/crates/registry-bregctl/tests/dev_lifecycle.rs b/crates/registry-bregctl/tests/dev_lifecycle.rs index b30d875399..cf35f3ce0d 100644 --- a/crates/registry-bregctl/tests/dev_lifecycle.rs +++ b/crates/registry-bregctl/tests/dev_lifecycle.rs @@ -665,8 +665,7 @@ seed: ); assert_eq!(receipt["destinationId"], destination); assert_eq!(receipt["status"], "received"); - assert!(receipt["generation"].as_u64().unwrap() > 0); - assert_eq!(receipt["attempt"], 1); + assert_eq!(receipt["webhookId"], receipt["eventId"]); } let payloads = session.success(&[ "dev", @@ -772,11 +771,7 @@ seed: && receipt["deliveryId"] == delivery["deliveryId"] }) .expect("replay has an authenticated receipt for the same event"); - assert_eq!( - receipt["generation"].as_u64().unwrap(), - delivery["generation"].as_u64().unwrap() + 1 - ); - assert_eq!(receipt["attempt"], 1); + assert_eq!(receipt["webhookId"], delivery["eventId"]); assert_eq!(receipt["status"], "received"); } // The operator queue also omits leased attempts. Check the durable terminal @@ -786,7 +781,7 @@ seed: report["deliveries"].as_array().unwrap().is_empty() }); let receipts_before = fs::read(&inbox).unwrap(); - let webhook_key = fs::read(dev.join("secrets/webhook-key")).unwrap(); + let webhook_key = fs::read(dev.join("secrets/inbox-key-receiver-a")).unwrap(); let assertion_key = fs::read(dev.join("credentials/operator/assertion-key.jwk")).unwrap(); session.stop(); assert!(std::net::TcpStream::connect(receiver_address).is_err()); @@ -798,7 +793,7 @@ seed: assert_eq!(retained[field], state[field]); } assert!(std::net::TcpStream::connect(receiver_address).is_ok()); - assert!(fs::read(dev.join("secrets/webhook-key")).unwrap() == webhook_key); + assert!(fs::read(dev.join("secrets/inbox-key-receiver-a")).unwrap() == webhook_key); assert!(fs::read(dev.join("credentials/operator/assertion-key.jwk")).unwrap() == assertion_key); assert_eq!(fs::read(&inbox).unwrap(), receipts_before); assert_eq!(events(), recovered); @@ -1819,7 +1814,11 @@ fn installed_dev_prepares_a_native_source_successor_with_retained_records() { let binary = Path::new(env!("CARGO_BIN_EXE_bregctl")); let temporary = tempfile::Builder::new() .prefix("breg-native-source-test-") - .tempdir_in(binary.parent().unwrap()) + .tempdir_in(if cfg!(target_os = "linux") { + std::env::temp_dir() + } else { + binary.parent().unwrap().to_owned() + }) .unwrap(); fs::set_permissions(temporary.path(), fs::Permissions::from_mode(0o700)).unwrap(); let parent = fs::canonicalize(temporary.keep()).unwrap(); @@ -1830,6 +1829,16 @@ fn installed_dev_prepares_a_native_source_successor_with_retained_records() { docker: installed("docker"), }; operator_project(&session); + let registry_path = project.join("registry.yaml"); + let mut source: Value = serde_norway::from_slice(&fs::read(®istry_path).unwrap()).unwrap(); + source["recordTypes"]["record"]["hooks"] = json!([ + {"phase":"after","id":"record-created", "trigger":"created", "projection":["status"], + "handler":{"type":"url","destinationId":"receiver"}} + ]); + write( + ®istry_path, + serde_norway::to_string(&source).unwrap().as_bytes(), + ); let client_file = project.join("dev-clients.yaml"); let mut clients = fs::read(&client_file).unwrap(); clients.extend_from_slice( @@ -1949,6 +1958,19 @@ seed: assert_eq!(found["data"]["domainData"]["status"], "active"); }); session.stop(); + let key = project.join(".breg/dev/secrets/inbox-key-receiver"); + fs::remove_file(&key).unwrap(); + let refusal = session.dev(&[]); + assert!(!refusal.status.success()); + let report: Value = serde_json::from_slice(&refusal.stdout).unwrap(); + assert_eq!(report["diagnostics"][0]["message"], "This development session predates per-destination keys. Run bregctl dev stop --remove and start again."); + session.remove(); + + let fresh = session.start(); + assert_eq!(fresh["outcome"], "ready"); + assert_eq!(fresh["packageSequence"], 1); + assert!(key.is_file()); + session.remove(); std::mem::forget(session); fs::remove_dir_all(parent).unwrap(); } diff --git a/crates/registry-bregctl/tests/migration_draft.rs b/crates/registry-bregctl/tests/migration_draft.rs new file mode 100644 index 0000000000..42729172d9 --- /dev/null +++ b/crates/registry-bregctl/tests/migration_draft.rs @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl migration draft` refuses before it opens any database, and never +//! overwrites a reviewed migration it already wrote. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use registry_breg::compiler::module_digest; +use registry_breg::contract::parse_module_json; +use registry_breg::fixtures::validate_fixture_journeys; +use registry_breg::package::{ + prepare_package, PackageBuildRequest, PackageMigrationPlanInput, PackageModuleSource, + PackageSourceFile, +}; +use serde_json::Value; + +const SOURCE_REVISION: &str = "compiler-source-revision"; +const FIXTURE_JOURNEYS: &[u8] = br#"apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: draft-record-list + steps: + - id: list-records + recordType: record + accessProfile: reader + claims: {principal: draft-reader} + request: {type: list} + expect: {outcome: success, status: 200, count: 0} +"#; +// Refusals happen before the runtime configuration is read, so a path that +// does not exist proves no refusal opened a database. +const UNREAD_RUNTIME_CONFIG: &str = "/nonexistent-runtime-config-is-never-read.yaml"; +static TEMPORARY_COUNTER: AtomicU64 = AtomicU64::new(0); + +struct TestDirectory { + path: PathBuf, +} + +impl TestDirectory { + fn create() -> Self { + let path = std::env::current_dir() + .expect("current directory is available") + .join(format!( + "bregctl-draft-test-{}-{}", + std::process::id(), + TEMPORARY_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).expect("test directory is created"); + Self { path } + } +} + +impl Drop for TestDirectory { + fn drop(&mut self) { + if self + .path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("bregctl-draft-test-")) + && self.path.exists() + { + fs::remove_dir_all(&self.path).expect("test directory is removed"); + } + } +} + +fn publish_package(parent: &Path, name: &str, classification: &str) -> PublishedPackage { + let module_bytes = module_bytes(classification); + let module = parse_module_json(&module_bytes).expect("package module parses"); + let project_bytes = project_bytes(&module_digest(&module)); + let prepared = prepare_package(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: SOURCE_REVISION.to_owned(), + schema_fingerprint: + "sha256:2222222222222222222222222222222222222222222222222222222222222222".to_owned(), + project: PackageSourceFile { + path: "source/registry.yaml".to_owned(), + bytes: project_bytes, + }, + modules: vec![PackageModuleSource { + id: "core".to_owned(), + path: "source/modules/core/module.yaml".to_owned(), + bytes: module_bytes, + assets: Vec::new(), + }], + fixture_journeys: PackageSourceFile { + path: "tests/journeys.yaml".to_owned(), + bytes: FIXTURE_JOURNEYS.to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }) + .expect("package prepares"); + validate_fixture_journeys(FIXTURE_JOURNEYS, prepared.registry()) + .expect("diff fixture journeys resolve against the packaged registry"); + let package = parent.join(name); + prepared + .publish_to_directory(&package) + .expect("package publishes"); + PublishedPackage { package } +} + +fn write_project(parent: &Path, name: &str, classification: &str) -> PathBuf { + write_project_with_module(parent, name, module_bytes(classification)) +} + +fn write_project_with_module(parent: &Path, name: &str, module: Vec) -> PathBuf { + let root = parent.join(name); + let parsed = parse_module_json(&module).expect("candidate module parses"); + fs::create_dir_all(root.join("modules/core")).expect("candidate directories create"); + fs::write( + root.join("registry.yaml"), + project_bytes(&module_digest(&parsed)), + ) + .expect("candidate project writes"); + fs::write(root.join("modules/core/module.yaml"), module).expect("candidate module writes"); + root +} + +fn project_bytes(module_digest: &str) -> Vec { + format!( + r#"{{"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"datasets":{{"neutral-registry": {{}}}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"restricted","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicService":{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}},"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"modules":{{"core":{{"version":"1","digest":"{module_digest}"}}}}}}"# + ) + .into_bytes() +} + +fn module_bytes(classification: &str) -> Vec { + format!( + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"record":{{"primaryDataset":"neutral-registry","route":"records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"{classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}}}}}}"# + ) + .into_bytes() +} + +fn run(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(arguments) + .output() + .expect("bregctl starts") +} + +fn json_stdout(output: &Output) -> Value { + serde_json::from_slice(&output.stdout).expect("stdout is JSON") +} + +fn path(path: &Path) -> &str { + path.to_str().expect("test path is UTF-8") +} + +struct PublishedPackage { + package: PathBuf, +} + +fn draft(arguments: &[&str]) -> Output { + let mut command = vec!["--format", "json", "migration", "draft"]; + command.extend_from_slice(arguments); + run(&command) +} + +fn refusal_code(output: &Output) -> String { + assert!(!output.status.success(), "{output:?}"); + json_stdout(output)["diagnostics"][0]["code"] + .as_str() + .expect("the refusal names a code") + .to_owned() +} + +#[test] +fn a_change_that_needs_sql_is_refused_before_any_database_access() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let module = String::from_utf8(module_bytes("internal")) + .expect("module is UTF-8") + .replacen(r#""id":"code""#, r#""id":"label""#, 1) + .replacen( + r#""readableFields":["code"]"#, + r#""readableFields":["label"]"#, + 1, + ); + let removal = write_project_with_module(&directory.path, "removal", module.into_bytes()); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&removal), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "label-rename", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.sql-required"); + let message = json_stdout(&refused)["diagnostics"][0]["message"] + .as_str() + .expect("message is text") + .to_owned(); + assert!(message.contains("field-removed"), "{message}"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn a_project_with_nothing_to_review_is_refused() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let unchanged = write_project(&directory.path, "unchanged", "internal"); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&unchanged), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "nothing", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.nothing-to-review"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn an_unknown_module_is_refused() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + + let refused = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "no-such-module", + "--id", + "widen", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.module-unknown"); + assert!(!output.exists(), "a refusal writes nothing"); +} + +#[test] +fn an_existing_reviewed_migration_is_never_overwritten() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + let existing = output.join("modules/core/migrations/widen"); + fs::create_dir_all(&existing).expect("the earlier migration directory creates"); + fs::write(existing.join("descriptor.json"), b"reviewed by hand") + .expect("the earlier descriptor writes"); + + let refused = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "widen", + ]); + assert_eq!(refusal_code(&refused), "migration.draft.output-exists"); + assert_eq!( + fs::read(existing.join("descriptor.json")).expect("the descriptor still reads"), + b"reviewed by hand" + ); + assert!(!existing.join("rehearsal.json").exists()); +} + +#[test] +fn identifiers_and_paths_are_checked_before_the_project_is_read() { + let directory = TestDirectory::create(); + let baseline = publish_package(&directory.path, "baseline", "internal"); + let widening = write_project(&directory.path, "widening", "public"); + let output = directory.path.join("reviewed"); + + let bad_id = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + "--id", + "Not A Local Id", + ]); + assert_eq!(refusal_code(&bad_id), "migration.draft.id-invalid"); + + let relative_output = draft(&[ + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + "reviewed", + "--module", + "core", + "--id", + "widen", + ]); + assert_eq!( + refusal_code(&relative_output), + "migration.draft.output-invalid" + ); + + // Every input is required: a missing --id is a usage error. + let usage = run(&[ + "migration", + "draft", + path(&widening), + "--baseline-package", + path(&baseline.package), + "--runtime-config", + UNREAD_RUNTIME_CONFIG, + "--output", + path(&output), + "--module", + "core", + ]); + assert_eq!(usage.status.code(), Some(2), "{usage:?}"); +} diff --git a/crates/registry-bregctl/tests/proposal_hooks.rs b/crates/registry-bregctl/tests/proposal_hooks.rs index 860bb01650..9588c823b9 100644 --- a/crates/registry-bregctl/tests/proposal_hooks.rs +++ b/crates/registry-bregctl/tests/proposal_hooks.rs @@ -72,10 +72,7 @@ fn native_observers_load_owned_assets_generate_schema_and_sample_the_real_transi "--event".into(), "local".into(), ]); - assert_eq!( - sample["request"]["headers"]["ce-type"], - "proposal.cancelled" - ); + assert_eq!(sample["request"]["body"]["type"], "proposal.cancelled"); assert_eq!(sample["request"]["body"]["data"]["transition"], "cancelled"); assert_eq!(sample["request"]["body"]["data"]["state"], "cancelled"); assert_eq!( diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs new file mode 100644 index 0000000000..1ae1a291a6 --- /dev/null +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision` without a database: print mode reads the runtime file +//! and writes the script without connecting or printing a password, and the +//! administrator flags refuse the combinations the shared command refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!("postgresql://breg_migration:{MIGRATION_PASSWORD}@db.invalid:5432/registry"), + ), + ( + "runtime-database-url", + format!("postgresql://breg_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/registry"), + ), + ( + "audit-key", + "synthetic-audit-key-of-at-least-32-bytes".to_owned(), + ), + ( + "cursor-key", + "synthetic-cursor-key-of-at-least-32-bytes".to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The runtime file's loader requires the package root to be a readable + // directory, though provision reads nothing from it. + std::fs::create_dir(directory.join("package")).unwrap(); + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:0 +identity: + environment: test + instanceId: provision-cli-test + databaseId: provision-cli-test-db + databaseInitializationEnvironment: test +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + pool: + maximumConnections: 4 + roles: + migration: breg_migration + runtime: breg_runtime +package: + root: {package} +authentication: + oidc: + issuer: https://issuer.example.test + audience: urn:breg:provision-cli-test + allowedAlgorithm: EdDSA + accessTokenType: JWT + scopeClaim: scope + scopeSeparator: \" \" + allowedClients: [directory-client] + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 60000 + authorityClaims: + principal: registry_principal + purpose: registry_purpose +audit: + hashKeyRef: secret:file/audit-key + path: {audit} +cursor: + secretRef: secret:file/cursor-key +", + package = directory.join("package").display(), + secrets = secrets.display(), + audit = directory.join("audit.jsonl").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in [ + "breg_migration", + "breg_runtime", + "registry", + "registry_internal", + "registry_data", + "registry_source", + "registry_derived", + "registry_context", + "btree_gist", + ] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + assert!( + !stdout.contains("postgis"), + "no package, so no PostGIS step: {stdout}" + ); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "breg"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "registry"); + assert_eq!(report["migrationRole"], "breg_migration"); + assert_eq!(report["runtimeRole"], "breg_runtime"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "BREG_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "BREG_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } +} + +#[test] +fn a_package_that_is_not_a_package_is_refused_before_any_connection() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let missing = directory.path().join("no-such-package"); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--package", + missing.to_str().unwrap(), + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(1), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["ok"], false, "{stdout}"); + assert_eq!(report["executed"], false, "{stdout}"); +} + +/// Runs `provision --print-sql --format json`, asserts the runtime file was +/// refused with exit 1 and no password anywhere in the output, and returns the +/// first diagnostic's code and path. The loader makes the checks `apply` +/// makes before it resolves the URLs itself, so these are the runtime file's +/// own codes. +fn loader_refusal(runtime: &str) -> (String, String) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "a refusal prints no password" + ); + } + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["ok"], false, "{stdout}"); + assert_eq!(report["executed"], false, "{stdout}"); + let diagnostic = &report["diagnostics"][0]; + ( + diagnostic["code"].as_str().unwrap().to_owned(), + diagnostic["path"].as_str().unwrap().to_owned(), + ) +} + +#[test] +fn a_missing_runtime_url_secret_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} + +#[test] +fn a_runtime_url_that_is_not_utf8_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/runtime-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} + +#[test] +fn a_url_user_that_differs_from_the_runtime_role_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/runtime-database-url"); + std::fs::write( + &secret, + format!("postgresql://someone_else:{RUNTIME_PASSWORD}@db.invalid:5432/registry"), + ) + .unwrap(); + let (code, path) = loader_refusal(&runtime); + assert_eq!(code, "breg.runtime.invalid-database"); + assert_eq!(path, "/database"); +} + +#[test] +fn a_missing_ca_bundle_is_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = text.replace( + " pool:\n", + " caBundleRef: secret:file/no-such-ca.pem\n pool:\n", + ); + assert_ne!(text, with_ca, "the runtime file gains the CA reference"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ("breg.runtime.secret".to_owned(), String::new()) + ); +} diff --git a/crates/registry-bregctl/tests/provision_postgres.rs b/crates/registry-bregctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..8290300cd5 --- /dev/null +++ b/crates/registry-bregctl/tests/provision_postgres.rs @@ -0,0 +1,548 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `bregctl provision` against a real server, then `test`, `package`, +//! `apply` and the runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. A spatial package needs a server with +//! PostGIS (`products/breg/scripts/local-postgres-tls.sh` starts one). The +//! administrator sessions of this suite use verified TLS, so the server must +//! offer it. Without the variables the tests fail on the spot: a skipped +//! database test is not database verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use registry_platform_testing::{TestActorKind, TestAuthorizationServer, TestClient}; +use serde_json::{json, Value}; +use uuid::Uuid; + +const AUDIENCE: &str = "urn:example:applications"; + +fn private_file(path: &Path, contents: &[u8]) { + std::fs::write(path, contents).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&std::ffi::OsStr]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + let report = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { + panic!( + "{error}: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) + }); + (output.status.code().unwrap(), report) +} + +fn ctl_ok(arguments: &[&std::ffi::OsStr]) -> Value { + let (code, report) = ctl(arguments); + assert_eq!(code, 0, "{report:#}"); + report +} + +/// A project with one record type. A spatial project adds a polygon field, +/// which makes the generated schema need PostGIS. +fn project(root: &Path, spatial: bool) { + let mut fields = vec![json!({ + "id": "owner", "type": "string", "required": true, + "maximumLength": 80, "classification": "internal" + })]; + let mut readable = vec!["owner"]; + if spatial { + fields.push(json!({ + "id": "boundary", "type": "crs84-polygon", "precision": 9, "maximumPositions": 100, + "bbox": {"west": "100.450000000", "south": "13.600000000", + "east": "100.700000000", "north": "13.900000000"}, + "required": true, "classification": "internal" + })); + readable.push("boundary"); + } + let registry = json!({ + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": { + "id": "provision-proof", + "canonicalBaseIri": "https://synthetic.example.test/provision-proof", + "version": "1", + "defaultLanguage": "en" + }, + "package": {"sourceRevision": "provision-proof"}, + "datasets": {"notes": {}}, + "recordTypes": {"note": { + "primaryDataset": "notes", "route": "notes", "mutationMode": "mutable", + "classification": "internal", "fields": fields + }}, + "accessProfiles": {"writer": { + "default": true, + "principalClaim": "sub", + "requiredScopes": ["applications:read"], + "actorKind": "service", + "requesterClients": ["application-reader"], + "permissions": {"records": [{ + "recordType": "note", + "operations": ["list"], + "readableFields": readable, + "rowBoundaries": "unrestricted" + }]} + }} + }); + std::fs::create_dir_all(root.join("tests")).unwrap(); + std::fs::write( + root.join("registry.yaml"), + serde_norway::to_string(®istry).unwrap(), + ) + .unwrap(); + let journeys = json!({ + "apiVersion": "id.registrystack.org/formats/breg/journeys/v1", + "kind": "BRegJourneys", + "journeys": [{"id": "provision-proof", "steps": [{ + "id": "list", "recordType": "note", "accessProfile": "writer", + "claims": {"principal": "fixture-reader", "scopes": ["applications:read"], + "actorKind": "service", "requesterClient": "application-reader", + "directClaims": {}}, + "request": {"type": "list"}, + "expect": {"outcome": "success", "status": 200, "count": 0} + }]}] + }); + std::fs::write( + root.join("tests/journeys.yaml"), + serde_norway::to_string(&journeys).unwrap(), + ) + .unwrap(); +} + +/// One deployment directory, the issuer its tokens come from, and the +/// superuser session that creates the roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, + base_url: String, + ca: Vec, + issuer: TestAuthorizationServer, + suffix: String, + owner: String, + owner_password: String, + migration: String, + runtime_role: String, + passwords: [String; 2], + /// Databases to drop at the end, and roles to drop after them. + databases: Vec, +} + +impl Deployment { + async fn new() -> Self { + let (base_url, ca) = provision_test_env(); + let admin = connect_verified(&base_url, &ca, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::create_dir(directory.path().join("audit")).unwrap(); + private_file(&secrets.join("postgres-ca.pem"), &ca); + private_file( + &secrets.join("audit-key"), + b"synthetic-audit-key-of-at-least-32-bytes", + ); + private_file( + &secrets.join("cursor-key"), + b"synthetic-cursor-key-of-at-least-32-bytes", + ); + let issuer = TestAuthorizationServer::builder() + .with_signing_key(generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap()) + .client( + TestClient::new("application-reader") + .with_resource(AUDIENCE) + .with_actor_kind(TestActorKind::Service), + ) + .start() + .await; + let jwks = reqwest::get(issuer.jwks_uri()) + .await + .unwrap() + .bytes() + .await + .unwrap(); + private_file(&secrets.join("jwks"), &jwks); + let token = issuer.issue_access_token( + "application-reader", + "fixture-reader", + AUDIENCE, + "applications:read", + chrono::Utc::now().timestamp() + 3600, + ); + private_file(&secrets.join("fixture-token"), token.as_bytes()); + let credentials = json!({ + "apiVersion": "id.registrystack.org/formats/breg/schema-test-credentials/v1", + "kind": "BRegSchemaTestCredentials", + "bindings": [{"journeyId": "provision-proof", "stepId": "list", + "credential": {"type": "bearer", "tokenRef": "secret:file/fixture-token"}}] + }); + std::fs::write( + directory.path().join("credentials.yaml"), + serde_norway::to_string(&credentials).unwrap(), + ) + .unwrap(); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let deployment = Self { + owner: format!("breg_owner_{suffix}"), + owner_password: password("owner"), + migration: format!("breg_mig_{suffix}"), + runtime_role: format!("breg_rt_{suffix}"), + passwords: [password("migration"), password("runtime")], + suffix, + directory, + admin, + base_url, + ca, + issuer, + databases: Vec::new(), + }; + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {} LOGIN PASSWORD '{}' NOSUPERUSER CREATEROLE CREATEDB", + deployment.owner, deployment.owner_password + )) + .await + .unwrap(); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + /// A URL for `role` against this server and `database`. + fn url(&self, role: &str, password: &str, database: &str) -> String { + let base = registry_platform_provision::admin_config(&self.base_url, Some(&self.ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + format!( + "postgresql://{role}:{password}@{}:{}/{database}", + base.host(), + base.port() + ) + } + + /// Writes the runtime file `name` for `database` over `package`. The two + /// database URLs are the only place the roles, the database and the + /// passwords are written. + fn write_runtime(&self, name: &str, database: &str, package: &Path, bind: &str) -> String { + private_file( + &self.path("secrets").join(format!("{name}-migration-url")), + self.url(&self.migration, &self.passwords[0], database) + .as_bytes(), + ); + private_file( + &self.path("secrets").join(format!("{name}-runtime-url")), + self.url(&self.runtime_role, &self.passwords[1], database) + .as_bytes(), + ); + let runtime = json!({ + "apiVersion": "id.registrystack.org/formats/breg/runtime/v1alpha1", + "kind": "BRegRuntimeConfig", + "listener": {"bind": bind}, + "identity": {"environment": "test", "instanceId": "provision-proof", + "databaseId": "provision-proof", + "databaseInitializationEnvironment": "test"}, + "secretProviders": {"file": {"root": self.path("secrets")}}, + "database": { + "runtimeUrlRef": format!("secret:file/{name}-runtime-url"), + "migrationUrlRef": format!("secret:file/{name}-migration-url"), + "caBundleRef": "secret:file/postgres-ca.pem", + "pool": {"maximumConnections": 4}, + "roles": {"migration": self.migration, "runtime": self.runtime_role} + }, + "package": {"root": package}, + "authentication": { + "oidc": { + "issuer": self.issuer.issuer(), "audience": AUDIENCE, + "allowedAlgorithm": "ES256", "accessTokenType": "at+jwt", + "scopeClaim": "scope", "scopeSeparator": " ", + "allowedClients": ["application-reader"], + "maximumTokenLifetimeSeconds": 3600, "leewayMilliseconds": 0, + "jwksSource": {"type": "static", "documentRef": "secret:file/jwks"} + }, + "authorityClaims": {"principal": "sub"} + }, + "audit": {"hashKeyRef": "secret:file/audit-key", "path": self.path("audit/breg.jsonl")}, + "cursor": {"secretRef": "secret:file/cursor-key"} + }); + let file = self.path(&format!("{name}.yaml")); + std::fs::write(&file, serde_norway::to_string(&runtime).unwrap()).unwrap(); + file.display().to_string() + } + + fn admin_url_file(&self) -> String { + let file = self.path("admin-url"); + private_file( + &file, + self.url(&self.owner, &self.owner_password, "postgres") + .as_bytes(), + ); + file.display().to_string() + } + + /// `provision` as the operate page runs it, from the non-superuser owner. + fn provision(&self, runtime: &str, package: Option<&Path>) -> (i32, Value) { + let admin_file = self.admin_url_file(); + let fixed = [ + "provision", + "--runtime-config", + runtime, + "--admin-url-file", + &admin_file, + ]; + let mut arguments: Vec<&std::ffi::OsStr> = fixed.iter().map(std::ffi::OsStr::new).collect(); + if let Some(package) = package { + arguments.push("--package".as_ref()); + arguments.push(package.as_os_str()); + } + let (code, report) = ctl(&arguments); + for password in self.passwords.iter().chain([&self.owner_password]) { + assert!( + !report.to_string().contains(password.as_str()), + "the report holds no password" + ); + } + (code, report) + } + + /// The PostGIS objects a spatial `test` needs in an already provisioned + /// rehearsal database: the operate page's statements, run by the + /// superuser, because `provision` cannot plan them before a package + /// exists to ask. + async fn add_postgis(&self, database: &str) { + let bbox = format!("{}__spatial_bbox", self.runtime_role); + let (migration, runtime) = (&self.migration, &self.runtime_role); + let setup = connect_verified(&self.base_url, &self.ca, Some(database)).await; + setup + .batch_execute(&format!( + "CREATE SCHEMA registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION postgis WITH SCHEMA registry_spatial_ext;\n\ + DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{bbox}') THEN \ + CREATE ROLE {bbox} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + END IF; END $$;\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {migration}, {runtime}, {bbox};" + )) + .await + .unwrap(); + } + + /// `test` then `package` over a rehearsal database, returning the + /// package directory. + fn build_package(&self, rehearsal_runtime: &str) -> PathBuf { + let project = self.path("project"); + let receipt = self.path("receipt.json"); + let build = self.path("build"); + ctl_ok(&[ + "test".as_ref(), + project.as_os_str(), + "--runtime-config".as_ref(), + rehearsal_runtime.as_ref(), + "--credentials".as_ref(), + self.path("credentials.yaml").as_os_str(), + "--output".as_ref(), + receipt.as_os_str(), + ]); + ctl_ok(&[ + "package".as_ref(), + project.as_os_str(), + "--test-receipt".as_ref(), + receipt.as_os_str(), + "--output".as_ref(), + build.as_os_str(), + ]); + build.join("package") + } +} + +/// Removes the databases and roles the suite created, whether the test passed +/// or an assertion failed. The statements run on a thread of their own with a +/// fresh session, so they do not depend on the test's runtime, which may be +/// unwinding. +impl Drop for Deployment { + fn drop(&mut self) { + // Dropping a database waits for its sessions to end, which the + // administrator session's statement timeout would cut short. + let mut statements: Vec = vec!["SET statement_timeout = 0".to_owned()]; + statements.extend( + self.databases + .iter() + .map(|database| format!("DROP DATABASE IF EXISTS {database} WITH (FORCE)")), + ); + statements.push(format!( + "DROP ROLE IF EXISTS {}__spatial_bbox", + self.runtime_role + )); + for role in [&self.runtime_role, &self.migration, &self.owner] { + statements.push(format!("DROP ROLE IF EXISTS {role}")); + } + let (base_url, ca) = (self.base_url.clone(), self.ca.clone()); + let cleanup = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime for the cleanup") + .block_on(async { + let admin = connect_verified(&base_url, &ca, None).await; + for statement in statements { + admin + .batch_execute(&statement) + .await + .unwrap_or_else(|error| { + panic!("cleanup statement `{statement}` failed: {error}") + }); + } + }); + }); + if let Err(failure) = cleanup.join() { + if std::thread::panicking() { + eprintln!("the suite's databases and roles were not removed: {failure:?}"); + } else { + std::panic::resume_unwind(failure); + } + } + } +} + +fn free_address() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().to_string() +} + +/// `provision` over the rehearsal and the serving database, `test` and +/// `package` over the first, `apply` over the second, and the runtime +/// started over the runtime credential answers its readiness route. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn provision_then_apply_then_serve_with_split_roles() { + let mut deployment = Deployment::new().await; + project(&deployment.path("project"), false); + let (rehearsal, live) = ( + format!("breg_rehearsal_{}", deployment.suffix), + format!("breg_live_{}", deployment.suffix), + ); + deployment.databases = vec![rehearsal.clone(), live.clone()]; + let empty_package = deployment.path("empty-package"); + std::fs::create_dir(&empty_package).unwrap(); + + let rehearsal_runtime = + deployment.write_runtime("rehearsal", &rehearsal, &empty_package, "127.0.0.1:0"); + let (code, provisioned) = deployment.provision(&rehearsal_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], rehearsal.as_str()); + let package = deployment.build_package(&rehearsal_runtime); + + let address = free_address(); + let live_runtime = deployment.write_runtime("live", &live, &package, &address); + let (code, provisioned) = deployment.provision(&live_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], live.as_str()); + let (code, again) = deployment.provision(&live_runtime, None); + assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } + + let applied = ctl_ok(&[ + "apply".as_ref(), + "--runtime-config".as_ref(), + live_runtime.as_ref(), + "--package".as_ref(), + package.as_os_str(), + "--initial".as_ref(), + ]); + assert_eq!(applied["activation"], "initial", "{applied:#}"); + + let config = registry_breg::runtime_config::load_runtime_config(Path::new(&live_runtime)) + .expect("the live runtime file loads"); + let prepared = registry_breg::startup::prepare_loaded(config) + .await + .expect("the runtime prepares over the runtime role"); + assert_eq!( + format!("{:?}", prepared.role_mode()).to_lowercase(), + "split", + "the runtime serves on separate roles" + ); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(registry_breg::startup::serve_until_shutdown( + prepared, + async move { + stopped.await.ok(); + Ok(()) + }, + )); + let http = reqwest::Client::builder().no_proxy().build().unwrap(); + let mut ready = false; + for _ in 0..100 { + if let Ok(response) = http.get(format!("http://{address}/ready")).send().await { + if response.status().is_success() { + ready = true; + break; + } + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + assert!(ready, "the readiness route answers"); + stop.send(()).unwrap(); + server.await.unwrap().expect("the server stops cleanly"); +} + +/// A package with a polygon field needs PostGIS, and `CREATE EXTENSION +/// postgis` needs a superuser, so a non-superuser owner is told which +/// statement needs more. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn spatial_package_as_a_non_superuser_owner_names_the_postgis_statement() { + let mut deployment = Deployment::new().await; + project(&deployment.path("project"), true); + let (rehearsal, live) = ( + format!("breg_rehearsal_{}", deployment.suffix), + format!("breg_live_{}", deployment.suffix), + ); + deployment.databases = vec![rehearsal.clone(), live.clone()]; + let empty_package = deployment.path("empty-package"); + std::fs::create_dir(&empty_package).unwrap(); + + // The owner provisions the rehearsal database, then the superuser adds + // the PostGIS objects `test` needs. + let rehearsal_runtime = + deployment.write_runtime("rehearsal", &rehearsal, &empty_package, "127.0.0.1:0"); + let (code, provisioned) = deployment.provision(&rehearsal_runtime, None); + assert_eq!(code, 0, "{provisioned:#}"); + deployment.add_postgis(&rehearsal).await; + let package = deployment.build_package(&rehearsal_runtime); + + let live_runtime = deployment.write_runtime("live", &live, &package, "127.0.0.1:0"); + let (code, refused) = deployment.provision(&live_runtime, Some(&package)); + assert_eq!(code, 1, "{refused:#}"); + assert_eq!(refused["status"], "domain-refusal", "{refused:#}"); + let diagnostic = &refused["diagnostics"][0]; + assert_eq!( + diagnostic["code"], "platform.provision.statement-needs-privilege", + "{refused:#}" + ); + assert_eq!(diagnostic["path"], "extension.postgis", "{refused:#}"); +} diff --git a/crates/registry-bregctl/tests/webhook.rs b/crates/registry-bregctl/tests/webhook.rs index e0ed777094..44f0fb114a 100644 --- a/crates/registry-bregctl/tests/webhook.rs +++ b/crates/registry-bregctl/tests/webhook.rs @@ -117,7 +117,7 @@ where } #[test] -fn sample_is_an_exact_deterministic_cloudevents_request_without_deployment_authority() { +fn sample_is_an_exact_deterministic_standard_webhooks_request_without_deployment_authority() { let project = TestProject::create(); let (status, first, stderr) = run([ OsStr::new("bregctl"), @@ -159,32 +159,17 @@ fn sample_is_an_exact_deterministic_cloudevents_request_without_deployment_autho assert_eq!( headers.keys().map(String::as_str).collect::>(), BTreeSet::from([ - "Accept", - "Content-Type", - "Idempotency-Key", - "X-Registry-Delivery-Attempt", - "X-Registry-Delivery-Time", - "X-Registry-Event-Generation", - "X-Registry-Signature", - "ce-dataschema", - "ce-id", - "ce-source", - "ce-specversion", - "ce-time", - "ce-type", + "accept", + "content-type", + "webhook-id", + "webhook-timestamp", + "webhook-signature", ]) ); - assert_eq!(headers["ce-specversion"], "1.0"); - assert_eq!(headers["ce-type"], EVENT_ID); - assert_eq!( - headers["ce-source"], - "urn:registrystack:registry:hook-sample:instance:" - ); - assert_eq!(headers["X-Registry-Signature"], "v1="); - assert!(headers["ce-dataschema"] - .as_str() - .expect("data schema is text") - .starts_with("urn:breg:event-schema:hook-sample:record:record-created-v1:sha256:")); + assert_eq!(headers["accept"], "application/json"); + assert_eq!(headers["content-type"], "application/json"); + assert_eq!(headers["webhook-timestamp"], "1767225600"); + assert_eq!(headers["webhook-signature"], "v1,"); let body = &report["request"]["body"]; assert_eq!( body.as_object() @@ -203,11 +188,17 @@ fn sample_is_an_exact_deterministic_cloudevents_request_without_deployment_autho "type", ]) ); - assert_eq!(body["id"], headers["ce-id"]); - assert_eq!(body["type"], headers["ce-type"]); - assert_eq!(body["source"], headers["ce-source"]); - assert_eq!(body["time"], headers["ce-time"]); - assert_eq!(body["dataschema"], headers["ce-dataschema"]); + assert_eq!(body["id"], headers["webhook-id"]); + assert_eq!(body["type"], EVENT_ID); + assert_eq!( + body["source"], + "urn:registrystack:registry:hook-sample:instance:" + ); + assert_eq!(body["time"], "2026-01-01T00:00:00Z"); + assert!(body["dataschema"] + .as_str() + .expect("data schema is text") + .starts_with("urn:breg:event-schema:hook-sample:record:record-created-v1:sha256:")); assert_eq!(body["subject"]["recordRevision"], 1); assert_eq!( body["causation"], diff --git a/crates/registry-casework-client/src/client.rs b/crates/registry-casework-client/src/client.rs index b7e2a47924..152882b688 100644 --- a/crates/registry-casework-client/src/client.rs +++ b/crates/registry-casework-client/src/client.rs @@ -25,7 +25,7 @@ use registry_platform_httputil::client::{ send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_review_client::{ ReviewAuth as ProducerReviewAuth, ReviewClient as ProducerReviewClient, @@ -1750,7 +1750,7 @@ impl CaseworkClient { .map_err(|error| CaseworkClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), CaseworkProtocolFailure::HeaderBounds, diff --git a/crates/registry-casework/Cargo.toml b/crates/registry-casework/Cargo.toml index a0e4a4851f..36d40f4e34 100644 --- a/crates/registry-casework/Cargo.toml +++ b/crates/registry-casework/Cargo.toml @@ -44,11 +44,11 @@ registry-casework-breg.workspace = true registry-platform-canonical-json.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-oidc.workspace = true registry-platform-httputil.workspace = true registry-platform-metrics.workspace = true @@ -79,7 +79,7 @@ registry-casework-client.workspace = true registry-breg-client.workspace = true registry-review-client.workspace = true registry-bregctl.workspace = true -registry-platform-testing = { workspace = true, features = ["test-utils", "migration-pins"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "migration-pins", "token-fixtures"] } tempfile.workspace = true tower.workspace = true wiremock.workspace = true diff --git a/crates/registry-casework/migrations/0201_activation_posture.sql b/crates/registry-casework/migrations/0201_activation_posture.sql new file mode 100644 index 0000000000..f216a5fc55 --- /dev/null +++ b/crates/registry-casework/migrations/0201_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE casework_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE casework_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-casework/src/activation.rs b/crates/registry-casework/src/activation.rs index 5e4a8a9791..54dbf1ec1c 100644 --- a/crates/registry-casework/src/activation.rs +++ b/crates/registry-casework/src/activation.rs @@ -687,15 +687,15 @@ async fn apply_in( let activation = platform_activation::append_activation( transaction, &activation_layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, - package_digest: candidate.package_digest, - database_id: candidate.database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + candidate.package_digest, + candidate.database_id, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; diff --git a/crates/registry-casework/src/assignment.rs b/crates/registry-casework/src/assignment.rs index 4cee5052b1..37ec0319ba 100644 --- a/crates/registry-casework/src/assignment.rs +++ b/crates/registry-casework/src/assignment.rs @@ -2,6 +2,7 @@ use crate::{CaseworkService, PostgresStore, ServiceError, StoreError}; use chrono::{TimeDelta, Utc}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; @@ -140,7 +141,7 @@ impl PostgresStore { CaseworkActsAs::Administrator | CaseworkActsAs::Requester => false, }; if !authorized { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } transaction .query( @@ -174,12 +175,12 @@ impl PostgresStore { ) .await? } - CaseworkActsAs::Requester => return Err(StoreError::Forbidden), + CaseworkActsAs::Requester => return Err(StoreError::Forbidden(FailedCheck::Operation)), }, DirectoryTargetPurpose::AbsenceCover => { let person = person.ok_or(StoreError::Invalid)?; if !can_manage_person(&transaction, actor, person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if actor.role == CaseworkActsAs::Supervisor { // A supervisor covers only inside the teams they lead, so a @@ -250,7 +251,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } validate_reason( idempotency_key, @@ -380,7 +381,7 @@ impl PostgresStore { actor.role, CaseworkActsAs::Staff | CaseworkActsAs::Supervisor | CaseworkActsAs::Administrator ) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if !(1..=1_000).contains(&limit) { return Err(StoreError::Invalid); @@ -572,7 +573,7 @@ impl PostgresStore { &[&id], ) .await? - .ok_or(StoreError::NotFound)?; + .ok_or(StoreError::Absent)?; let record = absence_from_row(row)?; if record.person != input.person { return Err(StoreError::Invalid); @@ -587,7 +588,7 @@ impl PostgresStore { if !can_manage_person(&transaction, actor, managed_person).await? || !valid_absence_cover(&transaction, actor, managed_person, &input.cover).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if let Some(response) = assignment_replay( &transaction, @@ -618,7 +619,7 @@ impl PostgresStore { if absence_id.is_some() { let changed=transaction.execute("UPDATE casework_absences SET person_issuer=$2,person_subject=$3,starts_at=$4,ends_at=$5,cover_issuer=$6,cover_subject=$7,revision=$8 WHERE absence_id=$1",&[&id,&input.person.issuer,&input.person.subject,&input.from,&input.until,&input.cover.issuer,&input.cover.subject,&next]).await?; if changed != 1 { - return Err(StoreError::NotFound); + return Err(StoreError::Absent); } } else { transaction.execute("INSERT INTO casework_absences(absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision) VALUES($1,$2,$3,$4,$5,$6,$7,$8)",&[&id,&input.person.issuer,&input.person.subject,&input.from,&input.until,&input.cover.issuer,&input.cover.subject,&next]).await?; @@ -697,7 +698,7 @@ impl PostgresStore { let replay: AbsenceDeleteReplay = serde_json::from_value(response).map_err(StoreError::Json)?; if !can_manage_person(&transaction, actor, &replay.person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } audit.record_outcome(crate::audit::AuditOutcome::Replayed); audit.commit(transaction).await?; @@ -713,10 +714,10 @@ impl PostgresStore { if actual != expected_directory_revision { return Err(StoreError::Conflict); } - let row=transaction.query_opt("SELECT absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision FROM casework_absences WHERE absence_id=$1 FOR UPDATE",&[&absence_id]).await?.ok_or(StoreError::NotFound)?; + let row=transaction.query_opt("SELECT absence_id,person_issuer,person_subject,starts_at,ends_at,cover_issuer,cover_subject,revision FROM casework_absences WHERE absence_id=$1 FOR UPDATE",&[&absence_id]).await?.ok_or(StoreError::Absent)?; let record = absence_from_row(row)?; if !can_manage_person(&transaction, actor, &record.person).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let next = actual.checked_add(1).ok_or(StoreError::Corrupt)?; transaction @@ -769,7 +770,7 @@ impl CaseworkService { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } if expected_directory_revision < 0 || !valid_directory_identifier(&request.team_id) @@ -798,7 +799,7 @@ impl CaseworkService { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } if expected_directory_revision < 0 || !valid_directory_identifier(team_id) diff --git a/crates/registry-casework/src/audit.rs b/crates/registry-casework/src/audit.rs index 034b8b6043..a6f2e358d8 100644 --- a/crates/registry-casework/src/audit.rs +++ b/crates/registry-casework/src/audit.rs @@ -885,7 +885,7 @@ mod capture { #[must_use] pub fn capture() -> (Self, AuditCapture) { let capture = AuditCapture::default(); - let writer = AuditWriter::from_line_sink(Box::new(capture.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())); let audit = Self::new(writer.clone(), AuditKeyHasher::unkeyed_dev_only()); { let mut state = capture.0.lock().expect("audit capture"); diff --git a/crates/registry-casework/src/auth.rs b/crates/registry-casework/src/auth.rs index 8eb4aef4ca..d020845d44 100644 --- a/crates/registry-casework/src/auth.rs +++ b/crates/registry-casework/src/auth.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use registry_casework_core::{ AccessProfile, ActorContext, CaseworkActsAs, CaseworkProject, IssuerPrincipal, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{JwksFetcher, TokenVerifier, TokenVerifierConfig}; use serde_json::Value; use thiserror::Error; @@ -25,15 +25,32 @@ pub struct CaseworkAuthenticator { initiator_profiles: BTreeSet, human_identity: HumanIdentityConfig, delegated_staff_readers: BTreeMap, + /// The claim the deployment configured to carry scopes. A scope refusal + /// names it to the operator. + scope_claim: String, +} + +tokio::task_local! { + /// The operator-declared values of the scope check the current request + /// failed. The HTTP edge scopes it around each request and attaches it to + /// the refusal answer's extensions, which are never written to the wire. + pub(crate) static DECLARED_SCOPE: std::cell::RefCell>; } impl CaseworkAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Casework authentication refused" - ); + /// Record, for the operator's refusal line, the scope the operation needs + /// and the access profile that was applied. Both are declared by the + /// configuration or the package, never read from the token. + fn declare_scope_refusal(&self, required_scope: Option<&str>, access_profile: Option<&str>) { + let mut declared = DeclaredScope::new(&self.scope_claim); + if let Some(scope) = required_scope { + declared = declared.with_required_scope(scope); + } + if let Some(profile) = access_profile { + declared = declared.with_access_profile(profile); + } + // Outside an HTTP request there is no line to carry it. + let _ = DECLARED_SCOPE.try_with(|slot| *slot.borrow_mut() = Some(declared)); } /// Constructs an authenticator from a project already validated by @@ -47,6 +64,7 @@ impl CaseworkAuthenticator { ) -> Self { let audience = verifier.audiences.first().cloned().unwrap_or_default(); Self { + scope_claim: verifier.scope_claim.clone(), source_verifier_config: verifier.clone(), source_keys: Arc::clone(&keys), source_verifiers: BTreeMap::new(), @@ -103,50 +121,61 @@ impl CaseworkAuthenticator { source: &str, provider: &str, ) -> Result<(), AuthenticationError> { - validate_compact_access_token(source).map_err(|_| AuthenticationError::Refused)?; + validate_compact_access_token(source) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let source_verifier = self .source_verifiers .get(provider) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::AccessProfile))?; let primary = self .verifier .verify(casework) .await - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; let secondary = source_verifier .verify(source) .await - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; for verified in [&primary, &secondary] { if !matches!( verified.claims.aud, Some(registry_platform_oidc::Audience::One(_)) - ) || verified.claims.sub.as_deref().is_none_or(str::is_empty) - || verified - .claims - .extra - .get("registry_actor_kind") - .and_then(Value::as_str) - != Some("human") + ) { + return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)); + } + if verified.claims.sub.as_deref().is_none_or(str::is_empty) { + return Err(AuthenticationError::Refused(FailedCheck::TokenClaims)); + } + if verified + .claims + .extra + .get("registry_actor_kind") + .and_then(Value::as_str) + != Some("human") || verified .claims .extra .get(&self.human_identity.claim) .and_then(Value::as_str) != Some(self.human_identity.value.as_str()) - || verified.claims.extra.contains_key("act") - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_")) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::ActorKind)); + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } } if primary.claims.iss != secondary.claims.iss || primary.claims.sub != secondary.claims.sub { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::TokenClaims)); } Ok(()) } @@ -166,38 +195,46 @@ impl CaseworkAuthenticator { scope: &str, kind: registry_platform_oidc::ActorKind, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework authentication refused" - ); - AuthenticationError::Refused - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; if !matches!( verified.claims.aud.as_ref(), Some(registry_platform_oidc::Audience::One(_)) ) && !matches!(verified.claims.aud.as_ref(), Some(registry_platform_oidc::Audience::Many(values)) if values.len() == 1) - || verified.claims.extra.contains_key("act") - || !verified.scopes.iter().any(|value| value == scope) - || verified.matched_client_id().ok().flatten().is_none() - || registry_platform_oidc::actor_kind( - &verified.claims, - ®istry_platform_oidc::ClaimNames::default(), - ) - .ok() - != Some(kind) - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_")) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)); + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if !verified.scopes.iter().any(|value| value == scope) { + self.declare_scope_refusal(Some(scope), None); + return Err(AuthenticationError::Refused(FailedCheck::Scope)); + } + if verified.matched_client_id().ok().flatten().is_none() { + return Err(AuthenticationError::Refused(FailedCheck::TokenClient)); + } + if registry_platform_oidc::actor_kind( + &verified.claims, + ®istry_platform_oidc::ClaimNames::default(), + ) + .ok() + != Some(kind) + { + return Err(AuthenticationError::Refused(FailedCheck::ActorKind)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } Ok(verified) } @@ -207,46 +244,52 @@ impl CaseworkAuthenticator { token: &str, selected_profile: &str, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework authentication refused" - ); - AuthenticationError::Refused - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; let matched_client = verified .matched_client_id() - .map_err(|_| AuthenticationError::Refused)?; - if self.delegated_staff_readers.values().any(|reader| { - matched_client == Some(reader.client.as_str()) - && (verified.claims.extra.contains_key("act") - || verified - .scopes - .iter() - .any(|scope| scope == &reader.required_scope)) - }) { - return Err(AuthenticationError::Refused); + .map_err(|_| AuthenticationError::Refused(FailedCheck::TokenClient))?; + for reader in self.delegated_staff_readers.values() { + if matched_client != Some(reader.client.as_str()) { + continue; + } + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .scopes + .iter() + .any(|scope| scope == &reader.required_scope) + { + // The delegated read scope is refused here because it belongs to the + // delegated path, so the line names no scope as required. + self.declare_scope_refusal(None, None); + return Err(AuthenticationError::Refused(FailedCheck::Scope)); + } } - let profile = self.profiles.get(selected_profile).ok_or_else(|| { - self.profile_diagnostic(); - AuthenticationError::Profile - })?; + let profile = self + .profiles + .get(selected_profile) + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; let requires_person = profile.acts_as != CaseworkActsAs::Requester || self.initiator_profiles.contains(&profile.id); - if requires_person - && (verified.claims.extra.contains_key("act") - || verified - .claims - .extra - .keys() - .any(|key| key.starts_with("registry_grant_"))) - { - return Err(AuthenticationError::Refused); + if requires_person { + if verified.claims.extra.contains_key("act") { + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); + } + if verified + .claims + .extra + .keys() + .any(|key| key.starts_with("registry_grant_")) + { + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); + } } let actual_scopes: BTreeSet<_> = verified.scopes.iter().map(String::as_str).collect(); if !profile @@ -254,13 +297,15 @@ impl CaseworkAuthenticator { .iter() .all(|scope| actual_scopes.contains(scope.as_str())) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Scope, - "Casework authentication profile refused", - remedy = "check authentication.oidc.scopeClaim and accessProfiles requiredScopes" + self.declare_scope_refusal( + profile + .required_scopes + .iter() + .map(String::as_str) + .find(|scope| !actual_scopes.contains(scope)), + Some(&profile.id), ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if requires_person { let human_identity = verified @@ -269,13 +314,9 @@ impl CaseworkAuthenticator { .get(&self.human_identity.claim) .and_then(Value::as_str) .filter(|value| !value.is_empty()) - .ok_or_else(|| { - self.profile_diagnostic(); - AuthenticationError::NotHuman - })?; + .ok_or(AuthenticationError::NotHuman(FailedCheck::ActorKind))?; if human_identity != self.human_identity.value { - self.profile_diagnostic(); - return Err(AuthenticationError::NotHuman); + return Err(AuthenticationError::NotHuman(FailedCheck::ActorKind)); } } let principal = if profile.principal_claim == "sub" { @@ -288,12 +329,12 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) } .filter(|value| !value.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let issuer = verified .claims .iss .filter(|issuer| !issuer.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(ActorContext { principal: IssuerPrincipal { issuer, @@ -303,15 +344,6 @@ impl CaseworkAuthenticator { role: profile.acts_as, }) } - - fn profile_diagnostic(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Profile, - "Casework authentication profile refused", - remedy = "check selected accessProfiles and authentication.oidc.humanIdentity profile category" - ); - } } impl std::fmt::Debug for CaseworkAuthenticator { @@ -329,16 +361,32 @@ impl std::fmt::Debug for CaseworkAuthenticator { } } +/// Why authentication refused a request. Each variant names the check that +/// failed, which goes to the operator's counter and log and never to the +/// caller. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the selected Casework profile was refused")] - Profile, + Profile(FailedCheck), #[error("the verified identity is not a human session")] - NotHuman, + NotHuman(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), +} + +impl AuthenticationError { + /// The check the request failed. + #[must_use] + pub const fn failed_check(self) -> FailedCheck { + match self { + Self::Refused(check) + | Self::Profile(check) + | Self::NotHuman(check) + | Self::Claims(check) => check, + } + } } #[cfg(test)] @@ -359,7 +407,7 @@ mod tests { const SECRET: &[u8] = b"01234567890123456789012345678901"; #[tokio::test] - async fn equivalent_profile_refusals_share_one_bounded_value_free_diagnostic() { + async fn equivalent_profile_refusals_name_their_check_and_write_no_log_line() { use tracing::instrument::WithSubscriber; #[derive(Clone)] struct Writer(Arc>>); @@ -405,7 +453,7 @@ mod tests { .with_subscriber(subscriber.clone()) .await .unwrap_err(), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::AccessProfile) ); for kind in [None, Some(""), Some("canary-private-actor")] { let mut claims = base.clone(); @@ -418,15 +466,13 @@ mod tests { .with_subscriber(subscriber.clone()) .await .unwrap_err(), - AuthenticationError::NotHuman + AuthenticationError::NotHuman(FailedCheck::ActorKind) ); } + // Recording belongs to the HTTP boundary, which counts and logs each + // refusal once by its check. The authenticator writes nothing. let rendered = String::from_utf8(output.lock().unwrap().clone()).unwrap(); - assert_eq!(rendered.lines().count(), 1); - assert!(rendered.contains("profile")); - assert!(rendered.contains("authentication.oidc.humanIdentity")); - assert!(!rendered.contains("canary-private")); - assert!(!rendered.contains(&credential)); + assert!(rendered.is_empty(), "{rendered}"); } fn project() -> CaseworkProject { @@ -636,6 +682,75 @@ mod tests { .is_err()); } + #[tokio::test] + async fn separate_human_source_refusals_name_the_check_that_failed() { + let auth = authenticator(BTreeMap::new()).with_human_source_audiences(BTreeMap::from([( + "registry".into(), + "urn:breg:source".into(), + )])); + let primary_claims = json!({"sub":"same-human", "client_id":CLIENT, "registry_actor_kind":"human", "human_session":"yes"}); + let source_claims = json!({"aud":"urn:breg:source", "sub":"same-human", "client_id":"source-client", "registry_actor_kind":"human", "human_session":"yes"}); + let primary = token(primary_claims.clone()); + let auth = { + let mut auth = auth; + auth.human_identity = HumanIdentityConfig { + claim: "human_session".into(), + value: "yes".into(), + }; + auth + }; + auth.verify_human_source_pair(&primary, &token(source_claims.clone()), "registry") + .await + .expect("the pair is the same human"); + assert_eq!( + auth.verify_human_source_pair(&primary, &token(source_claims.clone()), "unknown") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::AccessProfile) + ); + assert_eq!( + auth.verify_human_source_pair(&primary, "not-a-token", "registry") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + for (patch, expected) in [ + (json!({"sub":"another-human"}), FailedCheck::TokenClaims), + (json!({"aud":AUDIENCE}), FailedCheck::TokenAudience), + ( + json!({"aud":["urn:breg:source"]}), + FailedCheck::TokenAudience, + ), + ( + json!({"iss":"https://other.example.test"}), + FailedCheck::TokenIssuer, + ), + ( + json!({"registry_actor_kind":"service"}), + FailedCheck::ActorKind, + ), + (json!({"human_session":"no"}), FailedCheck::ActorKind), + (json!({"act":{"sub":"agent"}}), FailedCheck::Delegation), + ( + json!({"registry_grant_id":"grant"}), + FailedCheck::TaskGrantClaims, + ), + ] { + let mut claims = source_claims.clone(); + claims + .as_object_mut() + .unwrap() + .extend(patch.as_object().unwrap().clone()); + assert_eq!( + auth.verify_human_source_pair(&primary, &token(claims), "registry") + .await + .unwrap_err(), + AuthenticationError::Refused(expected), + "{patch}" + ); + } + } + #[tokio::test] async fn separate_human_source_refusals_never_log_credentials_or_subjects() { use tracing::instrument::WithSubscriber; @@ -730,7 +845,10 @@ mod tests { let result = authenticator .authenticate_task_client(&disallowed, "task-grant", ActorKind::Service) .await; - assert!(matches!(result, Err(AuthenticationError::Refused))); + assert_eq!( + result.unwrap_err(), + AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer) + ); let allowed = token(json!({ "azp": CLIENT, @@ -833,39 +951,46 @@ mod tests { .await .expect("the exact delegated reader is accepted"); assert_eq!(reader.principal_for_test().subject, "officer-7"); - assert!(matches!( - auth.authenticate(&credential, "staff").await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate(&credential, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&credential, "staff").await.unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); + assert_eq!( + auth.authenticate(&credential, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let delegated_actor_without_reader_scope = delegated_token(json!({ "scope": "casework:staff" })); - assert!(matches!( + assert_eq!( auth.authenticate(&delegated_actor_without_reader_scope, "requester-overlap") - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let second_policy = delegated_token(json!({ "scope": "casework:staff casework:other-delegated-read" })); - assert!(matches!( - auth.authenticate(&second_policy, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&second_policy, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); let stripped = token(json!({ "azp": CLIENT, "sub": "officer-7", "scope": "casework:staff casework:staff:delegated-read", "registry_actor_kind": "service" })); - assert!(matches!( - auth.authenticate(&stripped, "requester-overlap").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&stripped, "requester-overlap") + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Scope) + ); let credential = delegated_token(json!({"aud": [AUDIENCE]})); auth.authenticate_staff_read(&credential, "staff-mcp", Some("review-agent")) .await @@ -888,35 +1013,35 @@ mod tests { for (claims, expected) in [ ( json!({"act":{"iss":ISSUER,"sub":"other"}}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::Delegation), ), ( json!({"act":{"iss":ISSUER,"sub":"registry-mcp","act":{"sub":"nested"}}}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::Delegation), ), ( json!({"scope":"casework:staff:delegated-read"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"scope":"casework:staff"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"scope":"casework:staff casework:staff casework:staff:delegated-read"}), - AuthenticationError::Profile, + AuthenticationError::Profile(FailedCheck::Scope), ), ( json!({"iat":now,"exp":now+301}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TokenTime), ), ( json!({"registry_grant_id":"not-allowed"}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TaskGrantClaims), ), ( json!({"aud":[AUDIENCE, AUDIENCE]}), - AuthenticationError::Refused, + AuthenticationError::Refused(FailedCheck::TokenAudience), ), ] { let credential = delegated_token(claims); @@ -928,11 +1053,12 @@ mod tests { ); } let credential = delegated_token(json!({})); - assert!(matches!( + assert_eq!( auth.authenticate_staff_read(&credential, "staff-mcp", Some("other-source")) - .await, - Err(AuthenticationError::Profile) - )); + .await + .unwrap_err(), + AuthenticationError::Profile(FailedCheck::AccessProfile) + ); } #[tokio::test] @@ -956,20 +1082,21 @@ mod tests { json!({"sub":"other-gateway"}), json!({"sub":"registry-mcp","act":{"sub":"prior-gateway"}}), ] { - assert!(matches!( + assert_eq!( auth.authenticate_staff_read( &delegated_token(json!({"act":act})), "staff-mcp", Some("review-agent"), ) - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::Delegation) + ); } } #[tokio::test] - async fn delegated_staff_read_negative_cases_have_value_free_stage_diagnostics() { + async fn delegated_staff_read_negative_cases_name_their_check_and_write_no_log_line() { use registry_platform_testing::CapturedDiagnosticLogs; use tracing::instrument::WithSubscriber; @@ -979,7 +1106,6 @@ mod tests { policy: &'static str, source_profile: Option<&'static str>, expected_error: AuthenticationError, - expected_stage: &'static str, default_off: bool, } @@ -1008,8 +1134,7 @@ mod tests { credential: without_act, policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::Delegation), default_off: false, }, NegativeCase { @@ -1017,8 +1142,7 @@ mod tests { credential: delegated_token(json!({"azp": "canary-wrong-client"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer), default_off: false, }, NegativeCase { @@ -1028,8 +1152,7 @@ mod tests { })), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "client", + expected_error: AuthenticationError::Refused(FailedCheck::TokenAssertionIssuer), default_off: false, }, NegativeCase { @@ -1037,8 +1160,7 @@ mod tests { credential: delegated_token(json!({"registry_actor_kind": "service"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::NotHuman, - expected_stage: "profile", + expected_error: AuthenticationError::NotHuman(FailedCheck::ActorKind), default_off: false, }, NegativeCase { @@ -1046,8 +1168,7 @@ mod tests { credential: missing_iat, policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Refused, - expected_stage: "time", + expected_error: AuthenticationError::Refused(FailedCheck::TokenTime), default_off: false, }, NegativeCase { @@ -1055,8 +1176,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-unknown-policy"})), policy: "canary-unknown-policy", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: false, }, NegativeCase { @@ -1064,8 +1184,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-default-off"})), policy: "staff-mcp", source_profile: Some("review-agent"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: true, }, NegativeCase { @@ -1073,8 +1192,7 @@ mod tests { credential: delegated_token(json!({"sub": "canary-source-profile"})), policy: "staff-mcp", source_profile: Some("canary-unlisted-source"), - expected_error: AuthenticationError::Profile, - expected_stage: "profile", + expected_error: AuthenticationError::Profile(FailedCheck::AccessProfile), default_off: false, }, ]; @@ -1090,33 +1208,15 @@ mod tests { .with_subscriber(captured.subscriber()) .await; assert_eq!(result.unwrap_err(), case.expected_error, "{}", case.name); - let rendered = captured.text(); - let entries = rendered - .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .collect::>(); - assert_eq!(entries.len(), 1, "{}: {rendered}", case.name); - assert_eq!( - entries[0]["fields"]["message"], "Casework delegated staff authentication refused", - "{}", - case.name - ); - assert_eq!( - entries[0]["fields"]["stage"], case.expected_stage, - "{}", - case.name - ); - assert!(!rendered.contains("canary"), "{}: {rendered}", case.name); - assert!( - !rendered.contains(&case.credential), - "{}: credential reached diagnostic", - case.name - ); + // Recording belongs to the HTTP boundary. The authenticator + // writes nothing, whatever the credential carries. + assert_eq!(captured.text(), "", "{}", case.name); } } #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { + async fn compact_token_admission_refuses_a_malformed_token_as_malformed_and_writes_no_log_line() + { use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; use tracing::instrument::WithSubscriber; let captured = CapturedDiagnosticLogs::default(); @@ -1125,25 +1225,27 @@ mod tests { let auth = authenticator(BTreeMap::new()); for _ in 0..3 { for token in &tokens { - assert!(matches!( + assert_eq!( auth.authenticate(token, "requester") .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + assert_eq!( auth.authenticate_task_client( token, "casework:grants:status", ActorKind::Service ) .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); + .await + .unwrap_err(), + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); } } - captured.assert_one_value_free_header_diagnostic(&tokens); + assert_eq!(captured.text(), ""); } #[tokio::test] @@ -1190,31 +1292,31 @@ mod tests { let auth = &auth; async move { auth.authenticate(&token, "staff").await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. let token = self::token( json!({"azp":CLIENT,"scope":"casework:staff","registry_actor_kind":"human"}), ); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::Refused) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::Refused(FailedCheck::TokenAlgorithm) + ); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::NotHuman) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::NotHuman(FailedCheck::ActorKind) + ); let mut missing = claims.clone(); missing["scope"] = json!(""); let token = sign(missing, "at+jwt"); - assert!(matches!( - auth.authenticate(&token, "staff").await, - Err(AuthenticationError::Profile) - )); + assert_eq!( + auth.authenticate(&token, "staff").await.unwrap_err(), + AuthenticationError::Profile(FailedCheck::Scope) + ); } } } diff --git a/crates/registry-casework/src/auth/delegated.rs b/crates/registry-casework/src/auth/delegated.rs index 124c9cfc58..1f1fba6d1a 100644 --- a/crates/registry-casework/src/auth/delegated.rs +++ b/crates/registry-casework/src/auth/delegated.rs @@ -127,7 +127,7 @@ impl crate::CaseworkService { Err(error) => Err(error), } } - Ok(_) => Err(crate::ReviewRuntimeError::NotFound), + Ok(_) => Err(crate::ReviewRuntimeError::NotHeldByReader), Err(error) => Err(error), }; let terminal = delegated_audit_outcome(&outcome); @@ -142,8 +142,9 @@ fn delegated_audit_outcome( match outcome { Ok(_) => crate::audit::AuditOutcome::Succeeded, Err( - crate::ReviewRuntimeError::Forbidden + crate::ReviewRuntimeError::Forbidden(_) | crate::ReviewRuntimeError::NotFound + | crate::ReviewRuntimeError::NotHeldByReader | crate::ReviewRuntimeError::SourceProfileRequired | crate::ReviewRuntimeError::ResultExpired | crate::ReviewRuntimeError::Invalid, @@ -159,7 +160,7 @@ fn delegated_recheck( Ok(true) => Ok(()), Ok(false) | Err( - crate::ReviewRuntimeError::Forbidden + crate::ReviewRuntimeError::Forbidden(_) | crate::ReviewRuntimeError::NotFound | crate::ReviewRuntimeError::ResultExpired, ) => Err(crate::ReviewRuntimeError::NotFound), @@ -168,82 +169,51 @@ fn delegated_recheck( } impl CaseworkAuthenticator { - fn delegated_staff_refusal( - &self, - stage: registry_platform_oidc::AuthenticationStage, - error: AuthenticationError, - ) -> AuthenticationError { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - stage, - "Casework delegated staff authentication refused", - remedy = "check delegatedStaffReaders and authentication.oidc client, assertion, actor, scope and lifetime bindings" - ); - error - } - pub(crate) async fn authenticate_staff_read( &self, token: &str, policy_id: &str, source_profile: Option<&str>, ) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Casework delegated staff authentication refused" - ); - AuthenticationError::Refused - })?; - let binding = self.delegated_staff_readers.get(policy_id).ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - ) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| AuthenticationError::Refused(error.failed_check()))?; + let binding = self + .delegated_staff_readers + .get(policy_id) + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; let profile = self .profiles .get(&binding.profile) .filter(|profile| profile.acts_as == CaseworkActsAs::Staff) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - ) - })?; + .ok_or(AuthenticationError::Profile(FailedCheck::AccessProfile))?; if source_profile.is_some_and(|source| { !binding .source_profiles .iter() .any(|allowed| allowed == source) }) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Profile, - )); + return Err(AuthenticationError::Profile(FailedCheck::AccessProfile)); } - let matched_client = verified.matched_client_id().map_err(|_| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Client, - AuthenticationError::Refused, - ) - })?; - if matched_client != Some(binding.client.as_str()) - || verified - .claims - .extra - .get(ASSERTION_ISSUER_CLAIM) - .and_then(Value::as_str) - != Some(binding.assertion_issuer.as_str()) + let matched_client = verified + .matched_client_id() + .map_err(|_| AuthenticationError::Refused(FailedCheck::TokenClient))?; + if matched_client != Some(binding.client.as_str()) { + return Err(AuthenticationError::Refused(FailedCheck::TokenClient)); + } + if verified + .claims + .extra + .get(ASSERTION_ISSUER_CLAIM) + .and_then(Value::as_str) + != Some(binding.assertion_issuer.as_str()) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Client, - AuthenticationError::Refused, + return Err(AuthenticationError::Refused( + FailedCheck::TokenAssertionIssuer, )); } if verified @@ -252,10 +222,7 @@ impl CaseworkAuthenticator { .keys() .any(|key| key.starts_with("registry_grant_")) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Refused, - )); + return Err(AuthenticationError::Refused(FailedCheck::TaskGrantClaims)); } let audience = match verified.claims.aud.as_ref() { Some(Audience::One(audience)) if audience == &self.audience => audience.clone(), @@ -264,30 +231,19 @@ impl CaseworkAuthenticator { { audiences[0].clone() } - _ => { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Audience, - AuthenticationError::Refused, - )) - } + _ => return Err(AuthenticationError::Refused(FailedCheck::TokenAudience)), }; - let issuer = verified.claims.iss.as_deref().ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Issuer, - AuthenticationError::Refused, - ) - })?; + let issuer = verified + .claims + .iss + .as_deref() + .ok_or(AuthenticationError::Refused(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .as_deref() .filter(|subject| !subject.is_empty()) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Claims, - ) - })?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let expires_at = match (verified.claims.iat, verified.claims.exp) { (Some(issued_at), Some(expires_at)) if issued_at >= 0 @@ -298,21 +254,13 @@ impl CaseworkAuthenticator { { expires_at } - _ => { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Time, - AuthenticationError::Refused, - )) - } + _ => return Err(AuthenticationError::Refused(FailedCheck::TokenTime)), }; let act = strict_actor( verified.claims.extra.get("act"), issuer, &binding.actor_subject, - ) - .map_err(|error| { - self.delegated_staff_refusal(registry_platform_oidc::AuthenticationStage::Client, error) - })?; + )?; let actual_scopes = verified.scopes.iter().cloned().collect::>(); let mut expected_scopes = profile .required_scopes @@ -323,10 +271,14 @@ impl CaseworkAuthenticator { if !expected_scopes.is_subset(&actual_scopes) || actual_scopes.len() != verified.scopes.len() { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Scope, - AuthenticationError::Profile, - )); + self.declare_scope_refusal( + expected_scopes + .difference(&actual_scopes) + .next() + .map(String::as_str), + Some(&profile.id), + ); + return Err(AuthenticationError::Profile(FailedCheck::Scope)); } if verified .claims @@ -335,10 +287,7 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) != Some(self.human_identity.value.as_str()) { - return Err(self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::NotHuman, - )); + return Err(AuthenticationError::NotHuman(FailedCheck::ActorKind)); } let principal = if profile.principal_claim == "sub" { Some(subject) @@ -350,12 +299,7 @@ impl CaseworkAuthenticator { .and_then(Value::as_str) } .filter(|value| !value.is_empty()) - .ok_or_else(|| { - self.delegated_staff_refusal( - registry_platform_oidc::AuthenticationStage::Profile, - AuthenticationError::Claims, - ) - })?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(DelegatedStaffReader { actor: ActorContext { principal: IssuerPrincipal { @@ -388,20 +332,20 @@ fn strict_actor( ) -> Result<(String, String), AuthenticationError> { let object = value .and_then(Value::as_object) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::Delegation))?; if object.contains_key("act") { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); } if let Some(issuer) = object.get("iss") { if issuer.as_str() != Some(expected_issuer) { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused(FailedCheck::Delegation)); } } let subject = object .get("sub") .and_then(Value::as_str) .filter(|value| *value == expected_subject) - .ok_or(AuthenticationError::Refused)?; + .ok_or(AuthenticationError::Refused(FailedCheck::Delegation))?; Ok((expected_issuer.to_owned(), subject.to_owned())) } @@ -410,12 +354,14 @@ mod tests { use super::{delegated_audit_outcome, delegated_recheck}; use crate::audit::AuditOutcome; use crate::{ReviewRuntimeError, StoreError}; + use registry_platform_authcommon::FailedCheck; #[test] fn delegated_caller_refusals_are_not_audited_as_runtime_failures() { for error in [ - ReviewRuntimeError::Forbidden, + ReviewRuntimeError::Forbidden(FailedCheck::Operation), ReviewRuntimeError::NotFound, + ReviewRuntimeError::NotHeldByReader, ReviewRuntimeError::SourceProfileRequired, ReviewRuntimeError::ResultExpired, ReviewRuntimeError::Invalid, @@ -441,7 +387,7 @@ mod tests { Err(ReviewRuntimeError::NotFound) )); assert!(matches!( - delegated_recheck(Err(ReviewRuntimeError::Forbidden)), + delegated_recheck(Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation))), Err(ReviewRuntimeError::NotFound) )); assert!(matches!( diff --git a/crates/registry-casework/src/clocks.rs b/crates/registry-casework/src/clocks.rs index 2d9c47ee65..c36a22dbed 100644 --- a/crates/registry-casework/src/clocks.rs +++ b/crates/registry-casework/src/clocks.rs @@ -1,6 +1,7 @@ use crate::{CaseworkService, PostgresStore, ServiceError, StoreError}; use chrono::Utc; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use tokio_postgres::Transaction; @@ -13,7 +14,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result<(), StoreError> { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } if document.holiday_set.is_empty() || document.holiday_set.len() > 64 @@ -122,7 +123,7 @@ impl PostgresStore { &[&holiday_set, &revision], ) .await? - .ok_or(StoreError::NotFound)?; + .ok_or(StoreError::Absent)?; serde_json::from_value(row.get(0)).map_err(StoreError::Json) } } @@ -146,7 +147,7 @@ impl CaseworkService { revision: u64, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden.into()); + return Err(StoreError::Forbidden(FailedCheck::Operation).into()); } self.store .holiday_set(holiday_set, revision) diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 3945fa6251..213dc5f208 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -21,9 +21,11 @@ pub use registry_platform_config::{ OidcIssuerConfig, PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, }; +use registry_platform_httputil::loopback; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{escape_pointer_segment, Diagnostic, Report, RetiredApiVersion}; use serde::{Deserialize, Deserializer}; @@ -70,6 +72,14 @@ pub const CASEWORK_REMOVED_KEYS: &[RemovedKey] = &[ path: "audit.retainDays", replacement: "Rename audit.retainDays to audit.retentionDays", }, + RemovedKey { + path: "reviewCompletionDestinations.*.bearerTokenRef", + replacement: "Configure hmacSha256KeyRef with a Standard Webhooks signing key", + }, + RemovedKey { + path: "reviewCompletionDestinations.*.auth", + replacement: "Configure hmacSha256KeyRef with a Standard Webhooks signing key", + }, RemovedKey { path: "reviewCompletionDestinations.*.timeoutMilliseconds", replacement: "Rename timeoutMilliseconds to attemptTimeoutMilliseconds", @@ -334,13 +344,14 @@ where SecretReference::deserialize(deserializer).map(|reference| reference.as_str().to_owned()) } -/// An optional member holding a secret reference; absent reads as `None` -/// through `serde(default)`. -fn optional_secret_reference<'de, D>(deserializer: D) -> Result, D::Error> +pub(crate) const CURRENT_COMPLETION_KEY: &str = "hmacSha256KeyRef"; +pub(crate) const PREVIOUS_COMPLETION_KEY: &str = "previousHmacSha256KeyRef"; + +fn optional_secret_reference<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { - secret_reference(deserializer).map(Some) + SecretReference::deserialize(deserializer).map(Some) } fn valid_database_id(value: &str) -> bool { @@ -357,13 +368,11 @@ pub struct ReviewCompletionRuntimeConfig { #[serde(deserialize_with = "registry_casework_core::typed::url")] #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] pub url: String, - /// Shorthand for `auth` with no header: the secret is presented as - /// `Authorization: Bearer`. Exactly one of this and `auth` is configured. + /// Exact bytes of the current Standard Webhooks signing key. + pub hmac_sha256_key_ref: SecretReference, + /// Exact bytes of the previous signing key during rotation. #[serde(default, deserialize_with = "optional_secret_reference")] - #[cfg_attr(feature = "schema", schemars(with = "Option"))] - pub bearer_token_ref: Option, - #[serde(default)] - pub auth: Option, + pub previous_hmac_sha256_key_ref: Option, #[serde( default = "default_review_completion_timeout_ms", deserialize_with = "registry_casework_core::typed::bounded_u64::<_, MINIMUM_REVIEW_COMPLETION_TIMEOUT_MILLISECONDS, MAXIMUM_REVIEW_COMPLETION_TIMEOUT_MILLISECONDS>" @@ -402,136 +411,6 @@ pub struct ReviewCompletionRuntimeConfig { pub retry_delay_seconds: u64, } -/// How a completion destination presents its secret. Without `header` the -/// secret is sent as `Authorization: Bearer`; with one, the raw secret is the -/// value of that header and no `Authorization` header is sent. -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct ReviewCompletionAuthConfig { - #[serde(default)] - #[cfg_attr( - feature = "schema", - schemars(length(min = 1, max = MAXIMUM_REVIEW_COMPLETION_HEADER_NAME_BYTES)) - )] - pub header: Option, - #[serde(deserialize_with = "secret_reference")] - #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] - pub secret_ref: String, -} - -impl ReviewCompletionRuntimeConfig { - /// The secret reference this destination presents, when exactly one of - /// `bearerTokenRef` and `auth` names it. - #[must_use] - pub fn secret_ref(&self) -> Option<&str> { - match (&self.bearer_token_ref, &self.auth) { - (Some(reference), None) => Some(reference), - (None, Some(auth)) => Some(&auth.secret_ref), - _ => None, - } - } - - /// The header that carries the secret instead of `Authorization: Bearer`. - #[must_use] - pub fn secret_header(&self) -> Option<&str> { - self.auth.as_ref().and_then(|auth| auth.header.as_deref()) - } -} - -const MAXIMUM_REVIEW_COMPLETION_HEADER_NAME_BYTES: usize = 64; - -/// Header names a completion destination may not carry its secret in. -/// -/// Authentication, host and routing, cookie, framing, hop-by-hop, forwarding, -/// proxy, and tracing headers belong to the runtime or the operator's network -/// path, the same closed set Evidence refuses for its source headers. The -/// `idempotency-key` and `registry-` headers are the completion contract's own. -const RESERVED_REVIEW_COMPLETION_HEADER_NAMES: [&str; 39] = [ - "authorization", - "proxy-authorization", - "www-authenticate", - "proxy-authenticate", - "host", - "cookie", - "set-cookie", - "content-length", - "content-type", - "transfer-encoding", - "expect", - "connection", - "keep-alive", - "te", - "trailer", - "upgrade", - "proxy-connection", - "forwarded", - "via", - "x-real-ip", - "x-client-ip", - "x-cluster-client-ip", - "true-client-ip", - "cf-connecting-ip", - "fastly-client-ip", - "x-appengine-user-ip", - "x-azure-clientip", - "traceparent", - "tracestate", - "baggage", - "b3", - "x-cloud-trace-context", - "x-request-id", - "x-correlation-id", - "x-amzn-trace-id", - "x-original-url", - "x-rewrite-url", - "x-original-method", - "idempotency-key", -]; - -const RESERVED_REVIEW_COMPLETION_HEADER_PREFIXES: [&str; 8] = [ - "x-forwarded-", - "proxy-", - "sec-", - "x-b3-", - "x-envoy-", - "x-datadog-", - "x-http-method", - "registry-", -]; - -fn valid_review_completion_header_name(name: &str) -> bool { - let lower = name.to_ascii_lowercase(); - !name.is_empty() - && name.len() <= MAXIMUM_REVIEW_COMPLETION_HEADER_NAME_BYTES - && name.bytes().all(is_http_token_byte) - && !RESERVED_REVIEW_COMPLETION_HEADER_PREFIXES - .iter() - .any(|prefix| lower.starts_with(prefix)) - && !RESERVED_REVIEW_COMPLETION_HEADER_NAMES.contains(&lower.as_str()) -} - -fn is_http_token_byte(byte: u8) -> bool { - byte.is_ascii_alphanumeric() - || matches!( - byte, - b'!' | b'#' - | b'$' - | b'%' - | b'&' - | b'\'' - | b'*' - | b'+' - | b'-' - | b'.' - | b'^' - | b'_' - | b'`' - | b'|' - | b'~' - ) -} - fn default_review_completion_timeout_ms() -> u64 { 5_000 } @@ -884,7 +763,7 @@ impl RuntimeConfig { /// removed keys, and retired apiVersions. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(CASEWORK_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(CASEWORK_RUNTIME_ENVELOPE) .removed_keys(CASEWORK_REMOVED_KEYS) .retired_api_versions(CASEWORK_RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -1113,39 +992,39 @@ impl RuntimeConfig { } } } - for (destination_id, destination) in &self.review_completion_destinations { - match (&destination.bearer_token_ref, &destination.auth) { - (Some(reference), None) => { - references.push(( - vec![ - "reviewCompletionDestinations", - destination_id.as_str(), - "bearerTokenRef", - ], - reference.as_str(), - )); - } - (None, Some(auth)) => { - references.push(( - vec![ - "reviewCompletionDestinations", - destination_id.as_str(), - "auth", - "secretRef", - ], - auth.secret_ref.as_str(), - )); - } - _ => {} - } - } references } + fn completion_key_references(&self) -> impl Iterator { + self.review_completion_destinations + .iter() + .flat_map(|(id, destination)| { + [ + ( + CURRENT_COMPLETION_KEY, + Some(&destination.hmac_sha256_key_ref), + ), + ( + PREVIOUS_COMPLETION_KEY, + destination.previous_hmac_sha256_key_ref.as_ref(), + ), + ] + .into_iter() + .filter_map(move |(member, reference)| { + reference.map(|reference| { + ( + ["reviewCompletionDestinations", id.as_str(), member], + reference, + ) + }) + }) + }) + } + /// Resolve serving secrets without contacting their consumers or retaining /// their values. Migration credentials may remain off the serving host and - /// are resolved only by `caseworkctl apply`. This checks provider/file - /// availability and bounded secret text, not key formats or remote services. + /// are resolved only by `caseworkctl apply`. This checks provider and file + /// availability, bounded secret material, and completion signing key policy. pub fn check_runtime_secrets(&self, resolver: &SecretResolver) -> Result<(), Report> { let references = self.direct_secret_references() @@ -1169,6 +1048,33 @@ impl RuntimeConfig { )); } } + if let Err(errors) = crate::runtime::review_completion_targets( + &self.review_completion_destinations, + resolver, + ) { + use crate::runtime::CompletionKeyError; + + for error in errors { + let (field, code) = match &error { + CompletionKeyError::Unavailable { path, .. } => { + (path, "casework.runtime.secret-unavailable") + } + CompletionKeyError::Invalid { path, .. } + | CompletionKeyError::Repeated { second: path, .. } + | CompletionKeyError::PreviousEqualsCurrent { previous: path, .. } => { + (path, "casework.runtime.invalid-completion-key") + } + }; + let (section, field) = field.split_once('.').expect("completion key section"); + let (destination, member) = field.rsplit_once('.').expect("completion key member"); + diagnostics.push(Diagnostic::error( + code, + pointer_to(&[section, destination, member]), + error.to_string(), + "Retry doctor after correcting the completion signing key configuration.", + )); + } + } if diagnostics.is_empty() { Ok(()) } else { @@ -1190,31 +1096,8 @@ impl RuntimeConfig { for (segments, raw) in self.binding_secret_references() { self.check_binding_reference(findings, &segments, raw); } - for (destination_id, destination) in &self.review_completion_destinations { - let at = ["reviewCompletionDestinations", destination_id.as_str()]; - match (&destination.bearer_token_ref, &destination.auth) { - (Some(_), None) => {} - (None, Some(auth)) => { - if auth - .header - .as_deref() - .is_some_and(|header| !valid_review_completion_header_name(header)) - { - let segments = [at[0], at[1], "auth", "header"]; - findings.push(RuntimeConfigError::InvalidReviewCompletionAuth { - path: segments.join("."), - pointer: pointer_to(&segments), - }); - } - } - _ => { - let segments = [at[0], at[1], "auth"]; - findings.push(RuntimeConfigError::InvalidReviewCompletionAuth { - path: segments.join("."), - pointer: pointer_to(&segments), - }); - } - } + for (segments, reference) in self.completion_key_references() { + self.check_binding_reference(findings, &segments, reference.as_str()); } } @@ -1251,7 +1134,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { @@ -1395,7 +1278,7 @@ impl RuntimeConfig { findings.push(RuntimeConfigError::InvalidReviewCompletionDestination { path: segments.join("."), pointer: pointer_to(&segments), - reason: "must be an https URL with a host, or an http URL on 127.0.0.1 or [::1], without userinfo, query, or fragment", + reason: "must be an https URL with a host, or an http URL on a loopback literal (127.0.0.0/8, ::1 or ::ffff:127.0.0.0/104), without userinfo, query, or fragment", }); } } @@ -1730,7 +1613,7 @@ impl RuntimeConfig { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", @@ -1738,8 +1621,13 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = + parse_static_jwks(document.expose_secret()).map_err(|error| match error { + OidcError::StaticKeySet(refusal) => { + RuntimeConfigError::OidcJwksSecret(refusal.to_string()) + } + _ => RuntimeConfigError::Oidc, + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1906,7 +1794,9 @@ fn valid_review_completion_url(raw: &str) -> bool { } match url.scheme() { "https" => url.host_str().is_some(), - "http" => matches!(url.host_str(), Some("127.0.0.1" | "::1" | "[::1]")), + "http" => url + .host_str() + .is_some_and(|host| loopback::loopback_literal(host).is_some()), _ => false, } } @@ -2112,6 +2002,7 @@ fn stand_in_for(pointer: &str) -> &'static str { mod tests { use super::*; use jsonwebtoken::Algorithm; + use registry_platform_authcommon::FailedCheck; use registry_platform_config::write_package; use serde_json::json; @@ -2214,6 +2105,87 @@ mod tests { }) } + /// Resolve the verifier of a runtime file whose static key set is `document`. + async fn verifier_for_static_key_set( + document: &serde_json::Value, + ) -> Result<(), RuntimeConfigError> { + use std::os::unix::fs::PermissionsExt as _; + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = root.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = secrets.join("jwks"); + std::fs::write(&file, document.to_string()).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut value = operator_value(root.path(), root.path()); + value["authentication"]["oidc"]["jwksSource"] = + json!({"type":"static", "documentRef":"secret:file/jwks"}); + let config = read_operator(&value, root.path()); + let resolver = + SecretResolver::new([registry_platform_config::SecretProvider::File], &secrets) + .unwrap(); + config.oidc_verifier(&resolver).await.map(|_| ()) + } + + fn public_rsa_key(kid: &str) -> serde_json::Value { + json!({"kty":"RSA","kid":kid,"alg":"RS256","n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw","e":"AQAB"}) + } + + #[tokio::test] + async fn a_static_key_set_with_unknown_public_members_loads() { + let mut key = public_rsa_key("signing-1"); + key["ext"] = json!(true); + key["x5c"] = json!(["MIIB"]); + key["x5t"] = json!("thumbprint"); + key["use"] = json!("sig"); + key["key_ops"] = json!(["verify"]); + let mut encryption = public_rsa_key("encryption-1"); + encryption["use"] = json!("enc"); + let document = json!({"keys": [key, encryption], "issuer": "an unknown top-level member"}); + verifier_for_static_key_set(&document) + .await + .expect("members the validator does not name are ignored"); + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_its_text() { + let mut key = public_rsa_key("signing-1"); + key["d"] = json!("canary-private-exponent"); + let error = verifier_for_static_key_set(&json!({"keys": [key]})) + .await + .expect_err("a private member is refused"); + assert_eq!(error.code(), "casework.runtime.unreadable-jwks-secret"); + let rendered = error.to_string(); + assert!(rendered.contains("private-key member \"d\""), "{rendered}"); + assert!(!rendered.contains("canary"), "{rendered}"); + assert!(!rendered.contains("signing-1"), "{rendered}"); + } + + #[test] + fn a_review_completion_destination_may_use_http_only_on_a_loopback_address() { + for admitted in [ + "https://completion.example.test/reviews", + "http://127.0.0.1:9000/reviews", + "http://127.0.0.2/reviews", + "http://[::1]:9000/reviews", + "http://[::ffff:127.0.0.1]/reviews", + ] { + assert!(valid_review_completion_url(admitted), "{admitted}"); + } + for refused in [ + "http://localhost/reviews", + "http://LOCALHOST:9000/reviews", + "http://localhost./reviews", + "http://app.localhost/reviews", + "http://10.0.0.1/reviews", + "http://0.0.0.0/reviews", + "http://completion.example.test/reviews", + "http://127.0.0.1@example.test/reviews", + ] { + assert!(!valid_review_completion_url(refused), "{refused}"); + } + } + #[test] fn metrics_listener_wildcard_needs_container_private_exposure() { let directory = tempfile::tempdir().unwrap(); @@ -2574,10 +2546,10 @@ mod tests { let mut value = operator_value(directory.path(), directory.path()); value["authentication"]["oidc"]["revokedKeyIds"] = json!(["signing-1"]); let refused = verify_under_operator_profile(&value, "signing-1", 300).await; - assert!(matches!( - refused, - Err(crate::auth::AuthenticationError::Refused) - )); + assert_eq!( + refused.unwrap_err(), + crate::auth::AuthenticationError::Refused(FailedCheck::TokenKey) + ); verify_under_operator_profile(&value, "signing-2", 300) .await .expect("a key not on the list still verifies"); @@ -2592,10 +2564,10 @@ mod tests { .await .expect("a token within the bound verifies"); let refused = verify_under_operator_profile(&value, "signing-1", 301).await; - assert!(matches!( - refused, - Err(crate::auth::AuthenticationError::Refused) - )); + assert_eq!( + refused.unwrap_err(), + crate::auth::AuthenticationError::Refused(FailedCheck::TokenTime) + ); } #[test] @@ -2669,8 +2641,7 @@ mod tests { } }}); value["reviewCompletionDestinations"] = json!({ - "bearer":{"url":"https://completion.example.test/reviews","bearerTokenRef":"secret:file/bearer"}, - "header./receiver":{"url":"https://completion.example.test/reviews","auth":{"header":"x-api-key","secretRef":"secret:file/header"}} + "receiver./key":{"url":"https://completion.example.test/reviews","hmacSha256KeyRef":"secret:file/current","previousHmacSha256KeyRef":"secret:file/previous"} }); let config = read_operator(&value, root.path()); let resolver = SecretResolver::new( @@ -2696,8 +2667,8 @@ mod tests { "/contextProviders/facility/clientAssertionKeyRef", "/contextProviders/facility/delegatedDisplayExchange/clientIdRef", "/contextProviders/facility/delegatedDisplayExchange/clientAssertionKeyRef", - "/reviewCompletionDestinations/bearer/bearerTokenRef", - "/reviewCompletionDestinations/header.~1receiver/auth/secretRef" + "/reviewCompletionDestinations/receiver.~1key/hmacSha256KeyRef", + "/reviewCompletionDestinations/receiver.~1key/previousHmacSha256KeyRef" ] ); assert!(!report.render_human().contains("secret:file/")); @@ -3221,10 +3192,6 @@ pub enum RuntimeConfigError { pointer: String, reason: String, }, - #[error( - "{path} must name exactly one completion secret, in a header the runtime does not reserve" - )] - InvalidReviewCompletionAuth { path: String, pointer: String }, #[error("{path} {reason}")] InvalidReviewCompletionDestination { path: String, @@ -3280,7 +3247,6 @@ impl RuntimeConfigError { // Located by `pointer` itself. Self::Load(_) | Self::BindingSecret { .. } - | Self::InvalidReviewCompletionAuth { .. } | Self::InvalidReviewCompletionDestination { .. } | Self::InvalidContextProvider { .. } | Self::InvalidTaskAuthority { .. } @@ -3304,7 +3270,6 @@ impl RuntimeConfigError { match self { Self::Load(error) => error.deciding_diagnostic().path.clone(), Self::BindingSecret { pointer, .. } - | Self::InvalidReviewCompletionAuth { pointer, .. } | Self::InvalidReviewCompletionDestination { pointer, .. } | Self::InvalidContextProvider { pointer, .. } | Self::InvalidTaskAuthority { pointer, .. } @@ -3356,9 +3321,6 @@ impl RuntimeConfigError { Self::InvalidAuditDestination(_) => "casework.runtime.invalid-audit", Self::InvalidContextProviders => "casework.runtime.context-providers-mismatch", Self::InvalidContextProvider { .. } => "casework.runtime.invalid-context-provider", - Self::InvalidReviewCompletionAuth { .. } => { - "casework.runtime.invalid-review-completion-auth" - } Self::InvalidReviewCompletionDestination { .. } => { "casework.runtime.invalid-review-completion-destination" } @@ -3434,11 +3396,8 @@ impl RuntimeConfigError { Self::InvalidContextProvider { .. } => { "Correct the context provider member so it meets the rule the message names." } - Self::InvalidReviewCompletionAuth { .. } => { - "Configure exactly one of bearerTokenRef and auth.secretRef, and name in auth.header only a header the runtime does not reserve." - } Self::InvalidReviewCompletionDestination { .. } => { - "Give the destination a non-empty id and an https URL with a host, or an http URL on 127.0.0.1 or [::1] for local development." + "Give the destination a non-empty id and an https URL with a host, or an http URL on a loopback literal (127.0.0.0/8, ::1 or ::ffff:127.0.0.0/104) for local development." } Self::UnconfiguredReviewCompletionDestination => { "Add a reviewCompletionDestinations entry for each destination casework.yaml trustedProducers.PRODUCER_ID.completion.destinationId names." diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 4eab6c496a..0db408d148 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -1,6 +1,7 @@ use registry_casework_core::DirectoryTeamUpdateRequest; use std::sync::Arc; +use crate::auth::DECLARED_SCOPE; use axum::body::Bytes; use axum::extract::{FromRequest, Path, Query, Request, State}; use axum::http::header::{ @@ -12,11 +13,15 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; use registry_casework_core::*; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, +}; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use serde_json::error::Category; use uuid::Uuid; @@ -78,6 +83,13 @@ pub struct HttpState { } pub fn router(state: HttpState) -> Router { + router_with_recorder(state, crate::metrics::refusal_recorder()) +} + +/// The router, counting and logging every refusal through `recorder`. A test +/// passes its own recorder to read what a request counted. A service uses +/// [`router`], whose recorder feeds the metrics scrape. +pub fn router_with_recorder(state: HttpState, recorder: Arc) -> Router { let review = Router::new() .route("/v1/review-requests", post(create_review_request)) .route("/v1/review-results", get(review_result_feed)) @@ -91,8 +103,8 @@ pub fn router(state: HttpState) -> Router { post(cancel_review_request), ); let app = Router::new() - .route("/health", get(health)) - .route("/ready", get(ready)) + .route(HEALTH_PATH, get(health)) + .route(READY_PATH, get(ready)) .route("/v1/casework", get(description)) .route("/.well-known/jwks.json", get(task_jwks)) .route("/v1/task-grants/{grant_id}/assertion", post(task_assertion)) @@ -204,16 +216,29 @@ pub fn router(state: HttpState) -> Router { post(preview_caseload_move), ) .route("/v1/directory/caseload/apply", post(apply_caseload_move)); - http_edge(app, Some(state.clone())) + http_edge_recording(app, Some(state.clone()), Arc::clone(&recorder)) .merge(contract_edge( review, HttpContract::Review, Some(state.clone()), + recorder, )) .with_state(state) } +#[cfg(test)] fn http_edge(router: Router, source_state: Option) -> Router +where + S: Clone + Send + Sync + 'static, +{ + http_edge_recording(router, source_state, crate::metrics::refusal_recorder()) +} + +fn http_edge_recording( + router: Router, + source_state: Option, + recorder: Arc, +) -> Router where S: Clone + Send + Sync + 'static, { @@ -221,6 +246,7 @@ where router.fallback(route_not_found), HttpContract::Casework, source_state, + recorder, ) } @@ -228,6 +254,7 @@ fn contract_edge( router: Router, contract: HttpContract, source_state: Option, + recorder: Arc, ) -> Router where S: Clone + Send + Sync + 'static, @@ -243,12 +270,35 @@ where } else { router }; + // The one recording point: it sits outside the admission layer, so a + // refusal from either is counted once, inside the request's trace scope. router + .layer(middleware::from_fn_with_state(recorder, record_refusals)) .layer(request_body_limit_default()) .layer(middleware::from_fn(move |request, next| { http_boundary(contract, request, next) })) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) +} + +/// Counts and logs the refusal a response carries in its extensions. The +/// extension is never serialized, so the answer's bytes are unchanged. +async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + let declared = response.extensions().get::(); + match REQUEST_TRACE.try_with(|trace| trace.trace_id.clone()) { + Ok(trace_id) => { + record_refusal!(recorder, note, trace_id = &trace_id, declared = declared) + } + Err(_) => record_refusal!(recorder, note, declared = declared), + } + } + response } async fn http_boundary( @@ -261,10 +311,14 @@ async fn http_boundary( .scope(trace.clone(), async move { REQUEST_CONTRACT .scope(contract, async move { - normalize_framework_rejection( - next.run(request).await, - framework_rejection_problem, - ) + DECLARED_SCOPE + .scope(std::cell::RefCell::new(None), async move { + normalize_framework_rejection( + next.run(request).await, + framework_rejection_problem, + ) + }) + .await }) .await }) @@ -468,13 +522,17 @@ async fn method_not_allowed() -> Response { problem_response(ProblemCode::RequestMethodNotAllowed, None, None) } -async fn health() -> StatusCode { - StatusCode::OK +fn probe_response(body: &'static str) -> Response { + ([(CONTENT_TYPE, "application/json")], body).into_response() } -async fn ready(RequestState(state): RequestState) -> Result { +async fn health() -> Response { + probe_response(HEALTH_BODY) +} + +async fn ready(RequestState(state): RequestState) -> Result { if state.service.ready().await.is_ok() { - Ok(StatusCode::OK) + Ok(probe_response(READY_BODY)) } else { Err(HttpError::ServiceUnavailable) } @@ -792,7 +850,7 @@ async fn get_review_result( Ok(ReviewResultRead::Available(result)) => Ok(Json(result).into_response()), Ok(ReviewResultRead::Pending) => Ok(StatusCode::ACCEPTED.into_response()), Ok(ReviewResultRead::Expired) => Ok(StatusCode::GONE.into_response()), - Err(ReviewRuntimeError::NotFound) => Ok(StatusCode::NOT_FOUND.into_response()), + Err(ReviewRuntimeError::NotFound) => Ok(bare_not_found()), Err(error) => Err(HttpError::from(error)), } } @@ -914,6 +972,15 @@ async fn delegate_review_task( )) } +/// A 404 with no body, counted as a concealed target. +fn bare_not_found() -> Response { + let mut response = StatusCode::NOT_FOUND.into_response(); + response + .extensions_mut() + .insert(RefusalNote::new(FailedCheck::Visibility)); + response +} + async fn get_review_task_draft( RequestState(state): RequestState, headers: HeaderMap, @@ -927,6 +994,8 @@ async fn get_review_task_draft( .await? { Some(draft) => Ok(Json(draft).into_response()), + // No saved draft on a task the reviewer may read is absence, not a + // refusal, so it is not counted. None => Ok(StatusCode::NOT_FOUND.into_response()), } } @@ -1432,18 +1501,14 @@ async fn task_client( ) -> Result { if headers.contains_key(CASEWORK_PROFILE_HEADER) || headers.contains_key(SOURCE_PROFILE_HEADER) { - return Err(HttpError::AuthenticationRefused); + return Err(HttpError::AuthenticationRefused(FailedCheck::AccessProfile)); } - let raw = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = parse_bearer_token(raw).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; state .authenticator .authenticate_task_client(token, scope, kind) .await - .map_err(|_| HttpError::AuthenticationRefused) + .map_err(|error| HttpError::AuthenticationRefused(error.failed_check())) } async fn task_assertion( RequestState(state): RequestState, @@ -1482,23 +1547,13 @@ async fn authenticate<'a>( state: &HttpState, headers: &'a HeaderMap, ) -> Result<(registry_casework_core::ActorContext, &'a str), HttpError> { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = - parse_bearer_token(authorization).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; let profile = profile_header(headers, HttpContract::current().profile_header())?; let actor = state .authenticator .authenticate(token, profile) .await - .map_err(|error| match error { - AuthenticationError::Refused => HttpError::AuthenticationRefused, - AuthenticationError::Profile => HttpError::ProfileNotAuthorized, - AuthenticationError::NotHuman => HttpError::ProfileNotHuman, - AuthenticationError::Claims => HttpError::AuthenticationRefused, - })?; + .map_err(HttpError::from)?; Ok((actor, token)) } @@ -1508,33 +1563,39 @@ async fn authenticate_delegated_staff_read<'a>( source_profile: Option<&str>, ) -> Result<(crate::auth::delegated::DelegatedStaffReader, &'a str), HttpError> { if headers.contains_key(CASEWORK_PROFILE_HEADER) { - return Err(HttpError::ProfileNotAuthorized); + return Err(HttpError::ProfileNotAuthorized(FailedCheck::AccessProfile)); } - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or_else(|| header_authentication_refused(state))?; - let token = - parse_bearer_token(authorization).map_err(|_| header_authentication_refused(state))?; + let token = bearer_credential(headers)?; let policy = profile_header(headers, DELEGATED_READER_HEADER)?; let reader = state .authenticator .authenticate_staff_read(token, policy, source_profile) .await - .map_err(|error| match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError::AuthenticationRefused - } - AuthenticationError::Profile | AuthenticationError::NotHuman => { - HttpError::ProfileNotAuthorized - } - })?; + .map_err(HttpError::DelegatedStaff)?; Ok((reader, token)) } -fn header_authentication_refused(state: &HttpState) -> HttpError { - state.authenticator.record_header_refusal(); - HttpError::AuthenticationRefused +/// The bearer token of a request, or the refusal that names why there is +/// none: no header, a scheme other than Bearer, or a value that is not a +/// well-formed bearer credential. +fn bearer_credential(headers: &HeaderMap) -> Result<&str, HttpError> { + let Some(value) = headers.get(AUTHORIZATION) else { + return Err(HttpError::AuthenticationRefused( + FailedCheck::CredentialMissing, + )); + }; + let value = value + .to_str() + .map_err(|_| HttpError::AuthenticationRefused(FailedCheck::CredentialMalformed))?; + parse_bearer_token(value).map_err(bearer_refusal) +} + +/// The refusal for an `Authorization` value that is not a bearer credential. +fn bearer_refusal(error: BearerParseError) -> HttpError { + HttpError::AuthenticationRefused(match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn source_profile(headers: &HeaderMap) -> Result<&str, HttpError> { @@ -1638,11 +1699,19 @@ fn if_match_with_minimum(headers: &HeaderMap, minimum: i64) -> Result for HttpError { fn from(e: StoreError) -> Self { match e { @@ -1676,8 +1748,9 @@ impl From for HttpError { StoreError::CursorExpired => Self::CursorExpired, StoreError::CursorInvalid => Self::CursorInvalid, StoreError::IdempotencyExpired => Self::IdempotencyExpired, - StoreError::NotFound => Self::NotFound, - StoreError::Forbidden => Self::Forbidden, + StoreError::NotFound => Self::NotFound(FailedCheck::Visibility), + StoreError::Absent => Self::Absent, + StoreError::Forbidden(check) => Self::Forbidden(check), StoreError::Conflict => Self::PreconditionFailed, StoreError::AlreadyClaimed | StoreError::NotHolder => Self::ReviewTaskNotHeld, StoreError::IdempotencyConflict => Self::IdempotencyKeyReused, @@ -1696,8 +1769,9 @@ impl From for HttpError { fn from(e: ServiceError) -> Self { match e { ServiceError::Store(e) => e.into(), - ServiceError::NotFound => Self::NotFound, - ServiceError::Forbidden => Self::Forbidden, + ServiceError::NotFound(check) => Self::NotFound(check), + ServiceError::Absent => Self::Absent, + ServiceError::Forbidden(check) => Self::Forbidden(check), ServiceError::ReviewValidation(e) => Self::Validation(e), ServiceError::Configuration => Self::Internal, ServiceError::Context(ReviewContextError::VersionMismatch) => { @@ -1710,15 +1784,16 @@ impl From for HttpError { ServiceError::Context( ReviewContextError::Invalid | ReviewContextError::Unsupported, ) => Self::SourceBadGateway, - ServiceError::Context(_) => Self::NotFound, + ServiceError::Context(_) => Self::NotFound(FailedCheck::Visibility), } } } impl From for HttpError { fn from(e: ReviewRuntimeError) -> Self { match e { - ReviewRuntimeError::NotFound => Self::NotFound, - ReviewRuntimeError::Forbidden => Self::Forbidden, + ReviewRuntimeError::NotFound => Self::NotFound(FailedCheck::Visibility), + ReviewRuntimeError::NotHeldByReader => Self::NotFound(FailedCheck::Ownership), + ReviewRuntimeError::Forbidden(check) => Self::Forbidden(check), ReviewRuntimeError::SubmissionConflict => Self::ReviewSubmissionConflict, ReviewRuntimeError::ResultExpired => Self::ReviewResultExpired, ReviewRuntimeError::TaskNotHeld => Self::ReviewTaskNotHeld, @@ -1746,14 +1821,107 @@ impl From for HttpError { } } } +impl From for HttpError { + fn from(error: AuthenticationError) -> Self { + match error { + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + Self::AuthenticationRefused(check) + } + AuthenticationError::Profile(check) => Self::ProfileNotAuthorized(check), + AuthenticationError::NotHuman(check) => Self::ProfileNotHuman(check), + } + } +} + +/// Operator hint on a scope refusal. +const SCOPE_REMEDY: &str = "check authentication.oidc.scopeClaim and accessProfiles requiredScopes"; +/// Operator hint on a refusal of the selected profile or of a person's session. +const PROFILE_REMEDY: &str = + "check selected accessProfiles and authentication.oidc.humanIdentity profile category"; +/// Operator hint on a delegated staff read refused by its configured bindings. +const DELEGATED_STAFF_REMEDY: &str = "check delegatedStaffReaders and authentication.oidc client, assertion, actor, scope and lifetime bindings"; + impl HttpError { + /// The check a refused request failed, for the operator's counter and + /// log line. `None` for an answer that is not an authentication or + /// authorization refusal. Never written to a response. + #[deny(clippy::wildcard_enum_match_arm)] + fn failed_check(&self) -> Option { + match self { + Self::AuthenticationRefused(check) + | Self::ProfileNotAuthorized(check) + | Self::ProfileNotHuman(check) + | Self::Forbidden(check) + | Self::NotFound(check) => Some(*check), + Self::DelegatedStaff(error) => Some(error.failed_check()), + Self::ReviewDistinctApproverRequired | Self::ReviewInitiatorExcluded => { + Some(FailedCheck::SeparationOfDuties) + } + Self::Absent + | Self::PreconditionFailed + | Self::PreconditionRequired + | Self::IdempotencyKeyReused + | Self::IdempotencyExpired + | Self::Invalid + | Self::LimitOutOfRange + | Self::ServiceUnavailable + | Self::SourceProfileNotApplicable + | Self::SourceProfileRequired + | Self::SourceBadGateway + | Self::SourceVersionMismatch + | Self::SourceVersionUnavailable + | Self::ReviewInitiatorRequired + | Self::ReviewResultExpired + | Self::ReviewSubmissionConflict + | Self::ReviewTaskNotHeld + | Self::ReviewPolicyMismatch + | Self::ReviewQueryTooBroad + | Self::CursorInvalid + | Self::CursorExpired + | Self::Absence(_) + | Self::Internal + | Self::Validation(_) => None, + } + } + + /// The fixed operator hint that goes with the refusal, if there is one. + fn remedy(&self) -> Option<&'static str> { + match self { + Self::ProfileNotAuthorized(FailedCheck::Scope) => Some(SCOPE_REMEDY), + Self::ProfileNotAuthorized(FailedCheck::AccessProfile) + | Self::ProfileNotHuman(FailedCheck::ActorKind) => Some(PROFILE_REMEDY), + Self::DelegatedStaff(error) => matches!( + error.failed_check(), + FailedCheck::AccessProfile + | FailedCheck::TokenAssertionIssuer + | FailedCheck::TokenClient + | FailedCheck::TaskGrantClaims + | FailedCheck::TokenAudience + | FailedCheck::TokenClaims + | FailedCheck::Delegation + | FailedCheck::Scope + | FailedCheck::ActorKind + ) + .then_some(DELEGATED_STAFF_REMEDY), + _ => None, + } + } + fn problem(&self) -> ProblemCode { match self { - Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, - Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, - Self::ProfileNotHuman => ProblemCode::ProfileNotHuman, - Self::Forbidden => ProblemCode::OperationNotAuthorized, - Self::NotFound => ProblemCode::RequestNotFound, + Self::AuthenticationRefused(_) => ProblemCode::AuthenticationRefused, + Self::ProfileNotAuthorized(_) => ProblemCode::ProfileNotAuthorized, + Self::ProfileNotHuman(_) => ProblemCode::ProfileNotHuman, + Self::DelegatedStaff(error) => match error { + AuthenticationError::Refused(_) | AuthenticationError::Claims(_) => { + ProblemCode::AuthenticationRefused + } + AuthenticationError::Profile(_) | AuthenticationError::NotHuman(_) => { + ProblemCode::ProfileNotAuthorized + } + }, + Self::Forbidden(_) => ProblemCode::OperationNotAuthorized, + Self::NotFound(_) | Self::Absent => ProblemCode::RequestNotFound, Self::PreconditionFailed => ProblemCode::PreconditionFailed, Self::PreconditionRequired => ProblemCode::PreconditionRequired, Self::IdempotencyKeyReused => ProblemCode::IdempotencyKeyReused, @@ -1792,14 +1960,67 @@ impl IntoResponse for HttpError { Self::Validation(v) => Some(v), _ => None, }; - problem_response(self.problem(), None, validation) + let note = self.failed_check().map(|check| { + let note = RefusalNote::new(check); + match self.remedy() { + Some(remedy) => note.with_remedy(remedy), + None => note, + } + }); + match note { + Some(note) => { + let mut response = refusal_response(self.problem(), note, validation); + let declared = DECLARED_SCOPE + .try_with(|slot| slot.borrow().clone()) + .ok() + .flatten(); + if let Some(declared) = declared.filter(|_| note.check == FailedCheck::Scope) { + response.extensions_mut().insert(declared); + } + response + } + None => problem_response(self.problem(), None, validation), + } } } +/// A refusal of authority, with the check it failed. The note reaches the +/// operator's counter and log line through the response extensions and never +/// the caller's body. +fn refusal_response( + problem: ProblemCode, + note: RefusalNote, + validation: Option<&ReviewValidationError>, +) -> Response { + let mut response = build_problem_response(problem, validation); + response.extensions_mut().insert(note); + response +} + +/// An answer that is not a refusal of authority. A 401 or 403 is built with +/// [`refusal_response`] so it names its check. One arriving here is a defect: +/// it is answered unchanged and logged once, and a debug build stops. fn problem_response( problem: ProblemCode, _attempt_reference: Option, validation: Option<&ReviewValidationError>, +) -> Response { + if matches!( + problem.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.code(), + "a refusal was answered without its failed check" + ); + } + build_problem_response(problem, validation) +} + +fn build_problem_response( + problem: ProblemCode, + validation: Option<&ReviewValidationError>, ) -> Response { let trace = REQUEST_TRACE .try_with(Clone::clone) @@ -1950,6 +2171,7 @@ mod tests { Router::new().route("/review", post(selected_profile)), HttpContract::Review, None, + crate::metrics::refusal_recorder(), ), ); for (path, selected, other, base) in [ @@ -2053,6 +2275,7 @@ mod tests { ), HttpContract::Review, None, + crate::metrics::refusal_recorder(), ); for (method, path, media, body, expected) in [ ( @@ -2409,7 +2632,9 @@ mod tests { .route( "/authentication", axum::routing::get(|| async { - Err::(HttpError::AuthenticationRefused) + Err::(HttpError::AuthenticationRefused( + FailedCheck::TokenSignature, + )) }), ) .route( @@ -2644,4 +2869,396 @@ mod tests { ); } } + + fn refusing_router(recorder: Arc) -> Router { + let answer = |error: fn() -> HttpError| { + axum::routing::get(move || async move { Err::(error()) }) + }; + http_edge_recording( + Router::new() + .route( + "/signature", + answer(|| HttpError::AuthenticationRefused(FailedCheck::TokenSignature)), + ) + .route( + "/scope", + answer(|| HttpError::ProfileNotAuthorized(FailedCheck::Scope)), + ) + .route( + "/not-human", + answer(|| HttpError::ProfileNotHuman(FailedCheck::ActorKind)), + ) + .route( + "/delegated", + answer(|| { + HttpError::DelegatedStaff(AuthenticationError::Profile( + FailedCheck::AccessProfile, + )) + }), + ) + .route( + "/forbidden", + answer(|| HttpError::Forbidden(FailedCheck::Operation)), + ) + .route( + "/concealed", + answer(|| HttpError::NotFound(FailedCheck::Visibility)), + ) + .route( + "/distinct", + answer(|| HttpError::ReviewDistinctApproverRequired), + ) + .route("/excluded", answer(|| HttpError::ReviewInitiatorExcluded)) + .route("/absent", answer(|| HttpError::Absent)) + .route("/invalid", answer(|| HttpError::Invalid)) + .route("/outage", answer(|| HttpError::ServiceUnavailable)), + None, + recorder, + ) + } + + async fn refused(app: &Router, path: &str) -> StatusCode { + app.clone() + .oneshot( + Request::builder() + .uri(path) + .header("traceparent", TRACEPARENT) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response") + .status() + } + + fn recorder() -> Arc { + Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")) + } + + #[test] + fn store_service_and_review_refusals_keep_the_check_their_producer_named() { + for check in [ + FailedCheck::Operation, + FailedCheck::AccessProfile, + FailedCheck::SeparationOfDuties, + FailedCheck::TaskGrantExpired, + FailedCheck::TaskGrantStatus, + FailedCheck::RequesterClient, + ] { + assert_eq!( + HttpError::from(StoreError::Forbidden(check)).failed_check(), + Some(check) + ); + assert_eq!( + HttpError::from(ServiceError::Forbidden(check)).failed_check(), + Some(check) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::Forbidden(check)).failed_check(), + Some(check) + ); + } + for check in [FailedCheck::TaskGrantBinding, FailedCheck::AccessProfile] { + assert_eq!( + HttpError::from(ServiceError::NotFound(check)).failed_check(), + Some(check) + ); + } + assert_eq!(HttpError::from(StoreError::Absent).failed_check(), None); + assert_eq!(HttpError::from(ServiceError::Absent).failed_check(), None); + assert_eq!( + HttpError::from(StoreError::NotFound).failed_check(), + Some(FailedCheck::Visibility) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::NotHeldByReader).failed_check(), + Some(FailedCheck::Ownership) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::NotFound).failed_check(), + Some(FailedCheck::Visibility) + ); + assert_eq!( + HttpError::from(ReviewRuntimeError::NotHeldByReader).problem(), + ProblemCode::RequestNotFound + ); + } + + #[tokio::test] + async fn a_bare_not_found_is_empty_and_counted_as_concealed() { + let response = bare_not_found(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.extensions().get::().map(|n| n.check), + Some(FailedCheck::Visibility) + ); + let body = axum::body::to_bytes(response.into_body(), 1024) + .await + .unwrap(); + assert!(body.is_empty()); + } + + #[tokio::test] + async fn each_refusal_is_counted_once_under_its_own_check() { + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + for (path, status, check) in [ + ("/signature", 401, "token-signature"), + ("/scope", 403, "scope"), + ("/not-human", 403, "actor-kind"), + ("/delegated", 403, "access-profile"), + ("/forbidden", 403, "operation"), + ("/concealed", 404, "visibility"), + ("/distinct", 403, "separation-of-duties"), + ("/excluded", 403, "separation-of-duties"), + ] { + let before = recorder.counter().get(&[check]).expect("a declared check"); + assert_eq!(refused(&app, path).await.as_u16(), status, "{path}"); + assert_eq!( + recorder.counter().get(&[check]), + Some(before + 1), + "{path} counts under {check}" + ); + } + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 8, "no other check moved"); + } + + #[tokio::test] + async fn an_answer_that_is_not_a_refusal_is_not_counted() { + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + assert_eq!(refused(&app, "/invalid").await, StatusCode::BAD_REQUEST); + assert_eq!( + refused(&app, "/outage").await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!(refused(&app, "/unrouted").await, StatusCode::NOT_FOUND); + assert_eq!(refused(&app, "/absent").await, StatusCode::NOT_FOUND); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 0); + } + + /// Every answer that refuses a caller's credential or authority carries a + /// check, so the operator's counter sees it. A variant that answers 401 or + /// 403 and names no check fails here. + #[test] + fn every_unauthorized_or_forbidden_answer_names_a_check() { + use registry_casework_core::AbsenceError; + let check = FailedCheck::Operation; + let answers = [ + HttpError::AuthenticationRefused(check), + HttpError::ProfileNotAuthorized(check), + HttpError::ProfileNotHuman(check), + HttpError::DelegatedStaff(AuthenticationError::Refused(check)), + HttpError::DelegatedStaff(AuthenticationError::Claims(check)), + HttpError::DelegatedStaff(AuthenticationError::Profile(check)), + HttpError::DelegatedStaff(AuthenticationError::NotHuman(check)), + HttpError::Forbidden(check), + HttpError::NotFound(check), + HttpError::Absent, + HttpError::PreconditionFailed, + HttpError::PreconditionRequired, + HttpError::IdempotencyKeyReused, + HttpError::IdempotencyExpired, + HttpError::Invalid, + HttpError::LimitOutOfRange, + HttpError::ServiceUnavailable, + HttpError::SourceProfileNotApplicable, + HttpError::SourceProfileRequired, + HttpError::SourceBadGateway, + HttpError::SourceVersionMismatch, + HttpError::SourceVersionUnavailable, + HttpError::ReviewDistinctApproverRequired, + HttpError::ReviewInitiatorExcluded, + HttpError::ReviewInitiatorRequired, + HttpError::ReviewResultExpired, + HttpError::ReviewSubmissionConflict, + HttpError::ReviewTaskNotHeld, + HttpError::ReviewPolicyMismatch, + HttpError::ReviewQueryTooBroad, + HttpError::CursorInvalid, + HttpError::CursorExpired, + HttpError::Absence(AbsenceError::SelfCover), + HttpError::Internal, + ]; + for answer in answers { + let status = answer.problem().status(); + if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN { + assert!( + answer.failed_check().is_some(), + "{answer:?} answers {status} and names no check" + ); + } + } + } + + /// Every code answered as a 401 or 403 is built with its check. The list + /// comes from the code catalogue, so a code added later is covered. + #[test] + fn every_refusal_code_is_built_with_its_check() { + let refusals: Vec = ProblemCode::ALL + .iter() + .copied() + .filter(|code| { + matches!( + code.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) + }) + .collect(); + assert!(refusals.len() >= 4, "the catalogue lists its refusals"); + for code in refusals { + let response = refusal_response(code, RefusalNote::new(FailedCheck::Operation), None); + assert_eq!(response.status(), code.status()); + assert!(response.extensions().get::().is_some()); + } + } + + #[cfg(debug_assertions)] + #[test] + fn a_refusal_built_without_its_check_stops_a_debug_build() { + for code in ProblemCode::ALL.iter().copied().filter(|code| { + matches!( + code.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) + }) { + let outcome = std::panic::catch_unwind(|| problem_response(code, None, None)); + assert!( + outcome.is_err(), + "{} was built without a check", + code.code() + ); + } + } + + #[tokio::test] + async fn a_refusal_logs_one_value_free_line_with_its_check_remedy_and_trace() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let app = refusing_router(recorder()); + let captured = CapturedDiagnosticLogs::default(); + let subscriber = captured.subscriber(); + for path in ["/scope", "/delegated", "/signature"] { + refused(&app, path) + .with_subscriber(subscriber.clone()) + .await; + } + let lines: Vec = captured + .text() + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON log line")) + .collect(); + assert_eq!(lines.len(), 3, "{}", captured.text()); + for (line, check, remedy) in [ + (&lines[0], "scope", Some(SCOPE_REMEDY)), + (&lines[1], "access-profile", Some(DELEGATED_STAFF_REMEDY)), + (&lines[2], "token-signature", None), + ] { + let fields = &line["fields"]; + assert_eq!(fields["message"], "request refused"); + assert_eq!(fields["decision"], "refused"); + assert_eq!(fields["failed_check"], check); + assert_eq!(fields["suppressed"], 0); + assert_eq!(fields["trace_id"], "0123456789abcdef0123456789abcdef"); + assert_eq!( + fields.get("remedy").and_then(|value| value.as_str()), + remedy + ); + assert_eq!( + fields.as_object().expect("fields").len(), + if remedy.is_some() { 6 } else { 5 }, + "{line}" + ); + } + } + + #[tokio::test] + async fn a_flood_of_one_check_logs_five_lines_and_counts_every_refusal() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let recorder = recorder(); + let app = refusing_router(Arc::clone(&recorder)); + let captured = CapturedDiagnosticLogs::default(); + let subscriber = captured.subscriber(); + for _ in 0..20 { + refused(&app, "/signature") + .with_subscriber(subscriber.clone()) + .await; + } + assert_eq!(recorder.counter().get(&["token-signature"]), Some(20)); + assert_eq!(captured.text().lines().count(), 5, "{}", captured.text()); + } + + #[test] + fn an_authentication_error_maps_to_the_answer_it_always_had() { + for (error, problem) in [ + ( + AuthenticationError::Refused(FailedCheck::TokenKey), + ProblemCode::AuthenticationRefused, + ), + ( + AuthenticationError::Claims(FailedCheck::TokenClaims), + ProblemCode::AuthenticationRefused, + ), + ( + AuthenticationError::Profile(FailedCheck::Scope), + ProblemCode::ProfileNotAuthorized, + ), + ( + AuthenticationError::NotHuman(FailedCheck::ActorKind), + ProblemCode::ProfileNotHuman, + ), + ] { + assert_eq!(HttpError::from(error).problem(), problem); + } + // The delegated staff read answers a person's refusal as a profile one. + assert_eq!( + HttpError::DelegatedStaff(AuthenticationError::NotHuman(FailedCheck::ActorKind)) + .problem(), + ProblemCode::ProfileNotAuthorized + ); + } + + #[test] + fn a_bearer_header_is_missing_when_absent_or_not_bearer_and_malformed_otherwise() { + let check = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert(AUTHORIZATION, value.parse().expect("a header value")); + } + match bearer_credential(&headers) { + Err(HttpError::AuthenticationRefused(check)) => check, + other => panic!("expected a refusal, got {other:?}"), + } + }; + assert_eq!(check(None), FailedCheck::CredentialMissing); + assert_eq!(check(Some("Basic abc")), FailedCheck::CredentialMissing); + assert_eq!(check(Some("Bearer")), FailedCheck::CredentialMalformed); + assert_eq!(check(Some("Bearer a b")), FailedCheck::CredentialMalformed); + assert_eq!(check(Some("Bearer a")), FailedCheck::CredentialMalformed); + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, "Bearer token".parse().unwrap()); + assert_eq!(bearer_credential(&headers).unwrap(), "token"); + let mut unreadable = HeaderMap::new(); + unreadable.insert( + AUTHORIZATION, + axum::http::HeaderValue::from_bytes(b"Bearer \xff").unwrap(), + ); + assert!(matches!( + bearer_credential(&unreadable), + Err(HttpError::AuthenticationRefused( + FailedCheck::CredentialMalformed + )) + )); + } } diff --git a/crates/registry-casework/src/http/source_credentials.rs b/crates/registry-casework/src/http/source_credentials.rs index 59c09335c3..a94277ff8b 100644 --- a/crates/registry-casework/src/http/source_credentials.rs +++ b/crates/registry-casework/src/http/source_credentials.rs @@ -126,12 +126,15 @@ pub(super) async fn boundary( /// answers as not found. fn conceal_target_error(target: Target, error: HttpError) -> HttpError { match (target, error) { - ( - Target::Task(_) | Target::Request(_), - HttpError::AuthenticationRefused - | HttpError::NotFound - | HttpError::SourceProfileNotApplicable, - ) => HttpError::NotFound, + (Target::Task(_) | Target::Request(_), HttpError::NotFound(check)) => { + HttpError::NotFound(check) + } + (Target::Task(_) | Target::Request(_), HttpError::AuthenticationRefused(check)) => { + HttpError::NotFound(check) + } + (Target::Task(_) | Target::Request(_), HttpError::SourceProfileNotApplicable) => { + HttpError::NotFound(FailedCheck::Visibility) + } (_, error) => error, } } @@ -148,9 +151,9 @@ async fn admit( ) -> Result, HttpError> { let target = target(method, path).ok_or(HttpError::Invalid)?; let source = parse_bearer_token(single_header(headers, SOURCE_AUTHORIZATION_HEADER)?) - .map_err(|_| HttpError::AuthenticationRefused)?; + .map_err(bearer_refusal)?; registry_platform_authcommon::validate_compact_access_token(source) - .map_err(|_| HttpError::AuthenticationRefused)?; + .map_err(|_| HttpError::AuthenticationRefused(FailedCheck::CredentialMalformed))?; single_header(headers, AUTHORIZATION.as_str())?; single_header(headers, CASEWORK_PROFILE_HEADER)?; if !headers.contains_key(SOURCE_PROFILE_HEADER) { @@ -162,7 +165,7 @@ async fn admit( } let (actor, primary) = authenticate(state, headers).await?; if actor.role == CaseworkActsAs::Requester { - return Err(HttpError::ProfileNotAuthorized); + return Err(HttpError::ProfileNotAuthorized(FailedCheck::AccessProfile)); } let Some(provider) = state .service @@ -186,12 +189,13 @@ async fn admit( .authenticator .verify_human_source_pair(primary, source, &provider) .await - .map_err(|_| conceal_target_error(target, HttpError::AuthenticationRefused))?; - let original = state - .service - .providers - .get(&provider) - .ok_or_else(|| conceal_target_error(target, HttpError::AuthenticationRefused))?; + .map_err(|error| conceal_target_error(target, error.into()))?; + let original = state.service.providers.get(&provider).ok_or_else(|| { + conceal_target_error( + target, + HttpError::AuthenticationRefused(FailedCheck::AccessProfile), + ) + })?; let scoped = VerifiedSourceProvider { inner: Arc::clone(original), token: Zeroizing::new(source.to_owned()), diff --git a/crates/registry-casework/src/metrics.rs b/crates/registry-casework/src/metrics.rs index e30b08d253..17f8c9e556 100644 --- a/crates/registry-casework/src/metrics.rs +++ b/crates/registry-casework/src/metrics.rs @@ -1,12 +1,26 @@ //! Optional operator-private telemetry. Labels contain no caller or subject values. use crate::{CompletionBacklog, PostgresStore}; use axum::{extract::State, http::header::CONTENT_TYPE, routing::get, Json, Router}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ sample_error_class, Exposition, MetricKind, ScrapeDeadline, CLASS_NO_TIME_LEFT, CONTENT_TYPE as METRICS_CONTENT_TYPE, }; use serde_json::json; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; + +/// The process's refusal recorder, shared by the HTTP boundary that counts +/// refusals and the scrape that exposes the counter. +pub(crate) fn refusal_recorder() -> Arc { + static RECORDER: OnceLock> = OnceLock::new(); + Arc::clone(RECORDER.get_or_init(|| { + Arc::new( + RefusalRecorder::new("casework") + .expect("the refusal counter declares one closed label"), + ) + })) +} + /// One sample of the database. Each part is sampled on its own, so a failing /// part leaves out only its own series. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -193,7 +207,7 @@ pub(crate) async fn begin_sample<'a>( pub async fn scrape_for_test(store: PostgresStore, deadline: ScrapeDeadline) -> String { let state = MetricsState::new(store, Vec::new(), "sha256:test".to_owned()); let readings = state.sample(deadline).await; - render(readings, &state.inner.failures) + render(readings, &state.inner.failures, &refusal_recorder()) } pub(crate) fn metrics_router(state: MetricsState) -> Router { Router::new() @@ -210,13 +224,13 @@ async fn metrics( let readings = state.readings().await; ( [(CONTENT_TYPE, METRICS_CONTENT_TYPE)], - render(readings, &state.inner.failures), + render(readings, &state.inner.failures, &refusal_recorder()), ) } /// The exposition for one scrape. A part of `readings` that could not be /// read has no series. The database counts as up when the review counts were -/// read. -fn render(readings: Readings, failures: &SampleFailures) -> String { +/// read. The refusal counter follows, one series per check. +fn render(readings: Readings, failures: &SampleFailures, refusals: &RefusalRecorder) -> String { const DECLARATION: &str = "the metric declarations are valid"; let mut out = Exposition::new(); out.header("casework_database_up", None, MetricKind::Gauge) @@ -286,14 +300,36 @@ fn render(readings: Readings, failures: &SampleFailures) -> String { ) .expect(DECLARATION); } + refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } #[cfg(test)] mod tests { use super::{render, Readings, SampleFailures, SampleKind}; use crate::CompletionBacklog; + use registry_platform_authcommon::{FailedCheck, RefusalRecorder}; use registry_platform_metrics::ScrapeDeadline; + /// The refusal counter of a recorder that has counted `counted` once. + fn refusal_series(counted: Option) -> String { + let mut text = String::from( + "# HELP casework_request_refusals_total Requests refused, by the check that failed.\n\ + # TYPE casework_request_refusals_total counter\n", + ); + for check in FailedCheck::ALL { + let value = u8::from(counted == Some(check)); + text.push_str(&format!( + "casework_request_refusals_total{{check=\"{}\"}} {value}\n", + check.as_str() + )); + } + text + } + + fn recorder() -> RefusalRecorder { + RefusalRecorder::new("casework").expect("the casework recorder") + } + fn backlog() -> CompletionBacklog { CompletionBacklog { pending: 1, @@ -330,24 +366,39 @@ mod tests { review: Some([4, 9, 2]), completions: Some(backlog()), }; + let refusals = refusal_series(None); assert_eq!( - render(readings, &SampleFailures::default()), + render(readings, &SampleFailures::default(), &recorder()), format!( "{REVIEW}{COMPLETIONS}{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n\ + {refusals}" ) ); assert_eq!( - render(Readings::default(), &SampleFailures::default()), + render(Readings::default(), &SampleFailures::default(), &recorder()), format!( "# TYPE casework_database_up gauge\ncasework_database_up 0\n{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 0\n\ + {refusals}" ) ); } + #[test] + fn the_scrape_lists_every_check_and_counts_a_refusal_once() { + let recorder = recorder(); + let _ = recorder.record(FailedCheck::TokenSignature); + assert_eq!( + render(Readings::default(), &SampleFailures::default(), &recorder) + .split_once("# HELP casework_request_refusals_total") + .map(|(_, series)| format!("# HELP casework_request_refusals_total{series}")), + Some(refusal_series(Some(FailedCheck::TokenSignature))) + ); + } + #[test] fn a_failed_backlog_leaves_out_only_the_completion_series() { let readings = Readings { @@ -358,11 +409,13 @@ mod tests { failures.0[SampleKind::CompletionBacklog as usize] .store(2, std::sync::atomic::Ordering::Relaxed); assert_eq!( - render(readings, &failures), + render(readings, &failures, &recorder()), format!( "{REVIEW}{FAILURES}\ casework_metrics_sample_failures_total{{sample=\"review\"}} 0\n\ - casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 2\n" + casework_metrics_sample_failures_total{{sample=\"completion-backlog\"}} 2\n\ + {}", + refusal_series(None) ) ); } diff --git a/crates/registry-casework/src/review.rs b/crates/registry-casework/src/review.rs index 56cbde2218..be918ed818 100644 --- a/crates/registry-casework/src/review.rs +++ b/crates/registry-casework/src/review.rs @@ -5,6 +5,7 @@ use chrono::{DateTime, TimeDelta, Utc}; use deadpool_postgres::GenericClient; use deadpool_postgres::Transaction; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest as _, Sha256}; @@ -107,8 +108,10 @@ pub enum ReviewRuntimeError { QueryTooBroad, #[error("the review resource was not found")] NotFound, + #[error("the review resource was not found")] + NotHeldByReader, #[error("the caller is not authorized for this review operation")] - Forbidden, + Forbidden(FailedCheck), #[error("the retained submission has different canonical content")] SubmissionConflict, #[error("the retained review result has expired")] @@ -175,8 +178,12 @@ fn map_review_decision_error(error: ReviewDecisionError) -> ReviewRuntimeError { } ReviewDecisionError::InitiatorExcluded => ReviewRuntimeError::InitiatorExcluded, ReviewDecisionError::DuplicateReviewer - | ReviewDecisionError::PreviousStageReviewerExcluded - | ReviewDecisionError::ProfileNotEligible => ReviewRuntimeError::Forbidden, + | ReviewDecisionError::PreviousStageReviewerExcluded => { + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) + } + ReviewDecisionError::ProfileNotEligible => { + ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile) + } ReviewDecisionError::Validation(error) => review_validation_error(error), ReviewDecisionError::Policy(_) => ReviewRuntimeError::Corrupt, ReviewDecisionError::OutcomeNotAllowed { declared, .. } => ReviewRuntimeError::Validation( @@ -492,7 +499,7 @@ impl CaseworkService { ) -> Result { require_human_reviewer(actor)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let page = self .review_task_page( @@ -620,7 +627,7 @@ impl CaseworkService { match tokio::time::timeout_at(deadline_at, preflight).await { Ok(Ok(())) => {} Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired | ReviewRuntimeError::SourceProfileRequired @@ -764,7 +771,7 @@ impl CaseworkService { } Ok(_) => {} Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired, ) => { @@ -799,7 +806,7 @@ impl CaseworkService { skipped_without_source_profile = true; } Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::SourceProfileNotApplicable, )) => { @@ -964,7 +971,7 @@ impl CaseworkService { .await { Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired, ) => { @@ -1135,7 +1142,7 @@ impl CaseworkService { .source_namespaces .contains(&request.subject.source) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.store .cancel_review( @@ -1359,7 +1366,7 @@ impl CaseworkService { event_id: Uuid, ) -> Result { if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.store.review_accountability(actor, event_id).await } @@ -1379,7 +1386,7 @@ impl CaseworkService { } let producer = self.producer_for_actor(actor)?.producer; if request.audience != ReviewHistoryAudience::Requester { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Some(producer) } else { @@ -1671,7 +1678,7 @@ impl CaseworkService { .contains(&request.subject.source) || request.subject.source != request.subject.source.trim() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(admission) } @@ -1681,7 +1688,7 @@ impl CaseworkService { actor: &ActorContext, ) -> Result { if actor.role != registry_casework_core::CaseworkActsAs::Requester { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } self.project .trusted_producers @@ -1693,7 +1700,7 @@ impl CaseworkService { }) .cloned() .map(|producer| ProducerAdmission { producer }) - .ok_or(ReviewRuntimeError::Forbidden) + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) } /// The producer itself, or else a person whose profile some producer @@ -1705,7 +1712,7 @@ impl CaseworkService { ) -> Result { match self.producer_for_actor(actor) { Ok(admission) => return Ok(RequesterReader::Producer(Box::new(admission.producer))), - Err(ReviewRuntimeError::Forbidden) => {} + Err(ReviewRuntimeError::Forbidden(_)) => {} Err(error) => return Err(error), } let producers = self @@ -1716,7 +1723,7 @@ impl CaseworkService { .map(|producer| producer.id.clone()) .collect::>(); if producers.is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } Ok(RequesterReader::Initiator(producers)) } @@ -1820,7 +1827,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; // The UUID names an immutable scan position, not a claim about the @@ -1888,7 +1895,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let supervisory = view.is_supervisory(); @@ -1978,7 +1985,7 @@ impl PostgresStore { let membership = match actor.role { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", - _ => return Err(ReviewRuntimeError::Forbidden), + _ => return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)), }; let position = match cursor { Some(id) => Some( @@ -2049,7 +2056,7 @@ impl PostgresStore { let membership = match actor.role { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", - _ => return Err(ReviewRuntimeError::Forbidden), + _ => return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)), }; let client = self.client().await?; client @@ -2180,7 +2187,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -2681,7 +2688,7 @@ impl PostgresStore { .review_policies .iter() .find(|policy| policy.id == request.policy.id) - .ok_or(ReviewRuntimeError::Forbidden)?; + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::Operation))?; let snapshot = project .compile_policy(&policy.id) .map_err(|_| ReviewRuntimeError::Corrupt)?; @@ -2719,7 +2726,7 @@ impl PostgresStore { .as_ref() .ok_or(ReviewRuntimeError::Corrupt)?; if request.subject.source != provider.source_namespace { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } } _ => return Err(ReviewRuntimeError::Invalid), @@ -3291,7 +3298,7 @@ impl PostgresStore { .get(usize::from(stage_index)) .ok_or(ReviewRuntimeError::Corrupt)?; if !stage.deciding_profiles.contains(&actor.profile_id) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } ensure_actor_serves_review_queue(&transaction, actor, &row.get::<_, String>(2)).await?; if stage.exclude_initiator && record.initiator.as_ref() == Some(&actor.principal) { @@ -3315,14 +3322,14 @@ impl PostgresStore { return Err(if previous.get::<_, i32>(0) == i32::from(stage_index) { ReviewRuntimeError::DistinctApproverRequired } else { - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) }); } if !active_review_absences(&transaction, &actor.principal, now) .await? .is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let state: String = row.get(3); let held_by_caller = state == "claimed" @@ -3515,7 +3522,7 @@ impl PostgresStore { ensure_review_mutation_actor_authorized(&transaction, &record, actor, task_id).await?; } else { if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_actor_serves_review_queue(&transaction, actor, &task_queue).await?; } @@ -3558,10 +3565,10 @@ impl PostgresStore { .get(usize::from(stage_index)) .ok_or(ReviewRuntimeError::Corrupt)?; if delegate && !stage.deciding_profiles.contains(&actor.profile_id) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)); } if !delegate && actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let holder = match ( row.get::<_, Option>(4), @@ -3574,7 +3581,7 @@ impl PostgresStore { let queue = row.get::<_, String>(2); if delegate { if holder.as_ref() != Some(&actor.principal) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Ownership)); } ensure_actor_serves_review_queue(&transaction, actor, &queue).await?; } else if transaction @@ -3588,7 +3595,7 @@ impl PostgresStore { .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_review_identity_eligible( &transaction, @@ -4172,7 +4179,7 @@ impl PostgresStore { .await { Ok(()) => {} - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) => return Ok(()), + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) => return Ok(()), Err(error) => return Err(error), } @@ -5037,7 +5044,7 @@ async fn insert_stage_tasks( .map_err(map_review_source_error)?; observed.check(&expected).map_err(map_review_source_error)?; if !observed.reviewable { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::SourceAuthority)); } observed.fields } @@ -5896,7 +5903,9 @@ async fn ensure_review_identity_eligible( membership_kinds: &[String], ) -> Result<(), ReviewRuntimeError> { if stage.exclude_initiator && record.initiator.as_ref() == Some(person) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } if transaction .query_opt( @@ -5914,7 +5923,9 @@ async fn ensure_review_identity_eligible( .await? .is_some() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } if transaction .query_opt( @@ -5927,7 +5938,7 @@ async fn ensure_review_identity_eligible( .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(()) } @@ -5941,7 +5952,7 @@ async fn ensure_actor_serves_review_queue( CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; if transaction @@ -5960,7 +5971,7 @@ async fn ensure_actor_serves_review_queue( .await? .is_none() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } Ok(()) } @@ -6315,7 +6326,7 @@ fn require_human_reviewer(actor: &ActorContext) -> Result<(), ReviewRuntimeError | registry_casework_core::CaseworkActsAs::Supervisor ) .then_some(()) - .ok_or(ReviewRuntimeError::Forbidden) + .ok_or(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) } fn ensure_review_result_retained(record: &ReviewRequestRecord) -> Result<(), ReviewRuntimeError> { @@ -6368,7 +6379,7 @@ async fn ensure_review_stage_queue_access( CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; if eligible_stages.is_empty() { @@ -6411,7 +6422,9 @@ async fn ensure_review_mutation_actor_authorized( task_id: Uuid, ) -> Result<(), ReviewRuntimeError> { match ensure_review_reviewer_access(transaction, record, actor, Some(task_id), true).await { - Err(ReviewRuntimeError::NotFound) => Err(ReviewRuntimeError::Forbidden), + Err(ReviewRuntimeError::NotFound) => { + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) + } result => result, } } @@ -6475,7 +6488,7 @@ fn map_reviewer_conflict(error: tokio_postgres::Error) -> ReviewRuntimeError { .as_db_error() .is_some_and(|error| error.code() == &tokio_postgres::error::SqlState::UNIQUE_VIOLATION) { - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties) } else { ReviewRuntimeError::Store(StoreError::Postgres(error)) } @@ -6622,7 +6635,7 @@ impl CaseworkService { .get(field) .cloned() .map(|value| (field.clone(), value)) - .ok_or(crate::ServiceError::Forbidden) + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation)) }) .collect(), ( @@ -6652,7 +6665,7 @@ impl CaseworkService { return Err(ReviewContextError::Invalid.into()); } if !observed.reviewable { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::SourceAuthority)); } return Ok(Default::default()); } @@ -6678,7 +6691,7 @@ impl CaseworkService { .map_err(|_| crate::ServiceError::Context(ReviewContextError::Unavailable))??; observed.check(&expected)?; if !observed.reviewable { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::SourceAuthority)); } Ok(observed.fields) } @@ -6696,10 +6709,11 @@ fn review_service_error(error: ReviewRuntimeError) -> crate::ServiceError { ReviewContextError::VersionUnavailable.into() } ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired => { - crate::ServiceError::NotFound + crate::ServiceError::NotFound(FailedCheck::Visibility) } ReviewRuntimeError::RevisionConflict => StoreError::Conflict.into(), - _ => crate::ServiceError::Forbidden, + ReviewRuntimeError::Forbidden(check) => crate::ServiceError::Forbidden(check), + _ => crate::ServiceError::Forbidden(FailedCheck::Operation), } } @@ -6792,4 +6806,75 @@ mod tests { assert_ne!(actor_reference(&first), actor_reference(&second)); assert!(!actor_reference(&first).contains("person")); } + + fn refused_check(error: ReviewRuntimeError) -> FailedCheck { + match error { + ReviewRuntimeError::Forbidden(check) => check, + other => panic!("expected a forbidden answer, got {other:?}"), + } + } + + fn actor(role: CaseworkActsAs) -> ActorContext { + ActorContext { + principal: IssuerPrincipal { + issuer: "https://issuer.example".to_owned(), + subject: "person".to_owned(), + }, + profile_id: "profile".to_owned(), + role, + } + } + + #[test] + fn a_reviewer_who_already_acted_is_refused_for_separation_of_duties() { + for error in [ + ReviewDecisionError::DuplicateReviewer, + ReviewDecisionError::PreviousStageReviewerExcluded, + ] { + assert_eq!( + refused_check(map_review_decision_error(error)), + FailedCheck::SeparationOfDuties + ); + } + } + + #[test] + fn a_profile_outside_the_stage_is_refused_for_its_access_profile() { + assert_eq!( + refused_check(map_review_decision_error( + ReviewDecisionError::ProfileNotEligible + )), + FailedCheck::AccessProfile + ); + } + + #[test] + fn only_staff_and_supervisors_pass_the_human_reviewer_check() { + assert!(require_human_reviewer(&actor(CaseworkActsAs::Staff)).is_ok()); + assert!(require_human_reviewer(&actor(CaseworkActsAs::Supervisor)).is_ok()); + for role in [CaseworkActsAs::Administrator, CaseworkActsAs::Requester] { + assert_eq!( + refused_check(require_human_reviewer(&actor(role)).unwrap_err()), + FailedCheck::Operation + ); + } + } + + #[test] + fn a_service_refusal_keeps_the_check_the_review_layer_named() { + for check in [ + FailedCheck::SeparationOfDuties, + FailedCheck::AccessProfile, + FailedCheck::Ownership, + ] { + assert!(matches!( + review_service_error(ReviewRuntimeError::Forbidden(check)), + crate::ServiceError::Forbidden(kept) if kept == check + )); + } + assert!(matches!( + review_service_error(ReviewRuntimeError::TaskNotHeld), + crate::ServiceError::Forbidden(FailedCheck::Operation) + )); + } } diff --git a/crates/registry-casework/src/review/inbox.rs b/crates/registry-casework/src/review/inbox.rs index a15de044b7..9dd3e0c7f5 100644 --- a/crates/registry-casework/src/review/inbox.rs +++ b/crates/registry-casework/src/review/inbox.rs @@ -306,7 +306,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -402,7 +402,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } }; let supervisory = view.is_supervisory(); diff --git a/crates/registry-casework/src/review/staffing.rs b/crates/registry-casework/src/review/staffing.rs index 83d8042be4..8e990a5bdf 100644 --- a/crates/registry-casework/src/review/staffing.rs +++ b/crates/registry-casework/src/review/staffing.rs @@ -140,7 +140,7 @@ impl CaseworkService { match tokio::time::timeout_at(until, check).await { Ok(Ok(())) => {} Ok(Err( - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::SourceProfileRequired | ReviewRuntimeError::SourceProfileNotApplicable, @@ -232,7 +232,7 @@ impl CaseworkService { skipped_without_source_profile = true; continue; } - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) => { + Err(ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound) => { continue } Err(error) => return Err(error), @@ -366,7 +366,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let client = self.store.client().await?; let rows=client.query("SELECT task_id FROM casework_review_tasks WHERE state='claimed' AND holder_issuer=$1 AND holder_subject=$2 AND ($3::text IS NULL OR queue_id=$3) ORDER BY task_id LIMIT 101",&[&request.from.issuer,&request.from.subject,&request.queue]).await?; @@ -421,7 +421,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Supervisor { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let (movement, tasks, directory_revision) = self .store @@ -559,7 +559,9 @@ async fn validate_caseload_set( let stage_index = u16::try_from(row.get::<_, i32>(1)).map_err(|_| ReviewRuntimeError::Corrupt)?; if !selected_stages.insert((request_id, stage_index)) { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties, + )); } let queue: String = row.get(2); if record.lifecycle != ReviewRequestLifecycle::Reviewing @@ -601,7 +603,7 @@ async fn validate_caseload_set( .await? .is_empty() { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } ensure_review_identity_eligible( tx, @@ -613,7 +615,7 @@ async fn validate_caseload_set( &membership_kinds, ) .await?; - if tx.query_opt("SELECT 1 FROM casework_review_tasks WHERE request_id=$1 AND stage_index=$2 AND task_id<>$3 AND holder_issuer=$4 AND holder_subject=$5 AND state IN('open','claimed')",&[&request_id,&i32::from(stage_index),&task.task_id,&movement.to.issuer,&movement.to.subject]).await?.is_some(){return Err(ReviewRuntimeError::Forbidden)} + if tx.query_opt("SELECT 1 FROM casework_review_tasks WHERE request_id=$1 AND stage_index=$2 AND task_id<>$3 AND holder_issuer=$4 AND holder_subject=$5 AND state IN('open','claimed')",&[&request_id,&i32::from(stage_index),&task.task_id,&movement.to.issuer,&movement.to.subject]).await?.is_some(){return Err(ReviewRuntimeError::Forbidden(FailedCheck::SeparationOfDuties))} } Ok(()) } @@ -647,7 +649,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Administrator { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } for id in &request.task_ids { let record = self.store.review_request_for_task(*id).await?; @@ -707,7 +709,7 @@ impl CaseworkService { ) -> Result { request.check().map_err(|_| ReviewRuntimeError::Invalid)?; if actor.role != CaseworkActsAs::Administrator { - return Err(ReviewRuntimeError::Forbidden); + return Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)); } let (inputs, tasks, directory_revision) = self .store diff --git a/crates/registry-casework/src/runtime.rs b/crates/registry-casework/src/runtime.rs index 7767745520..9593e773f1 100644 --- a/crates/registry-casework/src/runtime.rs +++ b/crates/registry-casework/src/runtime.rs @@ -3,16 +3,17 @@ use std::future::Future; use std::num::NonZeroUsize; use std::path::Path; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, SystemTime}; use clap::{Arg, Command}; use registry_casework_core::ReviewContextProvider; use registry_platform_audit::{AuditProfile, AuditWriter}; -use registry_platform_config::SecretResolver; +use registry_platform_config::{SecretError, SecretReference, SecretResolver}; +use registry_platform_crypto::delivery_signature::{self, DeliveryKey, DeliveryKeys}; #[cfg(feature = "postgres-test")] use registry_platform_dispatch::postgres::DispatchOutcome; use registry_platform_dispatch::postgres::{DispatchWorker, Disposition, WorkerConfig}; -use registry_platform_httputil::{BearerToken, OutboundClientBuilder}; +use registry_platform_httputil::OutboundClientBuilder; use thiserror::Error; use tokio::sync::mpsc; use tokio::task::JoinHandle; @@ -25,86 +26,107 @@ use crate::{ router, CaseworkAuthenticator, CaseworkService, HttpState, PostgresStore, RuntimeConfig, }; -struct ReviewCompletionTarget { +pub(crate) struct ReviewCompletionTarget { url: String, - credential: ReviewCompletionCredential, + keys: DeliveryKeys, timeout: Duration, maximum_attempts: u32, retry: Duration, } -const MAXIMUM_COMPLETION_SECRET_BYTES: usize = 8 * 1024; - -/// The secret a completion destination presents on every wake-up. -enum ReviewCompletionCredential { - Bearer(BearerToken), - Header { - name: reqwest::header::HeaderName, - value: reqwest::header::HeaderValue, - }, +fn completion_key_path(id: &str, member: &str) -> String { + format!("reviewCompletionDestinations.{id}.{member}") } -impl ReviewCompletionCredential { - fn from_config(header: Option<&str>, secret: &[u8]) -> Result { - let Some(header) = header else { - return completion_bearer_token(secret).map(Self::Bearer); - }; - let name = reqwest::header::HeaderName::from_bytes(header.as_bytes()) - .map_err(|_| RuntimeError::CompletionConfiguration)?; - // The same header-safe subset a bearer credential is held to: visible - // ASCII only, so the secret cannot fold or inject a header. - if secret.is_empty() - || secret.len() > MAXIMUM_COMPLETION_SECRET_BYTES - || !secret.iter().all(u8::is_ascii_graphic) - { - return Err(RuntimeError::CompletionConfiguration); - } - let mut value = reqwest::header::HeaderValue::from_bytes(secret) - .map_err(|_| RuntimeError::CompletionConfiguration)?; - value.set_sensitive(true); - Ok(Self::Header { name, value }) - } - - fn header(&self) -> (reqwest::header::HeaderName, reqwest::header::HeaderValue) { - match self { - Self::Bearer(token) => ( - reqwest::header::AUTHORIZATION, - token.authorization_header_value(), - ), - Self::Header { name, value } => (name.clone(), value.clone()), - } - } +fn resolve_completion_key( + secrets: &SecretResolver, + path: &str, + reference: &SecretReference, +) -> Result { + let secret = secrets + .resolve_binary_reference(reference) + .map_err(|reason| CompletionKeyError::Unavailable { + path: path.to_owned(), + reason, + })?; + let bytes = secret.expose_secret(); + DeliveryKey::new(bytes).map_err(|source| CompletionKeyError::Invalid { + path: path.to_owned(), + length: bytes.len(), + trailing_newline: bytes.ends_with(b"\n"), + source, + }) } -/// Resolve every configured completion destination and its credential. -fn review_completion_targets( +/// Resolve every configured completion destination and its signing keys. +pub(crate) fn review_completion_targets( configured: &BTreeMap, secrets: &SecretResolver, -) -> Result>, RuntimeError> { +) -> Result>, Vec> { + use crate::config::{CURRENT_COMPLETION_KEY, PREVIOUS_COMPLETION_KEY}; + let mut targets = BTreeMap::new(); + let mut errors = Vec::new(); for (id, target) in configured { - let reference = target - .secret_ref() - .ok_or(RuntimeError::CompletionConfiguration)?; - let secret = secrets - .resolve(reference) - .map_err(|_| RuntimeError::CompletionConfiguration)?; - let credential = ReviewCompletionCredential::from_config( - target.secret_header(), - secret.expose_secret(), - )?; + let current_path = completion_key_path(id, CURRENT_COMPLETION_KEY); + let previous_path = completion_key_path(id, PREVIOUS_COMPLETION_KEY); + let current = resolve_completion_key(secrets, ¤t_path, &target.hmac_sha256_key_ref); + let previous = target + .previous_hmac_sha256_key_ref + .as_ref() + .map(|reference| resolve_completion_key(secrets, &previous_path, reference)) + .transpose(); + let current = current.map_err(|error| errors.push(error)); + let previous = previous.map_err(|error| errors.push(error)); + let (Ok(current), Ok(previous)) = (current, previous) else { + continue; + }; + let Ok(keys) = DeliveryKeys::new(current, previous) else { + errors.push(CompletionKeyError::PreviousEqualsCurrent { + current: current_path, + previous: previous_path, + }); + continue; + }; targets.insert( id.clone(), Arc::new(ReviewCompletionTarget { url: target.url.clone(), - credential, + keys, timeout: Duration::from_millis(target.attempt_timeout_milliseconds), maximum_attempts: target.maximum_attempts, retry: Duration::from_secs(target.retry_delay_seconds), }), ); } - Ok(targets) + let labeled_keys = targets + .iter() + .flat_map(|(id, target)| { + std::iter::once(( + completion_key_path(id, CURRENT_COMPLETION_KEY), + target.keys.current(), + )) + .chain( + target + .keys + .previous() + .map(|key| (completion_key_path(id, PREVIOUS_COMPLETION_KEY), key)), + ) + }) + .collect::>(); + if let Err(error) = delivery_signature::distinct_delivery_keys( + labeled_keys.iter().map(|(path, key)| (path.as_str(), *key)), + ) { + errors.push(CompletionKeyError::Repeated { + first: error.first().to_owned(), + second: error.second().to_owned(), + }); + } + if errors.is_empty() { + Ok(targets) + } else { + Err(errors) + } } fn review_completion_client() -> Result { @@ -156,11 +178,6 @@ fn completion_failure_diagnostic(destination: &str, attempt: i32, disposition: D } } -fn completion_bearer_token(bytes: &[u8]) -> Result { - let token = std::str::from_utf8(bytes).map_err(|_| RuntimeError::CompletionConfiguration)?; - BearerToken::new(token.to_owned()).map_err(|_| RuntimeError::CompletionConfiguration) -} - async fn validate_retained_completion_destinations( store: &PostgresStore, configured: &BTreeMap, @@ -199,8 +216,8 @@ pub async fn validate_retained_completion_destinations_for_test( (*id).to_owned(), crate::ReviewCompletionRuntimeConfig { url: "http://127.0.0.1/completion".to_owned(), - bearer_token_ref: Some("secret:env/TEST".to_owned()), - auth: None, + hmac_sha256_key_ref: SecretReference::parse("secret:env/TEST").unwrap(), + previous_hmac_sha256_key_ref: None, attempt_timeout_milliseconds: 1_000, maximum_attempts: 1, retry_delay_seconds: 1, @@ -215,17 +232,19 @@ pub async fn validate_retained_completion_destinations_for_test( fn test_completion_targets( destination_id: &str, url: String, - bearer_token: &str, + signing_key: &str, maximum_attempts: u32, ) -> Result { Ok(Arc::new(BTreeMap::from([( destination_id.to_owned(), Arc::new(ReviewCompletionTarget { url, - credential: ReviewCompletionCredential::Bearer( - BearerToken::new(bearer_token.to_owned()) + keys: DeliveryKeys::new( + DeliveryKey::new(signing_key.as_bytes()) .map_err(|_| crate::ReviewRuntimeError::Invalid)?, - ), + None, + ) + .expect("one validated key"), timeout: Duration::from_secs(30), maximum_attempts, retry: Duration::from_secs(1), @@ -241,9 +260,9 @@ pub async fn dispatch_review_completions_once_for_test( store: PostgresStore, destination_id: &str, url: String, - bearer_token: &str, + signing_key: &str, ) -> Result<(), crate::ReviewRuntimeError> { - let targets = test_completion_targets(destination_id, url, bearer_token, 3)?; + let targets = test_completion_targets(destination_id, url, signing_key, 3)?; let dispatcher = completion::completion_dispatcher(store, Arc::clone(&targets)).await?; let client = review_completion_client().map_err(|_| crate::ReviewRuntimeError::Invalid)?; let transport = completion::CompletionTransport::new(client, targets); @@ -300,7 +319,7 @@ pub async fn claim_review_completion_for_test( let targets = test_completion_targets( destination_id, "http://127.0.0.1/completion".to_owned(), - "completion-secret", + "synthetic-test-key-not-for-use!!", maximum_attempts, )?; let dispatcher = completion::completion_dispatcher(store, targets).await?; @@ -324,7 +343,7 @@ pub async fn finish_review_completion_for_test( let targets = test_completion_targets( destination_id, "http://127.0.0.1/completion".to_owned(), - "completion-secret", + "synthetic-test-key-not-for-use!!", maximum_attempts, )?; let dispatcher = completion::completion_dispatcher(store, targets).await?; @@ -353,14 +372,27 @@ async fn deliver_review_completion( target: &ReviewCompletionTarget, delivery: &crate::LeasedReviewCompletion, ) -> bool { - let (credential_name, credential_value) = target.credential.header(); + let Ok(body) = serde_json::to_vec(&delivery.event) else { + return false; + }; + let Ok(now) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) else { + return false; + }; + let timestamp = now.as_secs(); + let id = delivery.event.event_id.to_string(); + let Ok(signature) = delivery_signature::sign(&target.keys, &id, timestamp, &body) else { + return false; + }; let Ok(response) = client .post(&target.url) .timeout(target.timeout) - .header(credential_name, credential_value) - .header("idempotency-key", delivery.event.event_id.to_string()) + .header("accept", "application/json") + .header("content-type", "application/json") + .header("webhook-id", id) + .header("webhook-timestamp", timestamp.to_string()) + .header("webhook-signature", signature) .header("registry-recipient-binding", &delivery.recipient_binding) - .json(&delivery.event) + .body(body) .send() .await else { @@ -590,7 +622,14 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> .with_task_authority(task_authority); let completion_worker = review_completion_worker( store.clone(), - review_completion_targets(&config.review_completion_destinations, &secrets)?, + review_completion_targets(&config.review_completion_destinations, &secrets).map_err( + |errors| { + errors + .into_iter() + .next() + .expect("completion target refusal") + }, + )?, ) .await?; @@ -778,7 +817,7 @@ pub async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditDestination(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditDestination(error.operator_description()))?; Ok(crate::CaseworkAudit::new( @@ -822,6 +861,163 @@ mod tests { use super::*; + fn completion_test_keys() -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(&[b'k'; 32]).unwrap(), None).unwrap() + } + + fn completion_config( + current: &str, + previous: Option<&str>, + ) -> crate::ReviewCompletionRuntimeConfig { + let mut value = serde_json::json!({ + "url": "https://receiver.example.test/completions", + "hmacSha256KeyRef": current, + }); + if let Some(previous) = previous { + value["previousHmacSha256KeyRef"] = serde_json::json!(previous); + } + serde_json::from_value(value).unwrap() + } + + fn completion_key_file(root: &Path, name: &str, bytes: &[u8]) { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt as _; + + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(root.join(name)) + .unwrap() + .write_all(bytes) + .unwrap(); + } + + #[test] + fn completion_destinations_cannot_share_a_current_or_previous_signing_key() { + let root = tempfile::tempdir().unwrap(); + completion_key_file(root.path(), "current", &[0; 32]); + completion_key_file(root.path(), "other", &[1; 32]); + completion_key_file(root.path(), "previous", &[0; 32]); + let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); + let current_path = "reviewCompletionDestinations.first.hmacSha256KeyRef"; + for (destinations, second_path) in [ + ( + BTreeMap::from([ + ( + "first".to_owned(), + completion_config("secret:file/current", None), + ), + ( + "second".to_owned(), + completion_config("secret:file/other", Some("secret:file/previous")), + ), + ]), + "reviewCompletionDestinations.second.previousHmacSha256KeyRef", + ), + ( + BTreeMap::from([ + ( + "first".to_owned(), + completion_config("secret:file/current", None), + ), + ( + "second".to_owned(), + completion_config("secret:file/previous", None), + ), + ]), + "reviewCompletionDestinations.second.hmacSha256KeyRef", + ), + ] { + let errors = review_completion_targets(&destinations, &secrets) + .err() + .unwrap(); + let [error] = errors.as_slice() else { + panic!("expected one completion key refusal"); + }; + assert_eq!( + error.to_string(), + format!("{current_path} and {second_path} resolve to the same key bytes. Give {second_path} its own key by writing 32 new random bytes to another secret and referencing it there.") + ); + } + + let previous_path = "reviewCompletionDestinations.first.previousHmacSha256KeyRef"; + let destinations = BTreeMap::from([( + "first".to_owned(), + completion_config("secret:file/current", Some("secret:file/previous")), + )]); + let errors = review_completion_targets(&destinations, &secrets) + .err() + .unwrap(); + let [error] = errors.as_slice() else { + panic!("expected one completion key refusal"); + }; + assert_eq!( + error.to_string(), + format!("{previous_path} holds the same bytes as {current_path}. To rotate, write 32 new random bytes to the secret {current_path} references and keep the old bytes behind {previous_path}.") + ); + } + + #[test] + fn missing_completion_signing_key_reports_its_resolution_failure() { + assert_completion_secret_failure( + "missing", + registry_platform_config::SecretError::Unavailable, + ); + } + + #[test] + fn empty_completion_signing_key_reports_its_resolution_failure() { + assert_completion_secret_failure( + "empty", + registry_platform_config::SecretError::InvalidValue, + ); + } + + fn assert_completion_secret_failure(name: &str, reason: registry_platform_config::SecretError) { + let root = tempfile::tempdir().unwrap(); + completion_key_file(root.path(), "empty", b""); + let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); + let destinations = BTreeMap::from([( + "receiver".to_owned(), + completion_config(&format!("secret:file/{name}"), None), + )]); + let errors = review_completion_targets(&destinations, &secrets) + .err() + .unwrap(); + let [error] = errors.as_slice() else { + panic!("expected one completion key refusal"); + }; + assert_eq!( + error.to_string(), + format!("could not resolve reviewCompletionDestinations.receiver.hmacSha256KeyRef: {reason}. {}", reason.suggested_action()) + ); + } + + #[test] + fn a_65_byte_completion_signing_key_reports_its_length_and_trailing_newline() { + let root = tempfile::tempdir().unwrap(); + let mut bytes = [b'k'; 65]; + bytes[64] = b'\n'; + completion_key_file(root.path(), "oversized", &bytes); + let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); + let destinations = BTreeMap::from([( + "receiver".to_owned(), + completion_config("secret:file/oversized", None), + )]); + let errors = review_completion_targets(&destinations, &secrets) + .err() + .unwrap(); + let [error] = errors.as_slice() else { + panic!("expected one completion key refusal"); + }; + assert!(matches!(error, CompletionKeyError::Invalid { .. })); + let message = error.to_string(); + assert!(message.contains("reviewCompletionDestinations.receiver.hmacSha256KeyRef")); + assert!(message.contains("65 bytes")); + assert!(message.contains("trailing newline: true")); + } + #[tokio::test] async fn completion_acknowledgement_does_not_read_an_unfinished_body() { use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; @@ -843,9 +1039,7 @@ mod tests { }); let target = ReviewCompletionTarget { url: format!("http://{address}/completion"), - credential: ReviewCompletionCredential::Bearer( - BearerToken::new("canary-secret").unwrap(), - ), + keys: completion_test_keys(), timeout: Duration::from_secs(5), maximum_attempts: 3, retry: Duration::from_secs(1), @@ -875,7 +1069,7 @@ mod tests { } } #[tokio::test] - async fn review_completion_delivery_is_minimal_authenticated_and_stable_after_lost_ack() { + async fn review_completion_delivery_is_signed_and_stable_after_lost_ack() { let server = MockServer::start().await; let event = registry_casework_core::ReviewCompletion { event_type: registry_casework_core::ReviewCompletionType::ReviewCompleted, @@ -890,11 +1084,7 @@ mod tests { }; Mock::given(method("POST")) .and(path("/completion")) - .and(header("authorization", "Bearer dispatch-secret")) - .and(header( - "idempotency-key", - "11111111-1111-4111-8111-111111111111", - )) + .and(header("webhook-id", "11111111-1111-4111-8111-111111111111")) .and(header("registry-recipient-binding", "registry-service")) .and(body_json(&event)) .respond_with(ResponseTemplate::new(503)) @@ -905,11 +1095,7 @@ mod tests { .await; Mock::given(method("POST")) .and(path("/completion")) - .and(header("authorization", "Bearer dispatch-secret")) - .and(header( - "idempotency-key", - "11111111-1111-4111-8111-111111111111", - )) + .and(header("webhook-id", "11111111-1111-4111-8111-111111111111")) .and(header("registry-recipient-binding", "registry-service")) .and(body_json(&event)) .respond_with(ResponseTemplate::new(204)) @@ -922,9 +1108,7 @@ mod tests { .expect("completion client"); let target = ReviewCompletionTarget { url: format!("{}/completion", server.uri()), - credential: ReviewCompletionCredential::Bearer( - BearerToken::new("dispatch-secret").expect("completion token"), - ), + keys: completion_test_keys(), timeout: Duration::from_secs(1), maximum_attempts: 3, retry: Duration::from_secs(1), @@ -938,6 +1122,28 @@ mod tests { assert!(!deliver_review_completion(&client, &target, &delivery).await); assert!(deliver_review_completion(&client, &target, &delivery).await); + let attempts = server.received_requests().await.expect("recorded requests"); + let [first, second] = attempts.as_slice() else { + panic!("expected exactly two completion attempts"); + }; + assert_eq!(first.headers["webhook-id"], second.headers["webhook-id"]); + assert_eq!(first.body, second.body); + for attempt in [first, second] { + let header = |name: &str| attempt.headers[name].to_str().unwrap(); + delivery_signature::verify( + &target.keys, + delivery_signature::SignedContent { + id: header("webhook-id"), + timestamp: header("webhook-timestamp"), + signature: header("webhook-signature"), + body: &attempt.body, + }, + SystemTime::now(), + delivery_signature::DELIVERY_TOLERANCE, + ) + .unwrap(); + } + Mock::given(method("POST")) .and(path("/nonempty-success")) .respond_with(ResponseTemplate::new(200).set_body_string("accepted")) @@ -946,9 +1152,7 @@ mod tests { .await; let nonempty_success_target = ReviewCompletionTarget { url: format!("{}/nonempty-success", server.uri()), - credential: ReviewCompletionCredential::Bearer( - BearerToken::new("dispatch-secret").expect("completion token"), - ), + keys: completion_test_keys(), timeout: Duration::from_secs(1), maximum_attempts: 3, retry: Duration::from_secs(1), @@ -980,9 +1184,7 @@ mod tests { .await; let redirect_target = ReviewCompletionTarget { url: format!("{}/redirect", server.uri()), - credential: ReviewCompletionCredential::Bearer( - BearerToken::new("dispatch-secret").expect("completion token"), - ), + keys: completion_test_keys(), timeout: Duration::from_secs(1), maximum_attempts: 3, retry: Duration::from_secs(1), @@ -991,15 +1193,15 @@ mod tests { } #[tokio::test] - async fn review_completion_presents_its_secret_in_a_configured_header_without_authorization() { + async fn review_completion_signs_the_exact_bytes_it_sends() { + use registry_platform_crypto::delivery_signature::{ + verify, SignedContent, DELIVERY_TOLERANCE, + }; + let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/completion")) - .and(header("x-api-key", "dispatch-key")) - .and(header( - "idempotency-key", - "11111111-1111-4111-8111-111111111111", - )) + .and(header("webhook-id", "11111111-1111-4111-8111-111111111111")) .and(header("registry-recipient-binding", "registry-service")) .respond_with(ResponseTemplate::new(204)) .expect(1) @@ -1008,14 +1210,20 @@ mod tests { let client = OutboundClientBuilder::new() .try_build() .expect("completion client"); - let target = ReviewCompletionTarget { - url: format!("{}/completion", server.uri()), - credential: ReviewCompletionCredential::from_config(Some("X-Api-Key"), b"dispatch-key") - .expect("header credential"), - timeout: Duration::from_secs(1), - maximum_attempts: 3, - retry: Duration::from_secs(1), - }; + let root = tempfile::tempdir().unwrap(); + let current_bytes = [0; 32]; + let previous_bytes = [0xff; 32]; + completion_key_file(root.path(), "current", ¤t_bytes); + completion_key_file(root.path(), "previous", &previous_bytes); + let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); + let mut configured = completion_config("secret:file/current", Some("secret:file/previous")); + configured.url = format!("{}/completion", server.uri()); + let targets = review_completion_targets( + &BTreeMap::from([("receiver".to_owned(), configured)]), + &secrets, + ) + .unwrap(); + let target = &targets["receiver"]; let delivery = crate::LeasedReviewCompletion { event: registry_casework_core::ReviewCompletion { event_type: registry_casework_core::ReviewCompletionType::ReviewCompleted, @@ -1034,49 +1242,59 @@ mod tests { recipient_binding: "registry-service".to_owned(), }; - assert!(deliver_review_completion(&client, &target, &delivery).await); + assert!(deliver_review_completion(&client, target, &delivery).await); let received = server.received_requests().await.expect("recorded requests"); assert_eq!(received.len(), 1); - assert!( - !received[0].headers.contains_key("authorization"), - "a configured header replaces Authorization" - ); - - let (name, value) = ReviewCompletionCredential::from_config(None, b"dispatch-secret") - .expect("default credential") - .header(); - assert_eq!(name, reqwest::header::AUTHORIZATION); - assert_eq!(value, "Bearer dispatch-secret"); - assert!(value.is_sensitive()); - let (_, value) = - ReviewCompletionCredential::from_config(Some("x-api-key"), b"dispatch-key") - .expect("header credential") - .header(); - assert_eq!(value, "dispatch-key"); - assert!(value.is_sensitive()); - for invalid in [ - b"".as_slice(), - b"dispatch key", - b"dispatch-key\r\nhost: other", - &[0xff], - &[b'k'; MAXIMUM_COMPLETION_SECRET_BYTES + 1], - ] { - assert!(matches!( - ReviewCompletionCredential::from_config(Some("x-api-key"), invalid), - Err(RuntimeError::CompletionConfiguration) - )); - } - } - - #[test] - fn review_completion_bearer_tokens_are_validated_before_dispatch() { - assert!(completion_bearer_token(b"dispatch-secret").is_ok()); - for invalid in [b"dispatch-secret\n".as_slice(), &[0xff]] { - assert!(matches!( - completion_bearer_token(invalid), - Err(RuntimeError::CompletionConfiguration) - )); + let request = &received[0]; + let header = |name: &str| request.headers[name].to_str().unwrap(); + let content = SignedContent { + id: header("webhook-id"), + timestamp: header("webhook-timestamp"), + signature: header("webhook-signature"), + body: &request.body, + }; + let entries: Vec<_> = content.signature.split(' ').collect(); + assert_eq!(entries.len(), 2); + for (signature, key_bytes) in entries.into_iter().zip([current_bytes, previous_bytes]) { + let keys = DeliveryKeys::new(DeliveryKey::new(&key_bytes).unwrap(), None).unwrap(); + verify( + &keys, + SignedContent { + signature, + ..content + }, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .unwrap(); } + assert_eq!(header("webhook-id"), delivery.event.event_id.to_string()); + assert_eq!(header("accept"), "application/json"); + assert_eq!(header("content-type"), "application/json"); + let names: std::collections::BTreeSet<_> = request + .headers + .keys() + .map(|name| name.as_str()) + .filter(|name| !matches!(*name, "host" | "content-length" | "connection")) + .collect(); + assert_eq!( + names, + std::collections::BTreeSet::from([ + "accept", + "content-type", + "registry-recipient-binding", + "webhook-id", + "webhook-signature", + "webhook-timestamp", + ]) + ); + assert!(verify( + &completion_test_keys(), + content, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .is_err()); } #[test] @@ -1311,6 +1529,8 @@ pub enum RuntimeError { AuditDestination(String), #[error("the Casework review completion destination configuration is invalid")] CompletionConfiguration, + #[error(transparent)] + CompletionKey(#[from] CompletionKeyError), #[error("the CASEWORK_LOG level is invalid; it must be one of error, warn, or info")] Logging, #[error(transparent)] @@ -1325,6 +1545,28 @@ pub enum RuntimeError { WorkerStopped, } +/// A value-free refusal of a configured completion signing key. +#[derive(Debug, Error)] +pub enum CompletionKeyError { + #[error("could not resolve {path}: {reason}. {}", reason.suggested_action())] + Unavailable { + path: String, + #[source] + reason: SecretError, + }, + #[error("{path} has {length} bytes (trailing newline: {trailing_newline}). {source}")] + Invalid { + path: String, + length: usize, + trailing_newline: bool, + source: delivery_signature::DeliveryKeyError, + }, + #[error("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there.")] + Repeated { first: String, second: String }, + #[error("{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}.")] + PreviousEqualsCurrent { current: String, previous: String }, +} + impl RuntimeError { /// The reader's report when startup refused the runtime file or the /// Casework project, so `casework` prints its CFG-DIAG-2 lines unchanged diff --git a/crates/registry-casework/src/runtime/completion.rs b/crates/registry-casework/src/runtime/completion.rs index d25210c557..3e849b47df 100644 --- a/crates/registry-casework/src/runtime/completion.rs +++ b/crates/registry-casework/src/runtime/completion.rs @@ -571,6 +571,7 @@ impl DispatchTransport for CompletionTransport { #[cfg(test)] mod tests { use super::*; + use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; fn normalized(sql: &str) -> String { sql.split_whitespace().collect::>().join(" ") @@ -594,10 +595,7 @@ mod tests { fn target(maximum_attempts: u32, retry: Duration) -> ReviewCompletionTarget { ReviewCompletionTarget { url: "http://127.0.0.1/completion".to_owned(), - credential: super::super::ReviewCompletionCredential::Bearer( - registry_platform_httputil::BearerToken::new("completion-secret".to_owned()) - .expect("test bearer token"), - ), + keys: DeliveryKeys::new(DeliveryKey::new(&[0; 32]).unwrap(), None).unwrap(), timeout: Duration::from_secs(30), maximum_attempts, retry, diff --git a/crates/registry-casework/src/schema.rs b/crates/registry-casework/src/schema.rs index c68654d4e1..d975ff2513 100644 --- a/crates/registry-casework/src/schema.rs +++ b/crates/registry-casework/src/schema.rs @@ -100,7 +100,6 @@ fn install_runtime_constraints(schema: &mut Value) { Value::String(registry_platform_audit::ABSOLUTE_AUDIT_PATH_PATTERN.to_owned()), ); set_secret_provider_requirements(schema); - set_review_completion_auth_constraints(schema); set_audit_destination_constraints(schema); } @@ -133,29 +132,6 @@ fn set_audit_destination_constraints(schema: &mut Value) { } } -/// State the shape `RuntimeConfig::validate_secret_references` requires of a -/// completion destination: exactly one of `bearerTokenRef` and `auth`, and a -/// header name made of HTTP token characters. The reserved header set is -/// enforced at load, where names compare case-insensitively. -fn set_review_completion_auth_constraints(schema: &mut Value) { - if let Some(destination) = schema - .pointer_mut("/$defs/ReviewCompletionRuntimeConfig") - .and_then(Value::as_object_mut) - { - destination.insert( - "oneOf".to_owned(), - serde_json::json!([{"required": ["bearerTokenRef"]}, {"required": ["auth"]}]), - ); - } - set_definition_property( - schema, - "ReviewCompletionAuthConfig", - "header", - "pattern", - Value::String("^[!#$%&'*+.^_`|~0-9A-Za-z-]+$".to_owned()), - ); -} - /// Every secret reference names its provider by its prefix. When a provider /// is absent, prohibit that prefix at every fixed and keyed binding location. /// Expressing the rule from the absent-provider side makes @@ -226,10 +202,8 @@ fn absent_secret_provider_requirement(provider: &str, reference_pattern: &str) - "reviewCompletionDestinations": { "additionalProperties": { "properties": { - "bearerTokenRef": forbidden, - "auth": { - "properties": {"secretRef": forbidden} - } + "hmacSha256KeyRef": forbidden, + "previousHmacSha256KeyRef": forbidden } } } @@ -597,7 +571,7 @@ mod tests { } #[test] - fn completion_destination_schema_names_exactly_one_secret_and_a_token_header() { + fn completion_destination_schema_requires_a_current_signing_key() { let schema = runtime_schema(); let with = |destination: Value| { let mut instance = runtime_instance("secret:file/jwks.json", "file"); @@ -607,52 +581,26 @@ mod tests { }; let url = "https://requester.example.test/completions"; for accepted in [ - serde_json::json!({"url": url, "bearerTokenRef": "secret:file/completion-token"}), - serde_json::json!({"url": url, "auth": {"secretRef": "secret:file/completion-key"}}), - serde_json::json!({ - "url": url, - "auth": {"header": "x-api-key", "secretRef": "secret:file/completion-key"} - }), + serde_json::json!({"url": url, "hmacSha256KeyRef": "secret:file/current"}), + serde_json::json!({"url": url, "hmacSha256KeyRef": "secret:file/current", + "previousHmacSha256KeyRef": "secret:file/previous"}), ] { - assert!(schema.is_valid(&with(accepted.clone())), "{accepted}"); - } - // An explicit null is refused, by the schema and by the reader alike. - for nulled in [ - serde_json::json!({ - "url": url, - "bearerTokenRef": null, - "auth": {"secretRef": "secret:file/completion-key"} - }), - serde_json::json!({ - "url": url, - "bearerTokenRef": "secret:file/completion-token", - "auth": null - }), - ] { - assert!(!schema.is_valid(&with(nulled.clone())), "{nulled}"); - assert!(read(&with(nulled.clone())).is_err(), "{nulled}"); + let instance = with(accepted); + assert!(schema.is_valid(&instance)); + assert!(read(&instance).is_ok()); } for refused in [ serde_json::json!({"url": url}), - serde_json::json!({"url": url, "bearerTokenRef": null}), - serde_json::json!({"url": url, "auth": null}), - serde_json::json!({"url": url, "bearerTokenRef": null, "auth": null}), - serde_json::json!({ - "url": url, - "bearerTokenRef": "secret:file/completion-token", - "auth": {"secretRef": "secret:file/completion-key"} - }), - serde_json::json!({ - "url": url, - "auth": {"header": "x api key", "secretRef": "secret:file/completion-key"} - }), - serde_json::json!({ - "url": url, - "auth": {"header": "x-api-key", "secretRef": "completion-key"} - }), - serde_json::json!({"url": url, "auth": {"header": "x-api-key"}}), + serde_json::json!({"url": url, "previousHmacSha256KeyRef": "secret:file/previous"}), + serde_json::json!({"url": url, "hmacSha256KeyRef": null}), + serde_json::json!({"url": url, "hmacSha256KeyRef": "secret:file/current", + "previousHmacSha256KeyRef": null}), + serde_json::json!({"url": url, "hmacSha256KeyRef": "secret:file/current", "bearerTokenRef": "secret:file/retired"}), + serde_json::json!({"url": url, "auth": {"secretRef": "secret:file/retired"}}), ] { - assert!(!schema.is_valid(&with(refused.clone())), "{refused}"); + let instance = with(refused); + assert!(!schema.is_valid(&instance)); + assert!(read(&instance).is_err()); } } @@ -664,7 +612,7 @@ mod tests { instance["reviewCompletionDestinations"] = serde_json::json!({ "review-requester": { "url": "https://requester.example.test/completions", - "bearerTokenRef": "secret:file/completion-token", + "hmacSha256KeyRef": "secret:file/completion-key", "attemptTimeoutMilliseconds": timeout_milliseconds, "maximumAttempts": maximum_attempts, "retryDelaySeconds": retry_seconds @@ -816,16 +764,10 @@ mod tests { } }); instance["reviewCompletionDestinations"] = serde_json::json!({ - "bearer": { + "receiver": { "url": "https://producer.example.test/completions", - "bearerTokenRef": "secret:file/completion-token" - }, - "header": { - "url": "https://another-producer.example.test/completions", - "auth": { - "header": "x-api-key", - "secretRef": "secret:env/COMPLETION_API_KEY" - } + "hmacSha256KeyRef": "secret:file/completion-key", + "previousHmacSha256KeyRef": "secret:env/PREVIOUS_COMPLETION_KEY" } }); instance["taskAuthority"] = serde_json::json!({ @@ -879,8 +821,8 @@ mod tests { "/contextProviders/facility-registry/clientAssertionKeyRef", "/contextProviders/facility-registry/delegatedDisplayExchange/clientIdRef", "/contextProviders/facility-registry/delegatedDisplayExchange/clientAssertionKeyRef", - "/reviewCompletionDestinations/bearer/bearerTokenRef", - "/reviewCompletionDestinations/header/auth/secretRef", + "/reviewCompletionDestinations/receiver/hmacSha256KeyRef", + "/reviewCompletionDestinations/receiver/previousHmacSha256KeyRef", "/taskAuthority/signingKeyRef", ]; for &pointer in &pointers { diff --git a/crates/registry-casework/src/service.rs b/crates/registry-casework/src/service.rs index 034514739a..6ea716557e 100644 --- a/crates/registry-casework/src/service.rs +++ b/crates/registry-casework/src/service.rs @@ -1,5 +1,6 @@ use crate::{PostgresStore, StoreError}; use registry_casework_core::{CaseworkProject, InboxPolicy, ReviewContextProvider}; +use registry_platform_authcommon::FailedCheck; use std::collections::BTreeMap; use std::sync::Arc; #[derive(Clone)] @@ -76,9 +77,12 @@ pub enum ServiceError { #[error("the Casework service configuration is invalid")] Configuration, #[error("the requested review task was not found")] - NotFound, + NotFound(FailedCheck), + /// An absence that conceals nothing and is not counted as a refusal. + #[error("the requested resource was not found")] + Absent, #[error("the caller is not authorized")] - Forbidden, + Forbidden(FailedCheck), #[error(transparent)] ReviewValidation(#[from] registry_casework_core::ReviewValidationError), #[error(transparent)] diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 90639d572d..d4a1b187ff 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -5,6 +5,7 @@ use registry_casework_core::{ ActorContext, BootstrapDirectoryRequest, CaseworkActsAs, DirectoryMember, DirectoryResponse, IssuerPrincipal, TeamRecord, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::SecretResolver; use serde_json::{json, Value}; use std::str::FromStr; @@ -15,8 +16,13 @@ use uuid::Uuid; /// Every schema version, in the order it is applied. The baseline is /// version [`BASELINE_SCHEMA_VERSION`], above every version an earlier /// release applied; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 1] = - [(200, include_str!("../migrations/0200_reviews.sql"))]; +pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ + (200, include_str!("../migrations/0200_reviews.sql")), + ( + 201, + include_str!("../migrations/0201_activation_posture.sql"), + ), +]; /// The baseline schema version. A ledger holding any version below it was /// left by an earlier pre-1.0 release, which this release refuses by name: /// version 100 is the v0.42.0 and v0.43.0 baseline, whose completion outbox @@ -425,7 +431,7 @@ impl PostgresStore { idempotency_key: &str, ) -> Result { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let request_hash = request_hash(request)?; let mut audit = self @@ -528,7 +534,7 @@ impl PostgresStore { actor: &ActorContext, ) -> Result<(i64, Vec), StoreError> { if actor.role != CaseworkActsAs::Administrator { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let mut client = self.client().await?; let transaction = client.transaction().await?; @@ -548,7 +554,7 @@ impl PostgresStore { CaseworkActsAs::Staff => "staff", CaseworkActsAs::Supervisor => "supervisor", CaseworkActsAs::Administrator | CaseworkActsAs::Requester => { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } }; let client = self.client().await?; @@ -755,8 +761,12 @@ pub enum StoreError { AuditUnavailable, #[error("the requested resource was not found")] NotFound, + /// A record the caller named is absent and the answer conceals nothing, + /// so it is not a refusal the operator counts. + #[error("the requested resource was not found")] + Absent, #[error("the caller is not authorized for this operation")] - Forbidden, + Forbidden(FailedCheck), #[error("the expected revision is no longer current")] Conflict, #[error("the review task is already claimed")] @@ -937,12 +947,12 @@ mod schema_version_tests { } } assert!(refuse_unsupported_schema(&[]).is_ok()); - assert!(refuse_unsupported_schema(&[200]).is_ok()); + assert!(refuse_unsupported_schema(&[200, 201]).is_ok()); assert!(matches!( - refuse_unsupported_schema(&[200, 201]), + refuse_unsupported_schema(&[200, 201, 202]), Err(StoreError::SchemaNewer { - found: 201, - supported: 200 + found: 202, + supported: 201 }) )); } diff --git a/crates/registry-casework/src/task_grants.rs b/crates/registry-casework/src/task_grants.rs index d71c7ad2a0..b4fa83a2a6 100644 --- a/crates/registry-casework/src/task_grants.rs +++ b/crates/registry-casework/src/task_grants.rs @@ -2,6 +2,7 @@ use crate::{PostgresStore, StoreError}; use chrono::{DateTime, Utc}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use tokio_postgres::Transaction; @@ -273,7 +274,7 @@ impl PostgresStore { .await? .ok_or(StoreError::NotFound)?; if !template_active(&transaction, &grant.template).await? { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } // The revision-agnostic eligibility call confirms the caller's current // authority without binding it to the retry's original revision. @@ -287,7 +288,7 @@ impl PostgresStore { ) .await? else { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::AccessProfile)); }; let mut request = json!({ "reviewTaskId": grant.task_id, @@ -372,7 +373,8 @@ impl PostgresStore { if serde_json::to_vec(&record)?.len() > 65_536 { return Err(StoreError::Invalid); } - let role = membership_kind(actor.role).ok_or(StoreError::Forbidden)?; + let role = + membership_kind(actor.role).ok_or(StoreError::Forbidden(FailedCheck::Operation))?; transaction .execute( "INSERT INTO casework_review_task_grants( @@ -591,10 +593,12 @@ impl PostgresStore { let grant: ReviewTaskGrant = serde_json::from_value(row.get(0))?; if let Some(actor) = actor { let Some(kind) = membership_kind(actor.role) else { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); }; - if !template_active(&transaction, &grant.template).await? - || !grant.template.eligible_profiles.contains(&actor.profile_id) + if !template_active(&transaction, &grant.template).await? { + return Err(StoreError::Forbidden(FailedCheck::Operation)); + } + if !grant.template.eligible_profiles.contains(&actor.profile_id) || !transaction .query_one( "SELECT EXISTS( @@ -625,7 +629,7 @@ impl PostgresStore { .await? .get::<_, bool>(0) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::AccessProfile)); } } let first_invalidation = transaction @@ -799,7 +803,7 @@ impl TaskAuthority { ) -> Result { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; if now >= grant_expires_at { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::TaskGrantExpired)); } // Evidence checks only the grant deadline and no grant status, so an // Evidence grant is never signed under the deferred window. @@ -809,7 +813,7 @@ impl TaskAuthority { registry_casework_core::TaskGrantBounds::Evidence { .. } ) { - return Err(StoreError::Forbidden); + return Err(StoreError::Forbidden(FailedCheck::Operation)); } let expires = grant_expires_at.min( now.checked_add(registry_casework_core::TASK_ASSERTION_LIFETIME_SECONDS) @@ -851,7 +855,7 @@ impl crate::CaseworkService { pub(crate) fn task_jwks(&self) -> Result { self.task_authority .as_ref() - .ok_or(crate::ServiceError::NotFound)? + .ok_or(crate::ServiceError::Absent)? .jwks() .map_err(Into::into) } @@ -955,7 +959,7 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let template = self .project .task_templates @@ -965,13 +969,13 @@ impl crate::CaseworkService { && template.id == request.template_id && template.version == request.template_version }) - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let Some((request_id, current_revision, subject, assignment_generation)) = self .store .eligible_review_task_template(actor, task_id, template) .await? else { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); }; if current_revision != revision { return Err(StoreError::Conflict.into()); @@ -988,7 +992,7 @@ impl crate::CaseworkService { let values = self.review_grant_fields(task_id, revision, &fields).await?; let subjects = template .disclosed_subjects(&values) - .map_err(|_| crate::ServiceError::Forbidden)?; + .map_err(|_| crate::ServiceError::Forbidden(FailedCheck::Operation))?; let now = now_seconds()?; let grant = ReviewTaskGrant { id: Uuid::new_v4(), @@ -1027,7 +1031,7 @@ impl crate::CaseworkService { .preview_review_task_templates(actor, task_id, source_profile, token) .await?; if previews.task_revision == 0 { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::Visibility)); } let grants = self.store.review_task_grants_for_task(task_id).await?; let mut eligible = false; @@ -1048,7 +1052,7 @@ impl crate::CaseworkService { } } if !eligible { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::AccessProfile)); } Ok(TaskGrantList { grants: grants.iter().map(review_grant_view).collect(), @@ -1063,7 +1067,7 @@ impl crate::CaseworkService { ) -> Result { let stored = self.store.review_task_grant(id).await?; if stored.grant.task_id != task_id { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::TaskGrantBinding)); } self.store .invalidate_review_task_grant(id, "revoked", Some(actor)) @@ -1079,8 +1083,13 @@ impl crate::CaseworkService { id: Uuid, ) -> Result { let stored = self.store.review_task_grant(id).await?; - if stored.invalidated || now_seconds()? >= stored.grant.expires_at { - return Err(crate::ServiceError::Forbidden); + if stored.invalidated { + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); + } + if now_seconds()? >= stored.grant.expires_at { + return Err(crate::ServiceError::Forbidden( + FailedCheck::TaskGrantExpired, + )); } let grant = &stored.grant; let Some(template) = self.project.task_templates.iter().find(|template| { @@ -1090,7 +1099,7 @@ impl crate::CaseworkService { self.store .invalidate_review_task_grant(id, "template", None) .await?; - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); }; let configured_approver_role = self .project @@ -1103,7 +1112,7 @@ impl crate::CaseworkService { .check_review_task_grant_eligibility(grant, template, configured_approver_role) .await? { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); } let fields = template .subjects @@ -1137,15 +1146,19 @@ impl crate::CaseworkService { self.store .invalidate_review_task_grant(id, "source", None) .await?; - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::TaskGrantStatus)); } if !self .store .check_review_task_grant_eligibility(grant, template, configured_approver_role) .await? - || now_seconds()? >= grant.expires_at { - return Err(crate::ServiceError::Forbidden); + return Err(crate::ServiceError::Forbidden(FailedCheck::AccessProfile)); + } + if now_seconds()? >= grant.expires_at { + return Err(crate::ServiceError::Forbidden( + FailedCheck::TaskGrantExpired, + )); } Ok(stored) } @@ -1157,7 +1170,7 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let stored = self.store.review_task_grant(id).await?; require_grant_client(client, &stored.grant.template)?; let stored = self.active_review_task(id).await?; @@ -1174,20 +1187,20 @@ impl crate::CaseworkService { let authority = self .task_authority .as_ref() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::Operation))?; let client = client .matched_client_id() .ok() .flatten() - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::RequesterClient))?; let resource = authority .config .status_clients .get(client) - .ok_or(crate::ServiceError::Forbidden)?; + .ok_or(crate::ServiceError::Forbidden(FailedCheck::RequesterClient))?; let stored = self.store.review_task_grant(id).await?; if stored.grant.template.resource != *resource { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::RequesterClient)); } match self.active_review_task(id).await { Ok(stored) => Ok(active_grant_status( @@ -1197,7 +1210,7 @@ impl crate::CaseworkService { stored.grant.subjects, stored.grant.expires_at, )), - Err(crate::ServiceError::Forbidden) => Ok(inactive_grant_status()), + Err(crate::ServiceError::Forbidden(_)) => Ok(inactive_grant_status()), Err(error) => Err(error), } } @@ -1211,7 +1224,7 @@ fn require_grant_client( || client.claims.sub.as_deref() != Some(template.agent.subject.as_str()) || client.claims.iss.as_deref() != Some(template.agent.issuer.as_str()) { - return Err(crate::ServiceError::NotFound); + return Err(crate::ServiceError::NotFound(FailedCheck::TaskGrantBinding)); } Ok(()) } @@ -1362,7 +1375,7 @@ mod evidence_assertion_tests { template.authorization_mode = registry_casework_core::TaskAuthorizationMode::Deferred; assert!(matches!( authority.assertion_for(Uuid::new_v4(), &template, &holder, &fields, 1000, 200), - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(FailedCheck::Operation)) )); } #[test] @@ -1394,7 +1407,7 @@ mod evidence_assertion_tests { assert!(payload.get("registry_grant_authority").is_none()); assert!(matches!( authority.assertion_for(Uuid::new_v4(), &template(), &holder, &fields, 200, 200), - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(FailedCheck::TaskGrantExpired)) )); } } diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index bac3d445d9..070574187b 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -177,6 +177,7 @@ async fn fixture_for_role_with_templates( migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let (audit, audit_capture) = crate::CaseworkAudit::capture(); let store = PostgresStore::connect_migration(&config, &secrets) @@ -1093,6 +1094,71 @@ async fn eligible_officer_can_revoke_without_holding_the_task_or_reading_the_sou .unwrap(); } +#[tokio::test] +async fn a_revoke_refusal_names_the_template_or_the_profile_that_refused_it() { + let f = fixture(900).await; + let holder = token("human", "human-client", "human", "casework:staff"); + let base = format!("/v1/review-tasks/{}/task-grants", f.review_task); + let (status, grant) = request( + &f, + "POST", + &base, + &holder, + true, + Some(json!({"templateId":"summary","templateVersion":"1"})), + Some("approval-for-refused-revocation"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{grant}"); + let grant_id = Uuid::parse_str(grant["id"].as_str().unwrap()).unwrap(); + let actor = |subject: &str| ActorContext { + principal: IssuerPrincipal { + issuer: ISSUER.into(), + subject: subject.into(), + }, + profile_id: "staff".into(), + role: CaseworkActsAs::Staff, + }; + let db = f.store.client().await.unwrap(); + db.execute( + "INSERT INTO casework_memberships(team_id,issuer,subject,membership_kind) VALUES('team',$1,'revoker','staff')", + &[&ISSUER], + ) + .await + .unwrap(); + db.execute( + "UPDATE casework_meta SET directory_revision=directory_revision+1", + &[], + ) + .await + .unwrap(); + assert!( + matches!( + f.store + .invalidate_review_task_grant(grant_id, "revoked", Some(&actor("outsider"))) + .await, + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) + ), + "a caller outside the eligible team is refused under access-profile" + ); + db.execute("UPDATE casework_task_templates SET active=false", &[]) + .await + .unwrap(); + assert!( + matches!( + f.store + .invalidate_review_task_grant(grant_id, "revoked", Some(&actor("revoker"))) + .await, + Err(StoreError::Forbidden(FailedCheck::Operation)) + ), + "an inactive template is refused under operation" + ); + f.admin + .batch_execute(&format!("DROP SCHEMA {} CASCADE", f.schema)) + .await + .unwrap(); +} + #[tokio::test] async fn review_task_grants_bind_holder_revision_subject_and_revocation() { let f = fixture(900).await; @@ -1848,7 +1914,7 @@ async fn review_task_grant_approval_recovers_a_lost_response_after_the_task_revi f.store .approve_review_task_grant(&actor, "lost-response", grant) .await, - Err(StoreError::Forbidden) + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) )); f.admin diff --git a/crates/registry-casework/src/task_grants/lock_order_tests.rs b/crates/registry-casework/src/task_grants/lock_order_tests.rs index dd74f8df4e..77497b8423 100644 --- a/crates/registry-casework/src/task_grants/lock_order_tests.rs +++ b/crates/registry-casework/src/task_grants/lock_order_tests.rs @@ -49,6 +49,7 @@ async fn store_for_schema(schema: &str, application_name: &str) -> PostgresStore migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_runtime(&config, &secrets) .expect("connect lock-order store") @@ -287,7 +288,7 @@ async fn grant_approval_and_decision_lock_request_before_task_without_deadlock() .expect("lock-order interleaving task"); let approval_outcome = match &approval_result { Ok(_) => "approved".to_owned(), - Err(StoreError::Forbidden) => "forbidden".to_owned(), + Err(StoreError::Forbidden(_)) => "forbidden".to_owned(), Err(StoreError::Postgres(error)) if error.code() == Some(&SqlState::T_R_DEADLOCK_DETECTED) => { @@ -303,7 +304,10 @@ async fn grant_approval_and_decision_lock_request_before_task_without_deadlock() ); assert_eq!(decision_status, StatusCode::NO_CONTENT); assert!( - matches!(approval_result, Err(StoreError::Forbidden)), + matches!( + approval_result, + Err(StoreError::Forbidden(FailedCheck::AccessProfile)) + ), "the queued approval must recheck and refuse the terminal task" ); } diff --git a/crates/registry-casework/src/task_grants/native_exchange_tests.rs b/crates/registry-casework/src/task_grants/native_exchange_tests.rs index 45208e4af6..9e8b1f95b8 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -1114,6 +1114,7 @@ async fn fixture( migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&db_config, &secrets) .unwrap() diff --git a/crates/registry-casework/tests/breg_review_journey.rs b/crates/registry-casework/tests/breg_review_journey.rs index caba45b744..00317ea55a 100644 --- a/crates/registry-casework/tests/breg_review_journey.rs +++ b/crates/registry-casework/tests/breg_review_journey.rs @@ -416,6 +416,7 @@ async fn casework_store() -> (PostgresStore, tokio_postgres::Client, String) { migration_url_ref: format!("secret:env/{name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&config, &secrets) .unwrap() @@ -739,7 +740,7 @@ async fn native_current_source_approval_pattern(pattern: ApprovalPattern, index: Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -804,7 +805,7 @@ async fn native_current_source_approval_pattern(pattern: ApprovalPattern, index: Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); @@ -1194,7 +1195,7 @@ async fn native_proposal_journey(producer_id: &'static str) { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".into())), ) @@ -1277,7 +1278,7 @@ async fn native_proposal_journey(producer_id: &'static str) { Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - registry_platform_httputil::FetchUrlPolicy::dev(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); diff --git a/crates/registry-casework/tests/golden/refusal_responses.json b/crates/registry-casework/tests/golden/refusal_responses.json new file mode 100644 index 0000000000..a04dcbaedb --- /dev/null +++ b/crates/registry-casework/tests/golden/refusal_responses.json @@ -0,0 +1,435 @@ +[ + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "no-authorization", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "basic-scheme", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bearer-with-two-tokens", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "bad-signature", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "wrong-audience", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "expired", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "missing-principal", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "act-on-officer-profile", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "grant-claims-on-officer-profile", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "unknown-profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "scope-missing", + "status": 403 + }, + { + "body": { + "code": "profile.not-human", + "detail": "This action is reserved for a human session.", + "status": 403, + "title": "Human session required", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-human" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "service-on-human-profile", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-with-a-profile-header", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-no-authorization", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "task-assertion-without-its-scope", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-with-a-profile-header", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-no-authorization", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "delegated-read-unknown-policy", + "status": 403 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Casework authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "supervision-list-on-a-staff-profile", + "status": 403 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Casework authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "reviewer-list-on-a-requester-profile", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-with-two-tokens", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-casework/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-not-a-compact-token", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "source-pair-on-a-requester-profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Casework profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-casework/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "name": "source-bearer-refused-by-a-staff-profile-scope", + "status": 403 + } +] diff --git a/crates/registry-casework/tests/human_identity_auth.rs b/crates/registry-casework/tests/human_identity_auth.rs index 1d75c31ec5..c8605cec64 100644 --- a/crates/registry-casework/tests/human_identity_auth.rs +++ b/crates/registry-casework/tests/human_identity_auth.rs @@ -7,6 +7,7 @@ use registry_casework_core::{ AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, CASEWORK_API_VERSION, CASEWORK_KIND, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; @@ -56,7 +57,10 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .expect_err( "a service, missing, or non-string actor kind cannot produce an ActorContext", ); - assert_eq!(refusal, AuthenticationError::NotHuman); + assert_eq!( + refusal, + AuthenticationError::NotHuman(FailedCheck::ActorKind) + ); } let requester = authenticator @@ -81,7 +85,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&requester_with_human_assertion, human_profile) .await .expect_err("the dedicated Requester scope cannot select a human profile"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); } @@ -93,7 +97,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv ) .await .expect_err("selecting Staff does not union the Requester scope or identity class"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let wrong_audience = idp.mint_token(json!({ @@ -107,7 +111,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&wrong_audience, "staff") .await .expect_err("the verifier preserves audience enforcement"), - AuthenticationError::Refused + AuthenticationError::Refused(FailedCheck::TokenAudience) ); let expired = idp.mint_token(json!({ @@ -122,7 +126,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&expired, "staff") .await .expect_err("the verifier preserves expiry enforcement"), - AuthenticationError::Refused + AuthenticationError::Refused(FailedCheck::TokenTime) ); assert_eq!( @@ -133,7 +137,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv ) .await .expect_err("the selected profile still requires its configured scope"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let missing_principal = idp.mint_token(json!({ @@ -146,7 +150,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&missing_principal, "staff") .await .expect_err("a human assertion cannot replace the configured principal claim"), - AuthenticationError::Claims + AuthenticationError::Claims(FailedCheck::TokenClaims) ); let custom_authenticator = authenticator_with_human_identity( @@ -173,7 +177,7 @@ async fn trusted_human_assertion_gates_human_profiles_and_requester_accepts_serv .authenticate(&default_assertion_only, "staff") .await .expect_err("the default assertion cannot satisfy a custom claim contract"), - AuthenticationError::NotHuman + AuthenticationError::NotHuman(FailedCheck::ActorKind) ); idp.stop().await; @@ -208,7 +212,11 @@ async fn delegated_or_grant_bearing_tokens_are_refused_for_officer_profiles_only .authenticate(&idp.mint_token(claims), profile) .await .expect_err("delegated authority cannot enter an officer session"), - AuthenticationError::Refused + AuthenticationError::Refused(if extra.get("act").is_some() { + FailedCheck::Delegation + } else { + FailedCheck::TaskGrantClaims + }) ); } @@ -318,7 +326,7 @@ async fn same_role_profiles_on_one_principal_claim_are_selected_by_their_own_sco ) .await .expect_err("the scope of one staff profile cannot select the other"), - AuthenticationError::Profile + AuthenticationError::Profile(FailedCheck::Scope) ); let selected = authenticator .authenticate( @@ -351,7 +359,7 @@ fn authenticator_for_project_with_human_identity( let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); CaseworkAuthenticator::new( project, diff --git a/crates/registry-casework/tests/migration_pins.rs b/crates/registry-casework/tests/migration_pins.rs index 545c492080..b90a3ccb21 100644 --- a/crates/registry-casework/tests/migration_pins.rs +++ b/crates/registry-casework/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0200_reviews.sql", - "72a4b39c7f2cc64e28c1241b76c7277ee4b2581832ca8a2168d84f46b94d6b98", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0200_reviews.sql", + "72a4b39c7f2cc64e28c1241b76c7277ee4b2581832ca8a2168d84f46b94d6b98", + ), + ( + "0201_activation_posture.sql", + "3eacf388a3ebcc488315291f17c466bcc877932fd2a3c83c2333b36d2d02f85f", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs new file mode 100644 index 0000000000..37426f1463 --- /dev/null +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -0,0 +1,637 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The authentication and profile refusals Casework answers on its HTTP +//! surface, frozen against a checked-in file. +//! +//! Each case drives the real router and records the status, the headers a +//! caller can act on, and the problem body with its `traceId` removed. A +//! change to what a caller sees changes `golden/refusal_responses.json`. +//! `REGISTRY_UPDATE_GOLDEN=1` rewrites the file, and a reviewer reads the +//! diff. +//! +//! Each case also checks what the operator sees: the refusal counts once under +//! its check, and writes one log line that names the check and nothing a +//! caller sent. +//! +//! The router's store points at a PostgreSQL address nothing listens on: +//! every case here is refused before a handler reaches the store. + +use std::path::PathBuf; +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, Response}; +use registry_casework::{ + router_with_recorder, CaseworkAuthenticator, CaseworkService, DatabaseConfig, HttpState, + HumanIdentityConfig, PostgresStore, +}; +use registry_casework_core::{ + AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, + CASEWORK_API_VERSION, CASEWORK_KIND, +}; +use registry_platform_authcommon::{FailedCheck, RefusalRecorder}; +use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{oidc_verifier_config, CapturedDiagnosticLogs, MockIdp}; +use serde_json::{json, Map, Value}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber as _; + +const AUDIENCE: &str = "urn:test:casework"; +const PRINCIPAL: &str = "urn:test:person:refusal-golden"; +const PROFILE_HEADER: &str = "registry-casework-profile"; +const SOURCE_AUTHORIZATION_HEADER: &str = "registry-source-authorization"; +const SOURCE_PROFILE_HEADER: &str = "registry-source-profile"; +const DELEGATED_READER_HEADER: &str = "registry-casework-delegated-reader"; +const TASK_ID: &str = "00000000-0000-4000-8000-000000000001"; +const GRANT_ID: &str = "00000000-0000-4000-8000-000000000002"; + +struct Case { + name: &'static str, + /// The check the operator's counter and log line name for this refusal. + check: &'static str, + method: &'static str, + path: String, + headers: Vec<(&'static str, String)>, +} + +fn case( + name: &'static str, + check: &'static str, + method: &'static str, + path: &str, + headers: Vec<(&'static str, String)>, +) -> Case { + Case { + name, + check, + method, + path: path.to_owned(), + headers, + } +} + +/// The scope a token holds in the cases that refuse on scope. It is the +/// caller's value, so no log line may carry it. +const HELD_CANARY_SCOPE: &str = "casework:unrelated"; + +fn bearer(token: &str) -> String { + format!("Bearer {token}") +} + +fn claims(scope: &str, kind: Option<&str>) -> Value { + let mut claims = json!({ + "aud": AUDIENCE, + "registry_principal": PRINCIPAL, + "scope": scope, + }); + if let Some(kind) = kind { + claims["registry_actor_kind"] = json!(kind); + } + claims +} + +fn with(mut claims: Value, extra: Value) -> Value { + claims + .as_object_mut() + .expect("claims are an object") + .extend(extra.as_object().expect("extra is an object").clone()); + claims +} + +fn cases(idp: &MockIdp) -> Vec { + let staff = idp.mint_token(claims("casework:staff", Some("human"))); + let service_on_staff = idp.mint_token(claims("casework:staff", Some("service"))); + let requester = idp.mint_token(claims("casework:request", Some("service"))); + let other_scope = idp.mint_token(claims("casework:unrelated", Some("human"))); + let wrong_audience = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"aud": "urn:test:other-service"}), + )); + let expired = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"exp": chrono::Utc::now().timestamp() - 120}), + )); + let no_principal = idp.mint_token(json!({ + "aud": AUDIENCE, + "scope": "casework:staff", + "registry_actor_kind": "human", + })); + let delegated = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"act": {"sub": "agent"}}), + )); + let grant_bearing = idp.mint_token(with( + claims("casework:staff", Some("human")), + json!({"registry_grant_id": "grant"}), + )); + // The first signature character carries six signature bits, so changing it + // always changes the signature. The last one also carries padding bits. + let start = staff.rfind('.').expect("a token has a signature") + 1; + let first = staff[start..] + .chars() + .next() + .expect("a signature is not empty"); + let mut bad_signature = staff.clone(); + bad_signature.replace_range(start..=start, if first == 'A' { "B" } else { "A" }); + + let list = "/v1/review-tasks"; + let as_staff = |token: &str| { + vec![ + ("authorization", bearer(token)), + (PROFILE_HEADER, "staff".to_owned()), + ] + }; + let assertion = format!("/v1/task-grants/{GRANT_ID}/assertion"); + let history = format!("/v1/review-requests/{TASK_ID}/history"); + vec![ + case( + "no-authorization", + "credential-missing", + "GET", + list, + vec![(PROFILE_HEADER, "staff".to_owned())], + ), + case( + "basic-scheme", + "credential-missing", + "GET", + list, + vec![ + ("authorization", "Basic abc".to_owned()), + (PROFILE_HEADER, "staff".to_owned()), + ], + ), + case( + "bearer-with-two-tokens", + "credential-malformed", + "GET", + list, + vec![ + ("authorization", "Bearer one two".to_owned()), + (PROFILE_HEADER, "staff".to_owned()), + ], + ), + case( + "bearer-not-a-compact-token", + "credential-malformed", + "GET", + list, + as_staff("not-a-token"), + ), + case( + "bad-signature", + "token-signature", + "GET", + list, + as_staff(&bad_signature), + ), + case( + "wrong-audience", + "token-audience", + "GET", + list, + as_staff(&wrong_audience), + ), + case("expired", "token-time", "GET", list, as_staff(&expired)), + case( + "missing-principal", + "token-claims", + "GET", + list, + as_staff(&no_principal), + ), + case( + "act-on-officer-profile", + "delegation", + "GET", + list, + as_staff(&delegated), + ), + case( + "grant-claims-on-officer-profile", + "task-grant-claims", + "GET", + list, + as_staff(&grant_bearing), + ), + case( + "unknown-profile", + "access-profile", + "GET", + list, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "nobody".to_owned()), + ], + ), + case( + "scope-missing", + "scope", + "GET", + list, + as_staff(&other_scope), + ), + case( + "service-on-human-profile", + "actor-kind", + "GET", + list, + as_staff(&service_on_staff), + ), + case( + "task-assertion-with-a-profile-header", + "access-profile", + "POST", + &assertion, + as_staff(&staff), + ), + case( + "task-assertion-no-authorization", + "credential-missing", + "POST", + &assertion, + vec![], + ), + case( + "task-assertion-bearer-not-a-compact-token", + "credential-malformed", + "POST", + &assertion, + vec![("authorization", bearer("not-a-token"))], + ), + case( + "task-assertion-without-its-scope", + "scope", + "POST", + &assertion, + vec![("authorization", bearer(&staff))], + ), + case( + "delegated-read-with-a-profile-header", + "access-profile", + "GET", + "/v1/delegated-staff/review-tasks", + as_staff(&staff), + ), + case( + "delegated-read-no-authorization", + "credential-missing", + "GET", + "/v1/delegated-staff/review-tasks", + vec![(DELEGATED_READER_HEADER, "reader".to_owned())], + ), + case( + "delegated-read-unknown-policy", + "access-profile", + "GET", + "/v1/delegated-staff/review-tasks", + vec![ + ("authorization", bearer(&staff)), + (DELEGATED_READER_HEADER, "reader".to_owned()), + ], + ), + case( + "supervision-list-on-a-staff-profile", + "operation", + "GET", + "/v1/review-tasks/supervision", + as_staff(&staff), + ), + case( + "reviewer-list-on-a-requester-profile", + "operation", + "GET", + list, + vec![ + ("authorization", bearer(&requester)), + (PROFILE_HEADER, "requester".to_owned()), + ], + ), + case( + "source-bearer-with-two-tokens", + "credential-malformed", + "GET", + &history, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, "Bearer one two".to_owned()), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-bearer-not-a-compact-token", + "credential-malformed", + "GET", + &history, + vec![ + ("authorization", bearer(&staff)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer("not-a-token")), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-pair-on-a-requester-profile", + "access-profile", + "GET", + &history, + vec![ + ("authorization", bearer(&requester)), + (PROFILE_HEADER, "requester".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer(&staff)), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + case( + "source-bearer-refused-by-a-staff-profile-scope", + "scope", + "GET", + &history, + vec![ + ("authorization", bearer(&other_scope)), + (PROFILE_HEADER, "staff".to_owned()), + (SOURCE_AUTHORIZATION_HEADER, bearer(&staff)), + (SOURCE_PROFILE_HEADER, "review-agent".to_owned()), + ], + ), + ] +} + +fn profile(id: &str, scope: &str, role: CaseworkActsAs) -> AccessProfile { + AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "registry_principal".to_owned(), + required_scopes: vec![scope.to_owned()], + acts_as: role, + } +} + +fn project() -> CaseworkProject { + let starter = CaseworkProject::from_slice(include_bytes!( + "../../../products/casework/examples/standalone-decision/casework.yaml" + )) + .expect("canonical review fixture"); + CaseworkProject { + task_templates: Vec::new(), + api_version: CASEWORK_API_VERSION.to_owned(), + kind: CASEWORK_KIND.to_owned(), + project: ProjectIdentity::new("refusal-golden-test".parse().unwrap(), "1".to_owned()), + access_profiles: vec![ + profile("staff", "casework:staff", CaseworkActsAs::Staff), + profile("requester", "casework:request", CaseworkActsAs::Requester), + ], + queues: vec![QueuePolicy { + id: "decisions".to_owned(), + label: "Decisions".to_owned(), + }], + teams: starter.teams, + context_providers: Vec::new(), + review_policies: starter.review_policies, + trusted_producers: starter.trusted_producers, + calendars: Vec::new(), + clocks: Vec::new(), + inbox: InboxPolicy::default(), + } +} + +/// A store whose pool has no server behind it. It connects only when used. +fn unconnected_store(root: &std::path::Path) -> PostgresStore { + use std::os::unix::fs::PermissionsExt as _; + let root = std::fs::canonicalize(root).expect("canonical secret root"); + let secrets_dir = root.join("secrets"); + std::fs::create_dir(&secrets_dir).expect("secret directory"); + std::fs::set_permissions(&secrets_dir, std::fs::Permissions::from_mode(0o700)) + .expect("private secret directory"); + let file = secrets_dir.join("database-url"); + std::fs::write(&file, "postgresql://casework@127.0.0.1:9/casework").expect("database url"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("private database url"); + let secrets = + SecretResolver::new([SecretProvider::File], &secrets_dir).expect("secret resolver"); + PostgresStore::connect_runtime( + &DatabaseConfig { + runtime_url_ref: "secret:file/database-url".to_owned(), + migration_url_ref: "secret:file/database-url".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }, + &secrets, + ) + .expect("an unconnected runtime store") +} + +fn app(idp: &MockIdp, root: &std::path::Path, recorder: Arc) -> axum::Router { + let project = project(); + let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )); + let authenticator = CaseworkAuthenticator::new( + &project, + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.to_owned()]), + keys, + HumanIdentityConfig::default(), + ); + let service = CaseworkService::new(unconnected_store(root), project.clone(), []) + .expect("a service with no providers"); + router_with_recorder( + HttpState { + service, + authenticator: Arc::new(authenticator), + project: Arc::new(project), + }, + recorder, + ) +} + +const KEPT_HEADERS: [&str; 5] = [ + "content-type", + "www-authenticate", + "retry-after", + "cache-control", + "x-content-type-options", +]; + +async fn observe(app: &axum::Router, case: &Case) -> Value { + let mut request = Request::builder().method(case.method).uri(&case.path); + for (name, value) in &case.headers { + request = request.header(*name, value); + } + let response: Response = app + .clone() + .oneshot(request.body(Body::empty()).expect("request")) + .await + .expect("response"); + let status = response.status().as_u16(); + let mut headers = Map::new(); + for name in KEPT_HEADERS { + if let Some(value) = response.headers().get(name) { + headers.insert( + name.to_owned(), + json!(value.to_str().expect("a printable header")), + ); + } + } + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .expect("body"); + let mut body: Value = serde_json::from_slice(&bytes).expect("a JSON problem body"); + body.as_object_mut() + .expect("a problem object") + .remove("traceId") + .expect("every problem carries a traceId"); + json!({"name": case.name, "status": status, "headers": headers, "body": body}) +} + +fn golden_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusal_responses.json") +} + +#[tokio::test] +async fn authentication_and_profile_refusals_match_the_checked_in_answers() { + let idp = MockIdp::start().await; + let mut observed = Vec::new(); + let cases = cases(&idp); + let tokens: Vec = cases + .iter() + .flat_map(|case| case.headers.iter().map(|(_, value)| value.clone())) + .collect(); + for case in &cases { + // A recorder per case keeps each log line inside its check's budget + // of five lines a minute, however many cases share a check. + let root = tempfile::tempdir().expect("temporary directory"); + let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); + let app = app(&idp, root.path(), Arc::clone(&recorder)); + let logs = CapturedDiagnosticLogs::default(); + observed.push(observe(&app, case).with_subscriber(logs.subscriber()).await); + assert_eq!( + recorder.counter().get(&[case.check]), + Some(1), + "{} counts once under {}", + case.name, + case.check + ); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 1, "{} counts under no other check", case.name); + assert_one_value_free_line(case, &logs, &tokens); + } + let root = tempfile::tempdir().expect("temporary directory"); + let recorder = Arc::new(RefusalRecorder::new("casework").expect("the casework recorder")); + let app = app(&idp, root.path(), Arc::clone(&recorder)); + assert_absence_is_not_counted(&app, &recorder).await; + idp.stop().await; + let observed = Value::Array(observed); + let rendered = format!("{}\n", serde_json::to_string_pretty(&observed).unwrap()); + if std::env::var_os("REGISTRY_UPDATE_GOLDEN").is_some() { + std::fs::write(golden_path(), rendered).expect("write the golden file"); + return; + } + let expected = std::fs::read_to_string(golden_path()).expect( + "tests/golden/refusal_responses.json is missing; run once with REGISTRY_UPDATE_GOLDEN=1", + ); + assert_eq!( + rendered, expected, + "a refusal answer changed; if the change is intended, rerun with REGISTRY_UPDATE_GOLDEN=1 and review the diff" + ); +} + +/// A plain absence conceals nothing, so it is neither counted nor logged as a +/// refusal. The task grant key set route is unauthenticated and answers 404 +/// when task grants are not configured. +async fn assert_absence_is_not_counted(app: &axum::Router, recorder: &RefusalRecorder) { + let logs = CapturedDiagnosticLogs::default(); + let observed = observe( + app, + &case( + "jwks-without-task-grants", + "visibility", + "GET", + "/.well-known/jwks.json", + vec![], + ), + ) + .with_subscriber(logs.subscriber()) + .await; + assert_eq!(observed["status"], 404); + assert_eq!(observed["body"]["code"], "request.not-found"); + let counted: u64 = FailedCheck::ALL + .iter() + .map(|check| recorder.counter().get(&[check.as_str()]).unwrap_or(0)) + .sum(); + assert_eq!(counted, 0, "an absence records no refusal"); + assert_eq!(logs.text(), "", "an absence writes no refusal line"); +} + +/// The one line a refusal wrote names the check, carries a trace id, and +/// holds no credential, claim or profile a caller sent. +fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens: &[String]) { + let text = logs.text(); + let lines: Vec = text + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON log line")) + .collect(); + assert_eq!(lines.len(), 1, "{}: {text}", case.name); + let fields = lines[0]["fields"].as_object().expect("fields"); + assert_eq!(fields["message"], "request refused", "{}", case.name); + assert_eq!(fields["decision"], "refused", "{}", case.name); + assert_eq!(fields["failed_check"], case.check, "{}", case.name); + assert_eq!(fields["suppressed"], 0, "{}", case.name); + assert_eq!( + fields["trace_id"].as_str().map(str::len), + Some(32), + "{}", + case.name + ); + if case.check == "scope" { + // A scope refusal names what the operator declared, never the scopes + // the token held. + assert_eq!(fields["scope_claim"], "scope", "{}", case.name); + assert!( + fields["required_scope"].is_string(), + "{}: the line names the scope the operation needs", + case.name + ); + assert!(!text.contains(HELD_CANARY_SCOPE), "{}: {text}", case.name); + if case.name == "scope-missing" { + assert_eq!(fields["required_scope"], "casework:staff", "{}", case.name); + assert_eq!(fields["access_profile"], "staff", "{}", case.name); + } + } + for name in fields.keys() { + assert!( + [ + "message", + "decision", + "failed_check", + "suppressed", + "trace_id", + "remedy", + "scope_claim", + "required_scope", + "access_profile" + ] + .contains(&name.as_str()), + "{}: unexpected field {name}", + case.name + ); + } + // The profile id the operator declared is also a header value the caller + // sent, so the line may name it. Nothing else the caller sent may appear. + let declared_profile = fields.get("access_profile").and_then(Value::as_str); + for secret in tokens.iter().chain([&PRINCIPAL.to_owned()]) { + if Some(secret.as_str()) == declared_profile { + continue; + } + assert!(!text.contains(secret.as_str()), "{}: {secret}", case.name); + } +} diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 3b3e251cf7..9f94729074 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -4,6 +4,7 @@ use async_trait::async_trait; use chrono::{TimeDelta, Utc}; use registry_casework::*; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::{json, Value}; use std::{ @@ -216,6 +217,7 @@ impl Fixture { migration_url_ref: format!("secret:env/{variable}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let (audit, capture) = CaseworkAudit::capture(); let migration = PostgresStore::connect_migration(&config, &secrets) @@ -348,7 +350,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "reviewer-create" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let accepted = f.create("notice").await; assert!(f.request("notice").policy.matches(&accepted.policy)); @@ -370,7 +372,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { accepted.request_id ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) )); assert!(matches!( f.service @@ -383,7 +385,7 @@ async fn exact_policy_admission_and_independent_producer_authority() { "producer-claim" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } #[tokio::test] @@ -520,7 +522,7 @@ async fn current_policy_selection_recovers_before_updates_and_requires_live_auth revoked .create_review_request(&producer, request, "current-policy") .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::AccessProfile)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -582,7 +584,7 @@ async fn concurrent_current_policy_acceptance_freezes_one_binding_and_refuses_in f.service .create_review_request(&producer, wrong_subject, "incompatible-subject") .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } @@ -632,7 +634,9 @@ async fn submitted_two_stage_review_pins_policy_receipts_and_terminal_feed() { "same-reviewer" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let held = f.claim(second, "b").await; f.service @@ -1204,7 +1208,7 @@ async fn source_visibility_and_directory_authority_are_both_live_at_caseload_app } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); } @@ -1471,7 +1475,7 @@ async fn admission_namespace_cannot_substitute_the_pinned_provider_namespace() { "wrong-namespace" ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!( f.db.query_one("SELECT count(*) FROM casework_review_requests", &[]) @@ -1655,7 +1659,7 @@ async fn clock_recompute_uses_pinned_calendar_and_fences_changed_holiday_inputs( } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); } diff --git a/crates/registry-casework/tests/review_directory_postgres.rs b/crates/registry-casework/tests/review_directory_postgres.rs index 5df3ea1702..dd08cfd04c 100644 --- a/crates/registry-casework/tests/review_directory_postgres.rs +++ b/crates/registry-casework/tests/review_directory_postgres.rs @@ -2,6 +2,7 @@ use chrono::{TimeDelta, Utc}; use registry_casework::{CaseworkService, DatabaseConfig, PostgresStore, ServiceError, StoreError}; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::json; use std::{collections::BTreeSet, env}; @@ -106,6 +107,7 @@ async fn fixture() -> Fixture { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration = PostgresStore::connect_migration(&config, &secrets) .expect("migration store") @@ -527,7 +529,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let bulk_a = (0..100) @@ -553,7 +557,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let staff_absence_people = fixture .service @@ -583,7 +589,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let revision = fixture .service @@ -743,7 +751,9 @@ async fn directory_targets_are_paged_query_bound_and_recheck_current_authority() None, ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); let unrelated_supervisor = actor("unrelated", CaseworkActsAs::Supervisor, "supervisor"); let empty = fixture @@ -1006,7 +1016,9 @@ async fn supervisor_cannot_record_cover_from_an_unsupervised_shared_team() { "unsupervised-shared-cover", ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); } @@ -1166,7 +1178,9 @@ async fn absence_update_preserves_owner_and_delete_replay_rechecks_current_autho "delete-own-absence", ) .await, - Err(ServiceError::Store(StoreError::Forbidden)) + Err(ServiceError::Store(StoreError::Forbidden( + FailedCheck::Operation + ))) )); } diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index 9ed3bbdc23..777208804d 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -26,7 +26,10 @@ use registry_casework_client::{ use registry_casework_core::*; use registry_platform_config::{SecretProvider, SecretResolver}; -use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_httputil::{ + probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}, + FetchUrlPolicy, +}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; use serde_json::{json, Value}; @@ -487,6 +490,7 @@ async fn app_with_project_options( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; PostgresStore::connect_migration(&database_config, &secrets) .expect("migration store") @@ -548,7 +552,7 @@ async fn app_with_project_options( Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ) @@ -900,6 +904,28 @@ fn create_http_request(body: &ReviewCreateRequest, token: Option<&str>) -> Reque .expect("review HTTP request") } +#[tokio::test] +async fn health_and_ready_answer_the_shared_probe_bodies_without_a_token() { + let idp = MockIdp::start().await; + let (app, _service, _revoked, _changed, _failure, _source_state) = app(&idp).await; + for (path, expected) in [(HEALTH_PATH, HEALTH_BODY), (READY_PATH, READY_BODY)] { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + assert_eq!( + response.headers().get(CONTENT_TYPE).unwrap(), + "application/json", + "{path}" + ); + let body = to_bytes(response.into_body(), 1024).await.unwrap(); + assert_eq!(body.as_ref(), expected.as_bytes(), "{path}"); + } + idp.stop().await; +} + #[tokio::test] async fn delegated_reader_credential_cannot_enter_producer_create_or_cancel_routes() { let idp = MockIdp::start().await; @@ -5828,7 +5854,7 @@ async fn separate_human_source_credentials_bind_before_empty_inbox_and_guard_mut let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let authenticator = CaseworkAuthenticator::new( &project, diff --git a/crates/registry-casework/tests/review_migration_postgres.rs b/crates/registry-casework/tests/review_migration_postgres.rs index 7f2af8e781..7d9434980b 100644 --- a/crates/registry-casework/tests/review_migration_postgres.rs +++ b/crates/registry-casework/tests/review_migration_postgres.rs @@ -94,6 +94,7 @@ impl Fixture { migration_url_ref: reference, ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; Self::open(database, &url, url.clone(), schema).await } @@ -119,6 +120,7 @@ impl Fixture { migration_url_ref: secret_ref(&url), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; Self::open(database, &url, runtime_url, schema).await } @@ -344,7 +346,7 @@ async fn plan_against_an_empty_database_writes_nothing() { assert_eq!(plan.database_id_check, DatabaseIdCheck::NotRecorded); assert_eq!(plan.plan_kind, PlanKind::Initial); assert_eq!(plan.schema_version, None); - assert_eq!(plan.pending_schema_versions.len(), 1); + assert_eq!(plan.pending_schema_versions.len(), 2); assert!(plan.changes_pending, "{:?}", plan.refusals); assert_eq!( fixture.relation_count().await, @@ -368,7 +370,7 @@ async fn initial_apply_records_the_package_and_a_previous_package_reapplies_as_a .expect("initial apply"); assert_eq!(applied.activation.plan_kind, PlanKind::Initial); assert_eq!(applied.activation.role_mode, RoleMode::Single); - assert_eq!(applied.schema_versions_applied, vec![200]); + assert_eq!(applied.schema_versions_applied, vec![200, 201]); fixture .apply(&candidate(&project, &second, &[])) .await @@ -745,7 +747,7 @@ async fn split_role_runtime_cannot_write_the_ledgers_but_still_serves() { ); let client = connect(&fixture.runtime_url).await; for statement in [ - "INSERT INTO casework_activations(activation_id,apply_order,package_digest,database_id,plan_kind,role_mode) VALUES(gen_random_uuid(),99,'sha256:0000000000000000000000000000000000000000000000000000000000000000','x','initial','single')", + "INSERT INTO casework_activations(activation_id,apply_order,package_digest,database_id,plan_kind,role_mode,posture) VALUES(gen_random_uuid(),99,'sha256:0000000000000000000000000000000000000000000000000000000000000000','x','initial','single','production')", "UPDATE casework_activations SET database_id='x'", "DELETE FROM casework_activations", "TRUNCATE casework_activations", diff --git a/crates/registry-casework/tests/review_payment_fixture_postgres.rs b/crates/registry-casework/tests/review_payment_fixture_postgres.rs index c047d0c618..dad6a9dff1 100644 --- a/crates/registry-casework/tests/review_payment_fixture_postgres.rs +++ b/crates/registry-casework/tests/review_payment_fixture_postgres.rs @@ -4,6 +4,7 @@ use std::{ collections::{BTreeMap, BTreeSet}, env, sync::{Arc, Mutex}, + time::{SystemTime, UNIX_EPOCH}, }; use axum::{ @@ -11,7 +12,7 @@ use axum::{ http::{HeaderMap, StatusCode}, response::IntoResponse, routing::post, - Json, Router, + Router, }; use registry_casework::{ router, CaseworkAuthenticator, CaseworkService, DatabaseConfig, HttpState, HumanIdentityConfig, @@ -27,6 +28,9 @@ use registry_casework_core::{ CASEWORK_PROFILE_HEADER, REVIEW_PROFILE_HEADER, }; use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_crypto::delivery_signature::{ + sign, verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, +}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; @@ -38,7 +42,7 @@ use uuid::Uuid; const ISSUER: &str = "https://payments.example.test"; const BATCH_ID: &str = "batch-2026-09"; const AUDIENCE: &str = "urn:test:casework-payment-review"; -const RECEIVER_TOKEN: &str = "payment-sender-secret-canary"; +const RECEIVER_KEY: &str = "synthetic-payment-signing-key!!!"; const RECEIVER_BINDING: &str = "payment-service-recipient-canary"; const PRIVATE_REFERENCE: &str = "private-payment-reference-canary"; @@ -114,30 +118,71 @@ struct ReceiverHttpState { store: ReceiverStore, } +fn completion_keys(key: &str) -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(key.as_bytes()).unwrap(), None).unwrap() +} + +fn signed_completion( + request: reqwest::RequestBuilder, + event: &ReviewCompletion, + key: &str, + binding: &str, +) -> reqwest::RequestBuilder { + let body = serde_json::to_vec(event).unwrap(); + let id = event.event_id.to_string(); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let signature = sign(&completion_keys(key), &id, timestamp, &body).unwrap(); + request + .header("accept", "application/json") + .header("content-type", "application/json") + .header("webhook-id", id) + .header("webhook-timestamp", timestamp.to_string()) + .header("webhook-signature", signature) + .header("registry-recipient-binding", binding) + .body(body) +} + async fn receive_completion( State(state): State, headers: HeaderMap, - Json(event): Json, + body: axum::body::Bytes, ) -> impl IntoResponse { - let authenticated = headers - .get("authorization") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == format!("Bearer {RECEIVER_TOKEN}")); - if !authenticated { + let header = |name| headers.get(name).and_then(|value| value.to_str().ok()); + if header("registry-recipient-binding") != Some(RECEIVER_BINDING) { + return StatusCode::UNAUTHORIZED; + } + let (Some(id), Some(timestamp), Some(signature)) = ( + header("webhook-id"), + header("webhook-timestamp"), + header("webhook-signature"), + ) else { + return StatusCode::UNAUTHORIZED; + }; + if verify( + &completion_keys(RECEIVER_KEY), + SignedContent { + id, + timestamp, + signature, + body: &body, + }, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .is_err() + { return StatusCode::UNAUTHORIZED; } - let intended_recipient = headers - .get("registry-recipient-binding") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == RECEIVER_BINDING); - if !intended_recipient { - return StatusCode::FORBIDDEN; + if header("content-type") != Some("application/json") { + return StatusCode::UNSUPPORTED_MEDIA_TYPE; } - let idempotency_matches = headers - .get("idempotency-key") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == event.event_id.to_string()); - if !idempotency_matches { + let Ok(event) = serde_json::from_slice::(&body) else { + return StatusCode::BAD_REQUEST; + }; + if id != event.event_id.to_string() { return StatusCode::BAD_REQUEST; } @@ -440,6 +485,7 @@ async fn fixture_for_issuer( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; PostgresStore::connect_migration(&database_config, &secrets) .expect("payment migration store") @@ -586,7 +632,7 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound Arc::new(JwksFetcher::new_with_fetch_url_policy( idp.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), HumanIdentityConfig::default(), ); @@ -768,12 +814,7 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound completed_at: result.completed_at, }; let completion_body = serde_json::to_string(&completion).expect("completion JSON"); - for canary in [ - RECEIVER_TOKEN, - RECEIVER_BINDING, - PRIVATE_REFERENCE, - BATCH_ID, - ] { + for canary in [RECEIVER_KEY, RECEIVER_BINDING, PRIVATE_REFERENCE, BATCH_ID] { assert!(!completion_body.contains(canary)); } @@ -786,34 +827,31 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound }), ) .await; - let wrong_sender = client - .post(format!("{}/completion", receiver.base_url)) - .bearer_auth("wrong-sender-secret-canary") - .header("registry-recipient-binding", RECEIVER_BINDING) - .header("idempotency-key", completion.event_id.to_string()) - .json(&completion) - .send() - .await - .expect("wrong sender completion response"); + let wrong_sender = signed_completion( + client.post(format!("{}/completion", receiver.base_url)), + &completion, + "synthetic-invalid-signing-key!!!", + RECEIVER_BINDING, + ) + .send() + .await + .expect("wrong sender completion response"); assert_eq!(wrong_sender.status(), StatusCode::UNAUTHORIZED); assert!(wrong_sender .bytes() .await .expect("wrong sender body") .is_empty()); - let wrong_recipient = client - .post(format!("{}/completion", receiver.base_url)) - .bearer_auth(RECEIVER_TOKEN) - .header( - "registry-recipient-binding", - "different-payment-recipient-canary", - ) - .header("idempotency-key", completion.event_id.to_string()) - .json(&completion) - .send() - .await - .expect("wrong recipient completion response"); - assert_eq!(wrong_recipient.status(), StatusCode::FORBIDDEN); + let wrong_recipient = signed_completion( + client.post(format!("{}/completion", receiver.base_url)), + &completion, + RECEIVER_KEY, + "different-payment-recipient-canary", + ) + .send() + .await + .expect("wrong recipient completion response"); + assert_eq!(wrong_recipient.status(), StatusCode::UNAUTHORIZED); assert!(wrong_recipient .bytes() .await @@ -824,15 +862,15 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound 0 ); - let lost_ack = client - .post(format!("{}/completion", receiver.base_url)) - .bearer_auth(RECEIVER_TOKEN) - .header("registry-recipient-binding", RECEIVER_BINDING) - .header("idempotency-key", completion.event_id.to_string()) - .json(&completion) - .send() - .await - .expect("lost acknowledgement completion response"); + let lost_ack = signed_completion( + client.post(format!("{}/completion", receiver.base_url)), + &completion, + RECEIVER_KEY, + RECEIVER_BINDING, + ) + .send() + .await + .expect("lost acknowledgement completion response"); assert_eq!(lost_ack.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(receiver_store.unmatched_count(), 1); receiver.stop().await; @@ -845,15 +883,15 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound }), ) .await; - let duplicate = client - .post(format!("{}/completion", restarted_receiver.base_url)) - .bearer_auth(RECEIVER_TOKEN) - .header("registry-recipient-binding", RECEIVER_BINDING) - .header("idempotency-key", completion.event_id.to_string()) - .json(&completion) - .send() - .await - .expect("duplicate completion after receiver restart"); + let duplicate = signed_completion( + client.post(format!("{}/completion", restarted_receiver.base_url)), + &completion, + RECEIVER_KEY, + RECEIVER_BINDING, + ) + .send() + .await + .expect("duplicate completion after receiver restart"); assert_eq!(duplicate.status(), StatusCode::NO_CONTENT); assert_eq!( receiver_store.inbox.lock().expect("receiver inbox").len(), @@ -959,11 +997,11 @@ async fn payment_http_push_and_feed_recovery_preserve_receiver_and_release_bound let diagnostics = receiver_store.diagnostics(); for canary in [ - RECEIVER_TOKEN, + RECEIVER_KEY, RECEIVER_BINDING, PRIVATE_REFERENCE, BATCH_ID, - "wrong-sender-secret-canary", + "synthetic-invalid-signing-key!!!", "different-payment-recipient-canary", ] { assert!(!String::from_utf8_lossy(&first_feed_bytes).contains(canary)); diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index e2261c0c35..bf79c50c75 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -19,6 +19,7 @@ use registry_casework::{ ReviewRuntimeError, ReviewTaskDecisionRequest, RuntimeError, StoreError, }; use registry_casework_core::*; +use registry_platform_authcommon::FailedCheck; use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::json; use sha2::{Digest, Sha256}; @@ -530,6 +531,7 @@ async fn fixture() -> Fixture { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration = PostgresStore::connect_migration(&database_config, &secrets) .expect("migration store") @@ -837,31 +839,51 @@ struct DurableCompletionReceiver { observations: Arc>>, } +const COMPLETION_TEST_KEY: &str = "synthetic-test-key-not-for-use!!"; + async fn durable_completion_receiver( State(state): State, headers: axum::http::HeaderMap, - axum::Json(event): axum::Json, + body: axum::body::Bytes, ) -> StatusCode { - if headers - .get("authorization") - .and_then(|value| value.to_str().ok()) - != Some("Bearer canary-completion-secret") + use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, + }; + + let value = |name| headers.get(name).and_then(|value| value.to_str().ok()); + let (Some(id), Some(timestamp), Some(signature)) = ( + value("webhook-id"), + value("webhook-timestamp"), + value("webhook-signature"), + ) else { + return StatusCode::UNAUTHORIZED; + }; + let keys = DeliveryKeys::new( + DeliveryKey::new(COMPLETION_TEST_KEY.as_bytes()).unwrap(), + None, + ) + .unwrap(); + if verify( + &keys, + SignedContent { + id, + timestamp, + signature, + body: &body, + }, + std::time::SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .is_err() { return StatusCode::UNAUTHORIZED; } - let key = headers - .get("idempotency-key") - .unwrap() - .to_str() - .unwrap() - .to_owned(); - let recipient = headers - .get("registry-recipient-binding") - .unwrap() - .to_str() - .unwrap() - .to_owned(); - assert_eq!(key, event.event_id.to_string()); + let Ok(event) = serde_json::from_slice::(&body) else { + return StatusCode::BAD_REQUEST; + }; + assert_eq!(id, event.event_id.to_string()); + let key = id.to_owned(); + let recipient = value("registry-recipient-binding").unwrap().to_owned(); let payload = serde_json::to_value(&event).unwrap(); state .observations @@ -943,7 +965,7 @@ async fn at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhaus store.clone(), "registry-completion", url.clone(), - "canary-completion-secret", + COMPLETION_TEST_KEY, ) .with_subscriber(subscriber.clone()) .await @@ -1015,7 +1037,7 @@ async fn at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhaus let rendered = serde_json::to_string(&entries).unwrap(); for canary in [ "canary-private-destination", - "canary-completion-secret", + COMPLETION_TEST_KEY, "canary-durable-receiver-subject", "canary-terminal-receiver-subject", &request_id.to_string(), @@ -1078,7 +1100,7 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { fixture.store.clone(), "registry-completion", completion_url.clone(), - "completion-secret", + COMPLETION_TEST_KEY, )); tokio::time::timeout( std::time::Duration::from_secs(5), @@ -1134,7 +1156,7 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { fixture.store.clone(), "registry-completion", completion_url.clone(), - "completion-secret", + COMPLETION_TEST_KEY, ) .await .expect("recover the lapsed completion lease"); @@ -1171,7 +1193,7 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { fixture.store.clone(), "registry-completion", completion_url.clone(), - "completion-secret", + COMPLETION_TEST_KEY, )); tokio::time::timeout( std::time::Duration::from_secs(5), @@ -1231,7 +1253,7 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { fixture.store.clone(), "registry-completion", completion_url, - "completion-secret", + COMPLETION_TEST_KEY, ) .await .expect("deliver the later completion"); @@ -1995,7 +2017,7 @@ async fn recovery_pins_policy_and_terminal_settlement_emits_atomically() { .service_v1 .review_accountability(&fixture.reviewer_b, accountability_event) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let result = fixture @@ -4325,7 +4347,7 @@ async fn accountability_receipts_pin_selected_outcomes_through_independent_reten service .review_accountability(&fixture.reviewer_b, *event) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let outsider = actor("outside-team", CaseworkActsAs::Supervisor, "supervisor"); assert!(matches!( @@ -4692,7 +4714,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand source .own_review_decisions(&fixture.producer, None, "", None, None, 1) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert!(matches!( source @@ -4705,7 +4727,7 @@ async fn own_decisions_filter_authors_scope_and_continue_past_hidden_source_cand 1 ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let wrong_profile = actor("reviewer-a", CaseworkActsAs::Staff, "not-pinned"); assert!(source @@ -7187,7 +7209,9 @@ async fn prior_stage_identity_and_invalid_structured_result_emit_nothing() { "claim-excluded-secondary", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); assert_eq!( count_for_request( @@ -7419,7 +7443,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "nonmember-claim", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let assigned = fixture @@ -7484,7 +7508,7 @@ async fn claim_and_decide_require_current_exact_queue_membership() { "removed-holder-decision", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!( count_for_request( @@ -7547,7 +7571,7 @@ async fn delegation_requires_the_selected_profile_in_pinned_deciding_profiles() "delegate-ineligible-profile", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let unchanged = fixture .service_v1 @@ -7674,7 +7698,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-cross-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); let persisted = fixture .database @@ -7755,7 +7779,7 @@ async fn delegation_requires_membership_matching_the_selected_role_in_a_mixed_st "delegate-exact-role-membership", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; assert_eq!( @@ -7816,7 +7840,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-staff-scoped-supervisor", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); let unchanged = fixture .service_v1 @@ -7875,7 +7899,7 @@ async fn assignment_requires_a_selected_supervisor_profile_despite_directory_mem "assign-supervisor-scoped", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.supervisor, "supervisor", true).await; assert_eq!( @@ -7954,7 +7978,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "claim-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8042,7 +8066,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "release-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, project("1")); @@ -8166,7 +8190,7 @@ async fn reviewer_mutation_replays_require_current_exact_role_authority() { "decide-reviewer-replay", ) .await, - Err(ReviewRuntimeError::Forbidden | ReviewRuntimeError::NotFound) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation) | ReviewRuntimeError::NotFound) )); set_review_membership(&fixture, &fixture.reviewer_a, "staff", true).await; let (replay_service, replay_audit) = service_with_audit(&fixture, answer_project(false)); @@ -11516,7 +11540,9 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "assign-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let assigned = fixture .service_v1 @@ -11557,7 +11583,9 @@ async fn review_task_coordination_preserves_exclusions_drafts_history_and_absenc "delegate-initiator", ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) )); let delegated = fixture .service_v1 @@ -12019,7 +12047,7 @@ async fn staffing_diagnostic_is_disclosed_and_clears_when_responsibility_resumes 100 ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); // A diagnostic adds no authority. Concealed work matches unknown work for diff --git a/crates/registry-casework/tests/secret_diagnostics.rs b/crates/registry-casework/tests/secret_diagnostics.rs index bab55d5290..ac7dd30407 100644 --- a/crates/registry-casework/tests/secret_diagnostics.rs +++ b/crates/registry-casework/tests/secret_diagnostics.rs @@ -18,6 +18,7 @@ fn database(reference: &str) -> DatabaseConfig { migration_url_ref: reference.to_owned(), ca_bundle_ref: None, test_only_plaintext: false, + transport: None, } } diff --git a/crates/registry-casework/tests/startup_refusal.rs b/crates/registry-casework/tests/startup_refusal.rs index 49fec711ce..f74e6c2761 100644 --- a/crates/registry-casework/tests/startup_refusal.rs +++ b/crates/registry-casework/tests/startup_refusal.rs @@ -184,6 +184,43 @@ fn a_runtime_file_breaking_casework_rules_prints_each_at_its_position() { assert!(!stderr.contains("10.0.0.5"), "{stderr}"); } +fn assert_completion_credential_names_replacement(member: &str, value: &str) { + let directory = tempfile::tempdir().expect("temporary directory"); + let root = directory.path().canonicalize().expect("canonical root"); + let runtime = write_runtime_with( + &root, + &root.join("package"), + "casework-test", + "127.0.0.1:8100", + &format!("reviewCompletionDestinations:\n receiver:\n url: https://receiver.example.test/completions\n {member}: {value}\n"), + ); + + let (code, stderr) = serve(&runtime); + assert_eq!(code, Some(1)); + assert!( + stderr.contains(&format!("/reviewCompletionDestinations/receiver/{member}")), + "{stderr}" + ); + assert!( + stderr.contains("Configure hmacSha256KeyRef with a Standard Webhooks signing key"), + "{stderr}" + ); + assert!(!stderr.contains("secret:file/retired"), "{stderr}"); +} + +#[test] +fn a_completion_destination_with_a_bearer_token_names_its_replacement() { + assert_completion_credential_names_replacement("bearerTokenRef", "secret:file/retired"); +} + +#[test] +fn a_completion_destination_with_auth_names_its_replacement() { + assert_completion_credential_names_replacement( + "auth", + "{header: x-api-key, secretRef: secret:file/retired}", + ); +} + const CANONICAL: &str = include_str!("../../../products/casework/examples/canonical-review/casework.yaml"); const CANONICAL_SCHEMA: &str = include_str!( diff --git a/crates/registry-casework/tests/support/authority_closure_regressions.rs b/crates/registry-casework/tests/support/authority_closure_regressions.rs index d54e7a4c35..4e389402a7 100644 --- a/crates/registry-casework/tests/support/authority_closure_regressions.rs +++ b/crates/registry-casework/tests/support/authority_closure_regressions.rs @@ -283,7 +283,7 @@ async fn assignment_roles_stay_pinned_and_activation_refuses_changed_deciding_au let before = f.holders().await; assert!(matches!( assign(&service, task, "supervisor", "wrong-role").await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(f.holders().await, before); let candidate = ActivationCandidate { diff --git a/crates/registry-casework/tests/support/inbox_pagination.rs b/crates/registry-casework/tests/support/inbox_pagination.rs index b3083be51a..a11b5d9138 100644 --- a/crates/registry-casework/tests/support/inbox_pagination.rs +++ b/crates/registry-casework/tests/support/inbox_pagination.rs @@ -574,7 +574,7 @@ async fn directory_revocation_during_source_io_is_rechecked_in_both_paths() { Ok(page) => assert!(page.items.is_empty()), Err(error) => assert!(matches!( error, - ReviewRuntimeError::Forbidden + ReviewRuntimeError::Forbidden(_) | ReviewRuntimeError::NotFound | ReviewRuntimeError::ResultExpired )), diff --git a/crates/registry-casework/tests/support/independent_staffing_activation.rs b/crates/registry-casework/tests/support/independent_staffing_activation.rs index d94b2076aa..e7d26eaf58 100644 --- a/crates/registry-casework/tests/support/independent_staffing_activation.rs +++ b/crates/registry-casework/tests/support/independent_staffing_activation.rs @@ -25,7 +25,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); @@ -43,7 +43,7 @@ async fn caseload_target_membership_must_match_the_pinned_deciding_profiles() { movement("supervisor", CaseworkActsAs::Supervisor), ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); // Explicit supervisor eligibility is supported for newly admitted work. @@ -92,7 +92,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply f.service .preview_review_caseload(&supervisor, None, "", movement("b", CaseworkActsAs::Staff)) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); @@ -123,7 +123,7 @@ async fn caseload_refuses_active_absence_and_rechecks_scheduled_absence_at_apply } ) .await, - Err(ReviewRuntimeError::Forbidden) + Err(ReviewRuntimeError::Forbidden(FailedCheck::Operation)) )); assert_eq!(before, f.holders().await); } diff --git a/crates/registry-casework/tests/token_characterisation.rs b/crates/registry-casework/tests/token_characterisation.rs new file mode 100644 index 0000000000..bafbc2e4a8 --- /dev/null +++ b/crates/registry-casework/tests/token_characterisation.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the token fixture corpus through Casework's real authentication path +//! and asserts each result against the `casework` column of `expected.yaml`. +//! +//! The access-token verifier profile and the key source come from a runtime +//! file parsed by `RuntimeConfig::loader` and built by +//! `RuntimeConfig::oidc_verifier`, as at startup, with the signer's public +//! keys served as a static key set. Casework verifies RS256 and ES256 only, so +//! the key set the file points at holds those two keys. + +use std::path::Path; +use std::sync::Arc; + +use registry_casework::{secret_resolver, CaseworkAuthenticator, RuntimeConfig}; +use registry_casework_core::{ + AccessProfile, CaseworkActsAs, CaseworkProject, InboxPolicy, ProjectIdentity, QueuePolicy, + CASEWORK_API_VERSION, CASEWORK_KIND, +}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_oidc::JwksFetcher; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenFixture, + TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:casework:test"; +/// The client a default configuration lists when the fixture names none, so a +/// token without a client claim meets a list that does not include it. +const LISTED_CLIENT: &str = "journey-app"; +/// The scope a profile requires when the fixture carries none. +const FALLBACK_SCOPE: &str = "records:get"; +const JWKS_FILE: &str = "oidc-jwks"; + +#[tokio::test] +async fn casework_token_characterisation() { + let corpus = TokenCorpus::load().expect("the corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("temporary directory"); + let secrets = Secrets::write(root.path(), &signer.public_key_set()); + let report = corpus + .run_product_async("casework", &signer, ISSUER, AUDIENCE, |case| { + observe(case, &secrets) + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran, so the test proves nothing" + ); + report.assert_matches(); +} + +/// The directory the runtime file's `file` secret provider reads, holding the +/// static key set. +struct Secrets { + root: std::path::PathBuf, +} + +impl Secrets { + fn write(root: &Path, public_keys: &Value) -> Self { + use std::os::unix::fs::PermissionsExt as _; + let root = std::fs::canonicalize(root).expect("canonical root"); + let directory = root.join("secrets"); + std::fs::create_dir(&directory).expect("secrets directory"); + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)) + .expect("private secrets directory"); + // The runtime refuses a static key set that holds an OKP key, and it + // verifies RS256 and ES256 only. + let keys: Vec<&Value> = public_keys["keys"] + .as_array() + .expect("the key set lists keys") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .collect(); + let file = directory.join(JWKS_FILE); + std::fs::write(&file, json!({ "keys": keys }).to_string()).expect("key set file"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)) + .expect("private key set file"); + Self { root } + } +} + +/// What a configuration changes in the runtime file's `authentication.oidc` +/// block, derived from the fixture the way `expected.yaml` describes. +struct Shape { + /// `None` leaves `scopeClaim` out, as the runner's own file does. + scope_claim: Option<&'static str>, + /// Empty writes `allowedClients: unrestricted`. + clients: Vec, + /// The scope the access profile requires. + scope: String, +} + +impl Shape { + fn of(case: &FixtureCase) -> Self { + let fixture = &case.fixture; + let recipe = case.configuration == Configuration::Recipe; + let scope_claim = match (recipe, fixture.claims.contains_key("scp")) { + (true, true) => Some("scp"), + (true, false) => Some("scope"), + (false, _) => None, + }; + let client = literal_text(fixture, "client_id").or_else(|| literal_text(fixture, "azp")); + let clients = match (client, recipe) { + (Some(client), _) => vec![client], + (None, true) => Vec::new(), + (None, false) => vec![LISTED_CLIENT.to_owned()], + }; + let scope = fixture + .read_scope(scope_claim.unwrap_or("registry_scopes")) + .unwrap_or_else(|| FALLBACK_SCOPE.to_owned()); + Self { + scope_claim, + clients, + scope, + } + } + + fn runtime_yaml(&self, case: &FixtureCase, root: &Path) -> String { + let clients = if self.clients.is_empty() { + "unrestricted".to_owned() + } else { + json!(self.clients).to_string() + }; + let scope_claim = self + .scope_claim + .map(|claim| format!(" scopeClaim: {claim}\n")) + .unwrap_or_default(); + format!( + "apiVersion: id.registrystack.org/formats/casework/runtime/v1alpha1 +kind: CaseworkRuntimeConfig +identity: {{databaseId: casework-token-test}} +package: {{root: {root}/package}} +listener: {{bind: \"127.0.0.1:8100\", tlsTermination: development-loopback}} +secretProviders: {{file: {{root: {root}/secrets}}, environment: {{}}}} +database: {{runtimeUrlRef: secret:env/RUNTIME, migrationUrlRef: secret:env/MIGRATION}} +authentication: + oidc: + issuer: {issuer} + audience: {audience} + allowedClients: {clients} +{scope_claim} jwksSource: {{type: static, documentRef: secret:file/{JWKS_FILE}}} +audit: {{path: {root}/audit.ndjson, hashKeyRef: secret:file/audit}} +contextProviders: {{}} +", + root = root.display(), + issuer = case.issuer, + audience = case.audience, + ) + } + + /// A project with a Requester profile, which a service identity may use, + /// and a Staff profile, which only a person may use. Each requires the + /// fixture's first scope. + fn project(&self) -> CaseworkProject { + let starter = CaseworkProject::from_slice(include_bytes!( + "../../../products/casework/examples/standalone-decision/casework.yaml" + )) + .expect("canonical review fixture"); + let profile = |id: &str, acts_as| AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec![self.scope.clone()], + acts_as, + }; + CaseworkProject { + task_templates: Vec::new(), + api_version: CASEWORK_API_VERSION.to_owned(), + kind: CASEWORK_KIND.to_owned(), + project: ProjectIdentity::new( + "token-characterisation".parse().expect("project id"), + "1".to_owned(), + ), + access_profiles: vec![ + profile("requester", CaseworkActsAs::Requester), + profile("staff", CaseworkActsAs::Staff), + ], + queues: vec![QueuePolicy { + id: "decisions".to_owned(), + label: "Decisions".to_owned(), + }], + teams: starter.teams, + context_providers: Vec::new(), + review_policies: starter.review_policies, + trusted_producers: starter.trusted_producers, + calendars: Vec::new(), + clocks: Vec::new(), + inbox: InboxPolicy::default(), + } + } +} + +fn literal_text(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +async fn observe(case: FixtureCase, secrets: &Secrets) -> Outcome { + let shape = Shape::of(&case); + let config = RuntimeConfig::loader() + .parse_str::(&shape.runtime_yaml(&case, &secrets.root), |_| None) + .expect("the runtime file for this row parses") + .config; + let resolver = secret_resolver(&config).expect("the secret providers resolve"); + let (verifier, keys): (_, Arc) = config + .oidc_verifier(&resolver) + .await + .expect("the verifier profile builds"); + let authenticator = CaseworkAuthenticator::new( + &shape.project(), + verifier, + keys, + config.authentication.oidc.human_identity.clone(), + ); + + let profile = match case.against { + Against::PlainRead => "requester", + Against::HumanOnlyProfile => "staff", + }; + match authenticator + .authenticate(case.token.expose(), profile) + .await + { + Ok(_) => Outcome::Admitted(None), + Err(error) => Outcome::Refused(stage_of(error.failed_check())), + } +} + +/// The refusal stage the corpus names for the check a refusal failed. +fn stage_of(check: FailedCheck) -> Stage { + match check { + FailedCheck::CredentialMissing | FailedCheck::CredentialMalformed => Stage::Header, + FailedCheck::TokenAlgorithm => Stage::Algorithm, + FailedCheck::TokenType => Stage::TokenType, + FailedCheck::TokenKey => Stage::Key, + FailedCheck::TokenSignature => Stage::Signature, + FailedCheck::TokenIssuer => Stage::Issuer, + FailedCheck::TokenAudience => Stage::Audience, + FailedCheck::TokenTime => Stage::Time, + FailedCheck::TokenClient | FailedCheck::TokenAssertionIssuer => Stage::Client, + FailedCheck::Scope => Stage::Scope, + FailedCheck::AccessProfile | FailedCheck::ActorKind => Stage::Profile, + FailedCheck::KeySourceUnavailable => Stage::Unavailable, + FailedCheck::TokenClaims => Stage::Claims, + other => panic!("the corpus has no stage for the check {}", other.as_str()), + } +} diff --git a/crates/registry-caseworkctl/Cargo.toml b/crates/registry-caseworkctl/Cargo.toml index 70aa878dcf..9208d10618 100644 --- a/crates/registry-caseworkctl/Cargo.toml +++ b/crates/registry-caseworkctl/Cargo.toml @@ -33,6 +33,7 @@ clap.workspace = true jsonschema.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-cli-api.workspace = true @@ -47,7 +48,9 @@ serde_norway.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid = { workspace = true, features = ["serde"] } +zeroize.workspace = true [dev-dependencies] registry-breg.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio-postgres.workspace = true diff --git a/crates/registry-caseworkctl/src/lib.rs b/crates/registry-caseworkctl/src/lib.rs index 5d60f3eee6..9c8b7b8605 100644 --- a/crates/registry-caseworkctl/src/lib.rs +++ b/crates/registry-caseworkctl/src/lib.rs @@ -6,6 +6,7 @@ mod project; mod project_types; mod provider_add; mod provider_pair; +mod provision; mod report; #[cfg(feature = "schema")] pub mod schema; @@ -110,6 +111,8 @@ enum Command { #[arg(long)] backup_reference: Vec, }, + /// Create the migration and runtime roles and the database named by the runtime file. + Provision(registry_platform_provision::ProvisionArgs), /// Call the Casework HTTP API with a saved connection or an explicit URL. Api(Box), /// Manage saved Casework API connections. @@ -314,6 +317,9 @@ pub fn main_entry_from( let Cli { format, command } = cli; let command = match command { Command::Serve(args) => return serve(args, format, format_supplied, stdout, stderr), + Command::Provision(args) => { + return provision::run(args, matches!(format, OutputFormat::Json)); + } Command::Api(args) => return api(*args, format_supplied, stderr), Command::Connection { command } => { return connection(command, format, format_supplied, stderr); @@ -573,6 +579,7 @@ impl Command { Self::Plan(_) => "plan", Self::Status(_) => "status", Self::Apply { .. } => "apply", + Self::Provision(_) => "provision", Self::Api(_) => "api", Self::Connection { .. } => "connection", Self::RstackDev(_) => "rstack-dev", @@ -693,6 +700,7 @@ fn run(command: Command) -> Result { operator_reference, backup_reference, } => project::apply(&runtime_config, operator_reference, backup_reference), + Command::Provision(_) => unreachable!("provision writes its own report"), Command::Api(_) | Command::Connection { .. } => { unreachable!("raw API commands bypass report dispatch") } diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index 913c774bd7..5c214cf315 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -1531,7 +1531,7 @@ mod doctor_tests { const CANARY: &str = "DOCTOR_SECRET_VALUE_CANARY"; - fn setup() -> (tempfile::TempDir, PathBuf) { + fn setup(previous_key_ref: Option<&str>) -> (tempfile::TempDir, PathBuf) { let root = crate::canonical_tempdir(); let project = root.path().join("project"); init(&project, "standalone-decision").unwrap(); @@ -1546,11 +1546,11 @@ mod doctor_tests { "postgresql://casework@127.0.0.1:1/casework?sslmode=require&connect_timeout=1", ), ("audit-key", CANARY), - ("completion-token", CANARY), + ("completion-key", "synthetic-doctor-completion-key!"), ] { write_secret(&secrets.join(name), bytes.as_bytes(), 0o600); } - let config = json!({ + let mut config = json!({ "apiVersion":registry_casework::RUNTIME_CONFIG_API_VERSION,"kind":registry_casework::RUNTIME_CONFIG_KIND, "identity":{"databaseId":"doctor-preflight"},"package":{"root":package_root}, "listener":{"bind":"127.0.0.1:8100","tlsTermination":"development-loopback","networkExposure":"private-address"}, @@ -1558,8 +1558,12 @@ mod doctor_tests { "database":{"runtimeUrlRef":"secret:file/runtime-url","migrationUrlRef":"secret:file/absent-migration-url"}, "authentication":{"oidc":{"issuer":"https://identity.example.test","audience":"urn:example:casework","allowedClients":"unrestricted","scopeClaim":"scope","humanIdentity":{"claim":"registry_actor_kind","value":"human"}}}, "audit":{"path":root.path().join("audit.ndjson"),"hashKeyRef":"secret:file/audit-key"}, - "reviewCompletionDestinations":{"receiver":{"url":"https://completion.example.test/reviews","bearerTokenRef":"secret:file/completion-token"}} + "reviewCompletionDestinations":{"receiver":{"url":"https://completion.example.test/reviews","hmacSha256KeyRef":"secret:file/completion-key"}} }); + if let Some(reference) = previous_key_ref { + config["reviewCompletionDestinations"]["receiver"]["previousHmacSha256KeyRef"] = + json!(reference); + } let runtime = root.path().join("runtime.yaml"); fs::write(&runtime, serde_norway::to_string(&config).unwrap()).unwrap(); (root, runtime) @@ -1575,11 +1579,11 @@ mod doctor_tests { for (name, field) in [ ("audit-key", "audit.hashKeyRef"), ( - "completion-token", - "reviewCompletionDestinations.receiver.bearerTokenRef", + "completion-key", + "reviewCompletionDestinations.receiver.hmacSha256KeyRef", ), ] { - let (root, runtime) = setup(); + let (root, runtime) = setup(None); fs::remove_file(root.path().join("secrets").join(name)).unwrap(); let error = doctor(&runtime).unwrap_err(); let shown = format!("{error:#}"); @@ -1626,9 +1630,48 @@ mod doctor_tests { } } + #[test] + fn doctor_refuses_an_oversized_completion_signing_key() { + assert_doctor_refuses_completion_key(&[b'x'; 65], false, "65 bytes"); + } + + #[test] + fn doctor_refuses_repeated_completion_signing_key_bytes() { + assert_doctor_refuses_completion_key( + &[b'x'; 32], + true, + "To rotate, write 32 new random bytes", + ); + } + + #[test] + fn doctor_refuses_an_empty_completion_signing_key() { + assert_doctor_refuses_completion_key(b"", false, "Store a non-empty value"); + } + + fn assert_doctor_refuses_completion_key(bytes: &[u8], repeat: bool, expected: &str) { + let (root, runtime) = setup(repeat.then_some("secret:file/previous-key")); + write_secret(&root.path().join("secrets/completion-key"), bytes, 0o600); + let path = if repeat { + write_secret(&root.path().join("secrets/previous-key"), bytes, 0o600); + "/reviewCompletionDestinations/receiver/previousHmacSha256KeyRef" + } else { + "/reviewCompletionDestinations/receiver/hmacSha256KeyRef" + }; + let error = doctor(&runtime).unwrap_err(); + let report = error.downcast_ref::().expect("doctor diagnostic"); + let [diagnostic] = report.diagnostics() else { + panic!("expected one completion key diagnostic"); + }; + assert_eq!(diagnostic.path, path); + let message = report.to_json_value().to_string(); + assert!(message.contains(expected), "{message}"); + assert!(!message.contains(CANARY)); + } + #[test] fn serving_preflight_accepts_present_secrets_without_a_migration_credential() { - let (root, runtime) = setup(); + let (root, runtime) = setup(None); let config = load_runtime_config(&runtime).unwrap(); let resolver = secret_resolver(&config).unwrap(); config.check_runtime_secrets(&resolver).unwrap(); @@ -1639,7 +1682,7 @@ mod doctor_tests { #[test] fn serving_preflight_names_all_unusable_secrets_without_printing_values() { for condition in ["mode", "empty", "nul", "oversized", "symlink"] { - let (root, runtime) = setup(); + let (root, runtime) = setup(None); let audit = root.path().join("secrets/audit-key"); match condition { "mode" => write_secret(&audit, CANARY.as_bytes(), 0o644), @@ -1658,7 +1701,7 @@ mod doctor_tests { } _ => unreachable!(), } - fs::remove_file(root.path().join("secrets/completion-token")).unwrap(); + fs::remove_file(root.path().join("secrets/completion-key")).unwrap(); let config = load_runtime_config(&runtime).unwrap(); let resolver = secret_resolver(&config).unwrap(); let report = config.check_runtime_secrets(&resolver).unwrap_err(); @@ -1671,7 +1714,7 @@ mod doctor_tests { paths, [ "/audit/hashKeyRef", - "/reviewCompletionDestinations/receiver/bearerTokenRef" + "/reviewCompletionDestinations/receiver/hmacSha256KeyRef" ], "{condition}" ); diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs new file mode 100644 index 0000000000..c865bc129e --- /dev/null +++ b/crates/registry-caseworkctl/src/provision.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `caseworkctl provision`: creates the migration and runtime roles and the +//! database from the two URLs in the runtime file, so each credential is +//! written once. The shared command owns the flags, the plan and the report. + +use std::path::Path; +use std::process::ExitCode; + +use registry_casework::{secret_resolver, RuntimeConfig}; +use registry_platform_config::{describe_secret_failure, SecretResolver}; +use registry_platform_provision::cli::OutputFormat; +use registry_platform_provision::{ + run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, SchemaLayout, +}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +const SECRET_ACTION: &str = + "Provision a runtime-readable secret through the configured provider and retry provision."; + +/// Runs the command with this tool's global `--format`. +pub(crate) fn run(args: ProvisionArgs, json: bool) -> ExitCode { + let format = if json { + OutputFormat::Json + } else { + OutputFormat::Human + }; + run_provision( + "caseworkctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args, + format, + load, + ) +} + +fn load(path: &Path) -> Result> { + let config = RuntimeConfig::load(path).map_err(|error| { + Box::new(Diagnostic::error( + error.code(), + format!("runtime.yaml:{}", error.pointer()), + "The runtime configuration was refused.", + error.suggested_action(), + )) + })?; + let secrets = secret_resolver(&config).map_err(|_| { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + "runtime.yaml:/secretProviders", + "The secret provider configuration is invalid.", + SECRET_ACTION, + )) + })?; + let database = &config.database; + let migration_url = text_secret( + &secrets, + "database.migrationUrlRef", + "/database/migrationUrlRef", + &database.migration_url_ref, + )?; + let runtime_url = text_secret( + &secrets, + "database.runtimeUrlRef", + "/database/runtimeUrlRef", + &database.runtime_url_ref, + )?; + let ca_pem = database + .ca_bundle_ref + .as_deref() + .map(|reference| { + secrets + .resolve(reference) + .map(|secret| secret.expose_secret().to_vec()) + .map_err(|error| { + secret_diagnostic( + "database.caBundleRef", + "/database/caBundleRef", + reference, + &error, + ) + }) + }) + .transpose()?; + Ok(ProvisionInput { + product: ProductDatabase { + product: "casework", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + }, + migration_url, + runtime_url, + ca_pem, + }) +} + +fn text_secret( + secrets: &SecretResolver, + field: &str, + pointer: &str, + reference: &str, +) -> Result, Box> { + let secret = secrets + .resolve(reference) + .map_err(|error| secret_diagnostic(field, pointer, reference, &error))?; + let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + format!("runtime.yaml:{pointer}"), + format!("{field}: the secret value must be non-empty text"), + SECRET_ACTION, + )) + })?; + Ok(Zeroizing::new(text.to_owned())) +} + +fn secret_diagnostic( + field: &str, + pointer: &str, + reference: &str, + error: ®istry_platform_config::SecretError, +) -> Box { + Box::new(Diagnostic::error( + "casework.runtime.secret-unavailable", + format!("runtime.yaml:{pointer}"), + describe_secret_failure(field, reference, error), + SECRET_ACTION, + )) +} diff --git a/crates/registry-caseworkctl/tests/provision.rs b/crates/registry-caseworkctl/tests/provision.rs new file mode 100644 index 0000000000..de6c3ce497 --- /dev/null +++ b/crates/registry-caseworkctl/tests/provision.rs @@ -0,0 +1,576 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `caseworkctl provision`: print mode, usage refusals, and, with a disposable +//! server, provisioning as a non-superuser owner then apply then serve. + +#![cfg(unix)] +#![allow( + clippy::disallowed_methods, + reason = "tests write only their own synthetic project and secrets" +)] + +use serde_json::{json, Value}; +use std::{ + fs, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +const MIGRATION_PASSWORD: &str = "migration-password-canary-0123456789"; +const RUNTIME_PASSWORD: &str = "runtime-password-canary-0123456789"; + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_caseworkctl")) + .args(arguments) + .env_remove("RSTACK_GENERATION_DIR") + .output() + .expect("caseworkctl starts") +} + +fn ctl_ok(arguments: &[&str]) -> Value { + let output = ctl(&[&["--format", "json"], arguments].concat()); + assert!( + output.status.success(), + "caseworkctl {arguments:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("a typed JSON report") +} + +fn secret(path: &Path, value: &str) { + fs::write(path, value).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +/// One synthetic deployment: an authored project, its package, a secret root +/// and a runtime file whose two database URLs name the given roles. +struct Deployment { + _root: tempfile::TempDir, + #[cfg_attr(not(feature = "postgres-test"), allow(dead_code))] + root: PathBuf, + runtime: PathBuf, +} + +struct DatabaseUrls<'a> { + migration: &'a str, + runtime: &'a str, + ca_pem: Option<&'a Path>, + plaintext: bool, + bind: &'a str, +} + +fn deployment(urls: &DatabaseUrls<'_>) -> Deployment { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().canonicalize().unwrap(); + let project = root.join("project"); + ctl_ok(&[ + "init", + project.to_str().unwrap(), + "--template", + "standalone-decision", + ]); + let package = root.join("package"); + ctl_ok(&[ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ]); + let secrets = root.join("secrets"); + fs::create_dir(&secrets).unwrap(); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).unwrap(); + secret(&secrets.join("migration-url"), urls.migration); + secret(&secrets.join("runtime-url"), urls.runtime); + secret( + &secrets.join("audit-key"), + "provision-test-audit-key-canary-0123456789", + ); + // The issuer's public key is read from a secret, so serving needs no network. + secret( + &secrets.join("jwks"), + r#"{"keys":[{"kty":"EC","crv":"P-256","use":"sig","alg":"ES256","kid":"provision-test","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#, + ); + let mut database = json!({ + "runtimeUrlRef":"secret:file/runtime-url", + "migrationUrlRef":"secret:file/migration-url", + }); + if let Some(ca) = urls.ca_pem { + secret(&secrets.join("ca"), &fs::read_to_string(ca).unwrap()); + database["caBundleRef"] = json!("secret:file/ca"); + } + if urls.plaintext { + database["testOnlyPlaintext"] = json!(true); + } + let config = json!({ + "apiVersion":registry_casework::RUNTIME_CONFIG_API_VERSION,"kind":registry_casework::RUNTIME_CONFIG_KIND, + "identity":{"databaseId":"provision-test"},"package":{"root":package}, + "listener":{"bind":urls.bind,"tlsTermination":"development-loopback","networkExposure":"private-address"}, + "secretProviders":{"file":{"root":secrets}}, + "database":database, + "authentication":{"oidc":{"issuer":"https://identity.example.test","audience":"urn:example:casework", + "jwksSource":{"type":"static","documentRef":"secret:file/jwks"}, + "allowedClients":"unrestricted","scopeClaim":"scope","humanIdentity":{"claim":"registry_actor_kind","value":"human"}}}, + "audit":{"path":root.join("audit.ndjson"),"hashKeyRef":"secret:file/audit-key"} + }); + let runtime = root.join("runtime.yaml"); + fs::write(&runtime, serde_norway::to_string(&config).unwrap()).unwrap(); + Deployment { + _root: temporary, + root, + runtime, + } +} + +fn offline_urls() -> (String, String) { + ( + format!("postgresql://cw_migration:{MIGRATION_PASSWORD}@db.example.test:5432/casework_db"), + format!("postgresql://cw_runtime:{RUNTIME_PASSWORD}@db.example.test:5432/casework_db"), + ) +} + +#[test] +fn print_sql_connects_to_nothing_and_prints_no_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let output = ctl(&[ + "provision", + "--runtime-config", + deployment.runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let script = String::from_utf8(output.stdout).unwrap(); + for expected in ["cw_migration", "cw_runtime", "casework_db", "CREATE ROLE"] { + assert!(script.contains(expected), "script lacks {expected}"); + } + for private in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "db.example.test", + "postgresql://", + ] { + assert!(!script.contains(private), "script leaks {private}"); + } + assert!(!String::from_utf8_lossy(&output.stderr).contains(MIGRATION_PASSWORD)); +} + +#[test] +fn print_sql_with_a_global_json_format_reports_without_executing() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + deployment.runtime.to_str().unwrap(), + "--print-sql", + ]); + assert_eq!(output.status.code(), Some(0)); + let text = String::from_utf8(output.stdout).unwrap(); + let report: Value = serde_json::from_str(&text).expect("a JSON report on stdout"); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "casework"); + assert_eq!(report["executed"], false); + assert_eq!(report["migrationRole"], "cw_migration"); + assert_eq!(report["runtimeRole"], "cw_runtime"); + assert!(!text.contains(MIGRATION_PASSWORD) && !text.contains(RUNTIME_PASSWORD)); +} + +/// Runs `provision --print-sql` with a JSON report and returns the exit code, +/// the report, and everything the command wrote, for a leak check. +fn refused_print(runtime: &Path) -> (Option, Value, String) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime.to_str().unwrap(), + "--print-sql", + ]); + let written = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|_| panic!("a JSON report on stdout: {written}")); + (output.status.code(), report, written) +} + +fn assert_loader_refusal( + (code, report, written): &(Option, Value, String), + diagnostic_code: &str, + pointer: &str, +) { + assert_eq!(*code, Some(1), "{written}"); + assert_eq!(report["ok"], false, "{written}"); + assert_eq!( + report["diagnostics"][0]["code"], diagnostic_code, + "{written}" + ); + let location = report["diagnostics"][0]["path"] + .as_str() + .unwrap_or_default(); + assert!(location.ends_with(pointer), "{location} in {written}"); + for private in [MIGRATION_PASSWORD, RUNTIME_PASSWORD, "postgresql://"] { + assert!(!written.contains(private), "the refusal leaks {private}"); + } +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_without_printing_a_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/runtime-url")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_missing_migration_url_secret_is_refused_without_printing_a_password() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/migration-url")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/migrationUrlRef", + ); +} + +#[test] +fn a_runtime_url_secret_that_is_not_text_is_refused() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + let file = deployment.root.join("secrets/runtime-url"); + fs::write(&file, [0xff, 0xfe, 0xfd]).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused() { + let (migration, runtime) = offline_urls(); + let ca = tempfile::NamedTempFile::new().unwrap(); + fs::write(ca.path(), "not a bundle, never parsed here").unwrap(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: Some(ca.path()), + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::remove_file(deployment.root.join("secrets/ca")).unwrap(); + assert_loader_refusal( + &refused_print(&deployment.runtime), + "casework.runtime.secret-unavailable", + "/database/caBundleRef", + ); +} + +#[test] +fn a_runtime_file_that_does_not_load_is_refused_with_its_own_code() { + let (migration, runtime) = offline_urls(); + let deployment = deployment(&DatabaseUrls { + migration: &migration, + runtime: &runtime, + ca_pem: None, + plaintext: false, + bind: "127.0.0.1:8100", + }); + fs::write(&deployment.runtime, "kind: NotARuntimeConfig\n").unwrap(); + let (code, report, written) = refused_print(&deployment.runtime); + assert_eq!(code, Some(1), "{written}"); + assert_eq!(report["ok"], false, "{written}"); + assert_eq!( + report["diagnostics"][0]["code"], "config.missing-envelope", + "{written}" + ); +} + +#[test] +fn both_administrator_flags_are_a_usage_error() { + let output = ctl(&[ + "provision", + "--runtime-config", + "/nonexistent/runtime.yaml", + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "UNUSED_ADMIN_URL", + ]); + assert_eq!(output.status.code(), Some(2)); + let output = ctl(&[ + "provision", + "--runtime-config", + "/nonexistent/runtime.yaml", + "--print-sql", + "--admin-url-env", + "UNUSED_ADMIN_URL", + ]); + assert_eq!(output.status.code(), Some(2)); + let output = ctl(&["provision", "--runtime-config", "/nonexistent/runtime.yaml"]); + assert_eq!( + output.status.code(), + Some(2), + "an administrator flag is required unless --print-sql is given" + ); +} + +#[cfg(feature = "postgres-test")] +mod served { + use super::*; + use registry_platform_provision::test_support::{connect_verified, provision_test_env}; + use std::io::{Read as _, Write as _}; + use uuid::Uuid; + + fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) + } + + fn hex(length: usize) -> String { + Uuid::new_v4().simple().to_string()[..length].to_owned() + } + + /// Drops the database and roles a test created, even after a failure. + struct Cleanup { + superuser_url: String, + ca_pem: Vec, + database: String, + roles: Vec, + } + + impl Drop for Cleanup { + fn drop(&mut self) { + let (url, ca_pem, database, roles) = ( + self.superuser_url.clone(), + self.ca_pem.clone(), + self.database.clone(), + self.roles.clone(), + ); + std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let client = connect_verified(&url, &ca_pem, None).await; + client + .batch_execute(&format!( + "DROP DATABASE IF EXISTS \"{database}\" WITH (FORCE)" + )) + .await + .expect("drop database"); + for role in roles { + client + .batch_execute(&format!("DROP ROLE IF EXISTS \"{role}\"")) + .await + .expect("drop role"); + } + }); + }) + .join() + .expect("cleanup thread"); + } + } + + fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() + } + + fn get_status(address: &str, path: &str) -> std::io::Result { + let mut stream = std::net::TcpStream::connect(address)?; + stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?; + write!( + stream, + "GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n" + )?; + let mut response = String::new(); + stream.read_to_string(&mut response)?; + Ok(response.lines().next().unwrap_or_default().to_owned()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn provision_then_apply_then_serve_with_split_roles() { + let (superuser_url, ca_pem) = provision_test_env(); + let ca_path = PathBuf::from(required("PROVISION_TEST_DATABASE_CA")); + let server = registry_platform_provision::admin_config(&superuser_url, Some(&ca_pem)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (server.host().to_owned(), server.port()); + + let suffix = hex(12); + let (owner, migration, runtime, database) = ( + format!("cw_owner_{suffix}"), + format!("cw_mig_{suffix}"), + format!("cw_run_{suffix}"), + format!("cw_db_{suffix}"), + ); + let owner_password = hex(24); + let _cleanup = Cleanup { + superuser_url: superuser_url.clone(), + ca_pem: ca_pem.clone(), + database: database.clone(), + roles: vec![runtime.clone(), migration.clone(), owner.clone()], + }; + let admin = connect_verified(&superuser_url, &ca_pem, None).await; + admin + .batch_execute(&format!( + "CREATE ROLE \"{owner}\" LOGIN CREATEROLE CREATEDB NOSUPERUSER PASSWORD '{owner_password}'" + )) + .await + .unwrap(); + + let bind = format!("127.0.0.1:{}", free_port()); + let endpoint = format!("{host}:{port}/{database}"); + let migration_url = format!("postgresql://{migration}:{MIGRATION_PASSWORD}@{endpoint}"); + let runtime_url = format!("postgresql://{runtime}:{RUNTIME_PASSWORD}@{endpoint}"); + let deployment = deployment(&DatabaseUrls { + migration: &migration_url, + runtime: &runtime_url, + ca_pem: Some(&ca_path), + plaintext: false, + bind: &bind, + }); + let admin_file = deployment.root.join("admin-url"); + secret( + &admin_file, + &format!( + "postgresql://{owner}:{owner_password}@{host}:{port}/postgres?sslmode=verify-full" + ), + ); + let runtime_file = deployment.runtime.to_str().unwrap(); + + let provisioned = Command::new(env!("CARGO_BIN_EXE_caseworkctl")) + .args(["--format", "json", "provision", "--runtime-config"]) + .arg(runtime_file) + .arg("--admin-url-file") + .arg(&admin_file) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&provisioned.stdout).into_owned(); + assert_eq!( + provisioned.status.code(), + Some(0), + "provision refused: {text} {}", + String::from_utf8_lossy(&provisioned.stderr) + ); + let report: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(report["status"], "complete"); + assert_eq!(report["roleMode"], "split"); + for private in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + owner_password.as_str(), + ] { + assert!(!text.contains(private), "the report leaks a password"); + } + + // Apply records single-role mode and still succeeds, so only these + // fields show that provisioning left the two roles split. + let applied = ctl_ok(&["apply", "--runtime-config", runtime_file]); + assert_eq!(applied["ok"], true, "{applied}"); + assert!( + applied["singleRoleStatement"].is_null(), + "apply recorded single-role mode: {applied}" + ); + assert_eq!(applied["activation"]["roleMode"], "split", "{applied}"); + let status = ctl_ok(&["status", "--runtime-config", runtime_file]); + assert_eq!(status["ok"], true, "{status}"); + assert!( + status["singleRoleStatement"].is_null(), + "status reports single-role mode: {status}" + ); + assert_eq!(status["activation"]["roleMode"], "split", "{status}"); + + // A second provision finds everything present and creates nothing. + let again = ctl_ok(&[ + "provision", + "--runtime-config", + runtime_file, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(again["status"], "complete"); + assert!( + again["statements"] + .as_array() + .unwrap() + .iter() + .all(|statement| statement["outcome"] != "created"), + "{again}" + ); + + let server_task = tokio::spawn({ + let runtime = deployment.runtime.clone(); + async move { registry_casework::serve_from_path(runtime).await } + }); + let mut answer = String::new(); + for _ in 0..100 { + assert!( + !server_task.is_finished(), + "the runtime stopped: {:?}", + server_task.await + ); + let probe_address = bind.clone(); + answer = tokio::task::spawn_blocking(move || get_status(&probe_address, "/ready")) + .await + .unwrap() + .unwrap_or_default(); + if answer.contains("200") { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + server_task.abort(); + assert!( + answer.contains("200"), + "the runtime role serves /ready after provision and apply: {answer:?}" + ); + } +} diff --git a/crates/registry-cli-api/schema/connections.schema.json b/crates/registry-cli-api/schema/connections.schema.json index 85a76ded9f..8f995f848a 100644 --- a/crates/registry-cli-api/schema/connections.schema.json +++ b/crates/registry-cli-api/schema/connections.schema.json @@ -17,7 +17,7 @@ "description": "The file secret provider.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", "pattern": "^/", "type": "string" } diff --git a/crates/registry-cli-docs/Cargo.toml b/crates/registry-cli-docs/Cargo.toml index 0eaf0f333e..e9f397280b 100644 --- a/crates/registry-cli-docs/Cargo.toml +++ b/crates/registry-cli-docs/Cargo.toml @@ -34,6 +34,8 @@ registry-schedulingctl.workspace = true registry-messaging.workspace = true registry-messagingctl.workspace = true registry-mcp.workspace = true +registry-discovery = { workspace = true, features = ["server"] } +registry-discoveryctl.workspace = true registry-documents.workspace = true registry-documentsctl.workspace = true registry-manifest-cli.workspace = true diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 993ce463ea..61ac2b810b 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1744,6 +1744,111 @@ } ] }, + { + "name": "provision", + "invocation": "adapterctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "adapterctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "schemas", "invocation": "adapterctl schemas", @@ -5541,6 +5646,120 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "bregctl provision", + "about": "Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file", + "long_about": "Create the PostgreSQL roles, database and schemas a Registry needs, from its runtime file. The runtime file's two database URLs name both roles, the database and both passwords. The administrator URL comes from a file or an environment variable, never from the command line. The command grants the runtime role CONNECT on the database: apply grants the rest. With --package, a package that needs PostGIS also gets its schema, extension and bounding-box role, which CREATE EXTENSION postgis needs a superuser for, and both roles get USAGE on the PostGIS schema.", + "usage": "bregctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--package ", + "description": "Absolute target package directory; a package that needs PostGIS adds the PostGIS steps. A symbolic link at any component of this path is refused.", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "timer", "invocation": "bregctl timer", @@ -6230,6 +6449,96 @@ ], "constraints": [], "subcommands": [] + }, + { + "name": "draft", + "invocation": "bregctl migration draft", + "about": "Write the reviewed migration directory for a successor whose changes need no SQL", + "long_about": "Write the reviewed migration directory for a successor whose changes need no SQL. Covers every access or disclosure change against the baseline package. Compatible-additive changes, such as an optional field, may sit beside them and stay uncovered: the registry applies those through its own additive plan. Any other change is refused. Measures the candidate on the disposable database the runtime configuration names, and writes descriptor.json and rehearsal.json under /modules//migrations/. Pass as --reviewed-migrations to test and package. Never overwrites an existing migration.", + "usage": "bregctl migration draft [OPTIONS] --baseline-package --runtime-config --output --module --id ", + "arguments": [ + { + "display": "", + "description": "Base Registry Engine project directory. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--baseline-package ", + "description": "Absolute directory of the chain tip package the successor follows. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file of the disposable schema-test database. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "Absolute reviewed-migrations directory the draft is written under. A symbolic link at any component of this path is refused.", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--module ", + "description": "Module the migration directory belongs to", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--id ", + "description": "Identifier of the migration, also its directory name", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] } ] }, @@ -7253,7 +7562,7 @@ { "name": "sample", "invocation": "bregctl hook sample", - "about": "Render one deterministic exact CloudEvents request with synthetic values", + "about": "Render one deterministic Standard Webhooks request with synthetic values", "long_about": null, "usage": "bregctl hook sample [OPTIONS] --event ", "arguments": [ @@ -10199,7 +10508,112 @@ "subcommands": [] }, { - "name": "api", + "name": "provision", + "invocation": "caseworkctl provision", + "about": "Create the migration and runtime roles and the database named by the runtime file", + "long_about": null, + "usage": "caseworkctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human diagnostics and reports, or one typed JSON report", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, + { + "name": "api", "invocation": "caseworkctl api", "about": "Call the Casework HTTP API with a saved connection or an explicit URL", "long_about": null, @@ -12310,6 +12724,111 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "coordinatorctl provision", + "about": "Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator", + "long_about": null, + "usage": "coordinatorctl provision [OPTIONS]", + "arguments": [], + "options": [ + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Output format for local reports and authenticated API responses: readable text, or one JSON report", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "apply", "invocation": "coordinatorctl apply", @@ -13621,11 +14140,11 @@ ] }, { - "name": "documents", - "invocation": "documents", - "about": "Run the Registry Stack Document Store", + "name": "discovery", + "invocation": "discovery", + "about": "Serve one immutable Registry Discovery index", "long_about": null, - "usage": "documents --runtime-config ", + "usage": "discovery --runtime-config ", "arguments": [], "options": [ { @@ -13657,52 +14176,16 @@ } ], "constraints": [], - "subcommands": [ - { - "name": "serve", - "invocation": "documents serve", - "about": "Run the Document Store HTTP service", - "long_about": null, - "usage": "documents --runtime-config serve", - "arguments": [], - "options": [ - { - "display": "-h, --help", - "description": "Print help", - "always_required": false, - "repeatable": false, - "default_values": [], - "possible_values": [], - "environment": null - } - ], - "constraints": [], - "subcommands": [] - } - ] + "subcommands": [] }, { - "name": "documentsctl", - "invocation": "documentsctl", - "about": "Registry Stack Document Store adopter and local operator tooling", + "name": "discoveryctl", + "invocation": "discoveryctl", + "about": "Check and package one immutable Registry Discovery index", "long_about": null, - "usage": "documentsctl [OPTIONS] ", + "usage": "discoveryctl ", "arguments": [], "options": [ - { - "display": "--format ", - "description": "Emit the selected command's report in this format", - "always_required": false, - "repeatable": false, - "default_values": [ - "human" - ], - "possible_values": [ - "human", - "json" - ], - "environment": null - }, { "display": "-h, --help", "description": "Print help", @@ -13725,15 +14208,15 @@ "constraints": [], "subcommands": [ { - "name": "init", - "invocation": "documentsctl init", - "about": "Write the starter project into a new directory", + "name": "api", + "invocation": "discoveryctl api", + "about": "Send one raw HTTP request to a Discovery endpoint", "long_about": null, - "usage": "documentsctl init [OPTIONS] ", + "usage": "discoveryctl api [OPTIONS] ", "arguments": [ { - "display": "", - "description": "The directory to create. It must not exist", + "display": "", + "description": "Relative API path. A leading slash is accepted without discarding a deployment prefix", "always_required": true, "repeatable": false, "default_values": [], @@ -13743,38 +14226,977 @@ ], "options": [ { - "display": "--format ", - "description": "Emit the selected command's report in this format", + "display": "--project ", + "description": "Project directory, or a descendant from which the exact product root is found", "always_required": false, "repeatable": false, - "default_values": [ - "human" - ], - "possible_values": [ - "human", - "json" - ], + "default_values": [], + "possible_values": [], "environment": null }, { - "display": "-h, --help", - "description": "Print help", + "display": "--connection ", + "description": "Named saved remote connection", "always_required": false, "repeatable": false, "default_values": [], "possible_values": [], "environment": null - } - ], - "constraints": [], - "subcommands": [] - }, - { - "name": "check", - "invocation": "documentsctl check", - "about": "Check a project, a runtime configuration, or both, offline", - "long_about": null, - "usage": "documentsctl check [OPTIONS] <--project |--runtime-config >", + }, + { + "display": "--url ", + "description": "Explicit service base URL for an advanced one-off request", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-file ", + "description": "Bearer credential file used only with `--url`", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--ca-file ", + "description": "PEM certificate authority bundle for an explicit private-institution endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--method ", + "description": "HTTP method. Defaults to GET, or POST when `--input` is present", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--input ", + "description": "Request body file, or `-` for standard input", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--header
", + "description": "Request header as `NAME: VALUE`; use `NAME: @FILE` for a value or `@FILE` for complete lines", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--accept ", + "description": "Value of the HTTP Accept header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "Write response bytes to this file instead of standard output", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--include", + "description": "Include the HTTP status and response headers before the response body", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--idempotency-key ", + "description": "Value of the Idempotency-Key header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--if-match ", + "description": "Literal HTTP If-Match value, including quotes when the endpoint requires them", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "requires-all", + "when": "--token-file ", + "arguments": [ + "--url " + ] + }, + { + "kind": "requires-all", + "when": "--ca-file ", + "arguments": [ + "--url " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--connection ", + "--url " + ] + } + ], + "subcommands": [] + }, + { + "name": "connection", + "invocation": "discoveryctl connection", + "about": "Manage named Discovery API connections", + "long_about": null, + "usage": "discoveryctl connection [OPTIONS] ", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "add", + "invocation": "discoveryctl connection add", + "about": "Save one product-scoped remote connection", + "long_about": null, + "usage": "discoveryctl connection add [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local connection name used by `--connection` and project selections", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--url ", + "description": "API service base URL. Prompted when omitted in an interactive terminal", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--ca-file ", + "description": "PEM certificate authority bundle for a private-institution endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--access-profile ", + "description": "Casework only: stable caller access profile applied to its profile headers", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--anonymous", + "description": "Save a connection that sends no Authorization header", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-file ", + "description": "File holding a bearer token. The configuration stores only a secret reference", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-env ", + "description": "Environment variable holding a bearer token. The configuration stores only a secret reference", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--private-key-jwt", + "description": "Acquire renewable bearer tokens with OAuth private_key_jwt", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--token-endpoint ", + "description": "OAuth token endpoint used for private_key_jwt authentication", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--client-id ", + "description": "OAuth client identifier registered at the token endpoint", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--private-key-file ", + "description": "Owner-only file containing the private client JWK", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--scope ", + "description": "OAuth scope to request; repeat the option for multiple scopes", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--resource ", + "description": "Optional RFC 8707 resource indicator for the requested token", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--assertion-audience ", + "description": "Client assertion audience: the authorization server's issuer identifier", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "requires-all", + "when": "--token-endpoint ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--client-id ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--private-key-file ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--scope ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--resource ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "requires-all", + "when": "--assertion-audience ", + "arguments": [ + "--private-key-jwt" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--private-key-jwt" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--token-env " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--anonymous", + "--token-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--private-key-jwt", + "--token-env " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--private-key-jwt", + "--token-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--token-env ", + "--token-file " + ] + } + ], + "subcommands": [] + }, + { + "name": "list", + "invocation": "discoveryctl connection list", + "about": "List saved connections for this product", + "long_about": null, + "usage": "discoveryctl connection list [OPTIONS]", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "show", + "invocation": "discoveryctl connection show", + "about": "Show one saved connection without resolving its credential", + "long_about": null, + "usage": "discoveryctl connection show [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local name of the connection to show", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "use", + "invocation": "discoveryctl connection use", + "about": "Select a saved connection for one exact product project", + "long_about": null, + "usage": "discoveryctl connection use [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Local name of the connection to select for the project", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--project ", + "description": "Project directory, or a descendant from which the exact product root is found", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "check", + "invocation": "discoveryctl connection check", + "about": "Check one saved-connections file without resolving credentials or contacting endpoints", + "long_about": null, + "usage": "discoveryctl connection check [OPTIONS] --file ", + "arguments": [], + "options": [ + { + "display": "--file ", + "description": "Saved-connections YAML file to validate offline", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--deny-warnings", + "description": "Exit 1 when the check reports a warning", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report for connection check", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, + { + "name": "serve", + "invocation": "discoveryctl serve", + "about": "Run the production Discovery service with the selected runtime", + "long_about": null, + "usage": "discoveryctl serve --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file passed unchanged to the Discovery runtime", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "check", + "invocation": "discoveryctl check", + "about": "Check an authoring project, a runtime file, or an index without network I/O", + "long_about": null, + "usage": "discoveryctl check [OPTIONS] <--project |--runtime-config |--index >", + "arguments": [], + "options": [ + { + "display": "--project ", + "description": "The authoring project directory: origins.yaml, the mappings directory, and every runtime file beside them", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file, checked on its own", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--index ", + "description": "One index file, as `discoveryctl package` wrote it, checked on its own exactly as `discovery --runtime-config` parses it at startup", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--allow-loopback", + "description": "Accept an http loopback catalog URL, for development", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--environment", + "description": "Fill the runtime file's ${NAME} expressions from this process's environment and check the values they produce", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Write human-readable diagnostics or one JSON report", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "--deny-warnings", + "description": "Exit 1 when the check reports a warning", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "required-one-or-more", + "when": null, + "arguments": [ + "--project ", + "--runtime-config ", + "--index " + ] + } + ], + "subcommands": [] + }, + { + "name": "package", + "invocation": "discoveryctl package", + "about": "Fetch every enabled approved origin once and write one immutable package", + "long_about": null, + "usage": "discoveryctl package [OPTIONS] --project --output ", + "arguments": [], + "options": [ + { + "display": "--project ", + "description": "The authoring project directory: origins.yaml, the mappings directory, and every runtime file beside them", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--output ", + "description": "The new directory the package is written to", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--allow-loopback", + "description": "Accept an http loopback catalog URL, for development", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--revision ", + "description": "Optional operator revision recorded in the package envelope", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, + { + "name": "documents", + "invocation": "documents", + "about": "Run the Registry Stack Document Store", + "long_about": null, + "usage": "documents --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-V, --version", + "description": "Print version", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "serve", + "invocation": "documents serve", + "about": "Run the Document Store HTTP service", + "long_about": null, + "usage": "documents --runtime-config serve", + "arguments": [], + "options": [ + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, + { + "name": "documentsctl", + "invocation": "documentsctl", + "about": "Registry Stack Document Store adopter and local operator tooling", + "long_about": null, + "usage": "documentsctl [OPTIONS] ", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-V, --version", + "description": "Print version", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "init", + "invocation": "documentsctl init", + "about": "Write the starter project into a new directory", + "long_about": null, + "usage": "documentsctl init [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "The directory to create. It must not exist", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "check", + "invocation": "documentsctl check", + "about": "Check a project, a runtime configuration, or both, offline", + "long_about": null, + "usage": "documentsctl check [OPTIONS] <--project |--runtime-config >", "arguments": [], "options": [ { @@ -13884,18 +15306,62 @@ "environment": null }, { - "display": "--revision ", - "description": "Optional source revision recorded in the package envelope", + "display": "--revision ", + "description": "Optional source revision recorded in the package envelope", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--dry-run", + "description": "Validate and report the digest without writing the package", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", "always_required": false, "repeatable": false, "default_values": [], "possible_values": [], "environment": null - }, + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "plan", + "invocation": "documentsctl plan", + "about": "Report what apply would change in the database, writing nothing", + "long_about": null, + "usage": "documentsctl plan [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ { - "display": "--dry-run", - "description": "Validate and report the digest without writing the package", - "always_required": false, + "display": "--runtime-config ", + "description": "Runtime configuration file", + "always_required": true, "repeatable": false, "default_values": [], "possible_values": [], @@ -13929,22 +15395,58 @@ "subcommands": [] }, { - "name": "plan", - "invocation": "documentsctl plan", - "about": "Report what apply would change in the database, writing nothing", + "name": "provision", + "invocation": "documentsctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", "long_about": null, - "usage": "documentsctl plan [OPTIONS] --runtime-config ", + "usage": "documentsctl provision [OPTIONS] --runtime-config ", "arguments": [], "options": [ { "display": "--runtime-config ", - "description": "Runtime configuration file", + "description": "Runtime configuration file, the one the service runs with", "always_required": true, "repeatable": false, "default_values": [], "possible_values": [], "environment": null }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--format ", "description": "Emit the selected command's report in this format", @@ -13969,7 +15471,32 @@ "environment": null } ], - "constraints": [], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], "subcommands": [] }, { @@ -20880,6 +22407,111 @@ ], "subcommands": [] }, + { + "name": "provision", + "invocation": "messagingctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "messagingctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "plan", "invocation": "messagingctl plan", @@ -25815,6 +27447,111 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "schedulingctl provision", + "about": "Create the roles and the database the runtime file names, or print the SQL", + "long_about": null, + "usage": "schedulingctl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--runtime-config ", + "description": "Runtime configuration file, the one the service runs with", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "apply", "invocation": "schedulingctl apply", diff --git a/crates/registry-cli-docs/src/lib.rs b/crates/registry-cli-docs/src/lib.rs index 17ac1065bd..1c8cb68938 100644 --- a/crates/registry-cli-docs/src/lib.rs +++ b/crates/registry-cli-docs/src/lib.rs @@ -27,6 +27,8 @@ pub fn catalog() -> Catalog { command_reference(registry_messaging::runtime::command(), None, None), command_reference(registry_messagingctl::command(), None, None), command_reference(registry_mcp::command(), None, None), + command_reference(registry_discovery::cli::command(), None, None), + command_reference(registry_discoveryctl::command(), None, None), command_reference(registry_documents::runtime::command(), None, None), command_reference(registry_documentsctl::command(), None, None), command_reference(registry_manifest_cli::command(), None, None), @@ -166,6 +168,8 @@ mod tests { "caseworkctl", "coordinator", "coordinatorctl", + "discovery", + "discoveryctl", "documents", "documentsctl", "evidence", diff --git a/crates/registry-cli-report/Cargo.toml b/crates/registry-cli-report/Cargo.toml index 3e4a6b58ae..1bb68b21a4 100644 --- a/crates/registry-cli-report/Cargo.toml +++ b/crates/registry-cli-report/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true publish = false [dependencies] +registry-platform-posture.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/registry-cli-report/README.md b/crates/registry-cli-report/README.md index fa76bdf89b..27c347a5a4 100644 --- a/crates/registry-cli-report/README.md +++ b/crates/registry-cli-report/README.md @@ -6,6 +6,10 @@ array. Products retain their command payloads, diagnostic contracts, and exit decisions. The primitive adds no HTTP, runtime configuration, or authentication dependency. +`Report::with_posture` adds a `posture` member with `value` (`development` or +`production`) and `source` (`flag`, `environment` or `default`) after the +command members. Without it the body is unchanged. + `status` is `complete`, `domain-refusal`, `usage-error`, or `operational-failure`, corresponding to exit codes 0 through 3. A command's more specific result, such as `declined`, is an `outcome`. An invalid envelope diff --git a/crates/registry-cli-report/src/lib.rs b/crates/registry-cli-report/src/lib.rs index 12657c917f..bf7f7bc4c4 100644 --- a/crates/registry-cli-report/src/lib.rs +++ b/crates/registry-cli-report/src/lib.rs @@ -3,6 +3,7 @@ use std::io::{self, Write}; +use registry_platform_posture::{DeclaredPosture, PostureSource}; use serde::ser::{Serialize, SerializeMap as _, Serializer}; use serde_json::{json, Map, Value}; @@ -68,6 +69,7 @@ pub struct Report<'a> { version: &'a str, status: Status, outcome: Option<&'a Value>, + posture: Option, } impl<'a> Report<'a> { @@ -132,8 +134,21 @@ impl<'a> Report<'a> { version, status, outcome, + posture: None, }) } + + /// Report the declared posture as a `posture` member holding `value` and + /// `source`, placed after the command members. A command member named + /// `posture` is not written, so the key appears once. Without this call the + /// body is unchanged. + #[must_use] + pub fn with_posture(self, declared: DeclaredPosture) -> Self { + Self { + posture: Some(declared), + ..self + } + } } impl Serialize for Report<'_> { @@ -148,12 +163,17 @@ impl Serialize for Report<'_> { } map.serialize_entry("version", self.version)?; for (key, value) in self.members { + let replaced = self.posture.is_some() && key == "posture"; if !HEAD.contains(&key.as_str()) && !matches!(key.as_str(), "version" | "diagnostics" | "outcome") + && !replaced { map.serialize_entry(key, value)?; } } + if let Some(declared) = self.posture { + map.serialize_entry("posture", &PostureMember(declared))?; + } if let Some(outcome) = self.outcome { map.serialize_entry("outcome", outcome)?; } @@ -165,6 +185,26 @@ impl Serialize for Report<'_> { } } +/// The `posture` member, written with `value` before `source`. +struct PostureMember(DeclaredPosture); + +impl Serialize for PostureMember { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(2))?; + map.serialize_entry("value", self.0.posture.as_str())?; + map.serialize_entry("source", source_word(self.0.source))?; + map.end() + } +} + +fn source_word(source: PostureSource) -> &'static str { + match source { + PostureSource::Flag => "flag", + PostureSource::Environment => "environment", + PostureSource::Default => "default", + } +} + /// Static binary identity used when a command cannot finish normally. #[derive(Clone, Copy)] pub struct Identity { diff --git a/crates/registry-cli-report/tests/envelope.rs b/crates/registry-cli-report/tests/envelope.rs index e579ce022c..d90bd0c434 100644 --- a/crates/registry-cli-report/tests/envelope.rs +++ b/crates/registry-cli-report/tests/envelope.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 use registry_cli_report::{json_requested, Report, Status}; +use registry_platform_posture::{DeclaredPosture, Posture, PostureSource}; use serde_json::{json, Value}; fn members() -> Value { @@ -89,3 +90,80 @@ fn panic_output_selection_understands_both_format_spellings_and_the_terminator() )); } } + +fn declared(posture: Posture, source: PostureSource) -> DeclaredPosture { + DeclaredPosture { posture, source } +} + +#[test] +fn a_report_without_posture_is_unchanged() { + let value = members(); + let rendered = serde_json::to_string(&Report::new(&value, "1.0.0-dev").unwrap()).unwrap(); + assert_eq!( + rendered, + concat!( + r#"{"ok":true,"command":"check","status":"complete","#, + r#""apiVersion":"format/v1","kind":"CtlReport","version":"1.0.0-dev","#, + r#""filesChecked":2,"diagnostics":[]}"# + ) + ); +} + +#[test] +fn with_posture_adds_value_and_source_after_the_command_members() { + let value = members(); + let report = Report::new(&value, "1.0.0-dev") + .unwrap() + .with_posture(declared(Posture::Production, PostureSource::Default)); + let rendered = serde_json::to_string(&report).unwrap(); + assert_eq!( + rendered, + concat!( + r#"{"ok":true,"command":"check","status":"complete","#, + r#""apiVersion":"format/v1","kind":"CtlReport","version":"1.0.0-dev","#, + r#""filesChecked":2,"posture":{"value":"production","source":"default"},"#, + r#""diagnostics":[]}"# + ) + ); +} + +#[test] +fn posture_value_and_source_use_the_documented_spellings() { + for (posture, value) in [ + (Posture::Development, "development"), + (Posture::Production, "production"), + ] { + for (source, word) in [ + (PostureSource::Flag, "flag"), + (PostureSource::Environment, "environment"), + (PostureSource::Default, "default"), + ] { + let envelope = members(); + let report = serde_json::to_value( + Report::new(&envelope, "1.0.0") + .unwrap() + .with_posture(declared(posture, source)), + ) + .unwrap(); + assert_eq!(report["posture"], json!({"value": value, "source": word})); + } + } +} + +#[test] +fn the_declared_posture_replaces_a_command_member_of_the_same_name() { + let mut envelope = members(); + envelope["posture"] = json!("free text"); + let rendered = serde_json::to_string( + &Report::new(&envelope, "1.0.0") + .unwrap() + .with_posture(declared(Posture::Development, PostureSource::Flag)), + ) + .unwrap(); + assert_eq!(rendered.matches("\"posture\"").count(), 1, "{rendered}"); + let report: Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!( + report["posture"], + json!({"value": "development", "source": "flag"}) + ); +} diff --git a/crates/registry-coordinator-client/src/client.rs b/crates/registry-coordinator-client/src/client.rs index 9cb76c43f0..1eb94b69b7 100644 --- a/crates/registry-coordinator-client/src/client.rs +++ b/crates/registry-coordinator-client/src/client.rs @@ -7,7 +7,7 @@ use registry_platform_httputil::client::{ build_client, classify_keyed_attempt, read_failure_kind, retry_keyed_mutation, send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::{ header::{HeaderMap, ACCEPT, AUTHORIZATION, CONTENT_TYPE}, Method, RequestBuilder, Response, StatusCode, @@ -398,7 +398,7 @@ impl CoordinatorClient { let response = request.send().await.map_err(|e| Error::Transport { kind: send_failure_kind(&e), })?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(response.status().as_u16(), Failure::HeaderBounds))?; Ok(response) } diff --git a/crates/registry-coordinator/Cargo.toml b/crates/registry-coordinator/Cargo.toml index 06f1149aa4..029a70cf61 100644 --- a/crates/registry-coordinator/Cargo.toml +++ b/crates/registry-coordinator/Cargo.toml @@ -146,10 +146,11 @@ registry-payment-client.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true registry-platform-oidc.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-calendar.workspace = true -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-metrics.workspace = true jsonwebtoken.workspace = true registry-platform-canonical-json.workspace = true @@ -185,7 +186,8 @@ zeroize.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["test-util"] } -registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server", "migration-pins"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } +registry-platform-testing = { workspace = true, features = ["test-utils", "test-authorization-server", "migration-pins", "token-fixtures"] } tempfile.workspace = true tower.workspace = true wiremock.workspace = true diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index dce0a4eea2..2e976a4a1f 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -1,13 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 //! Verified access-token ownership and exact deployment policy matching. use crate::{store::Actor, CoordinatorError, Result}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_config::{ JwksSource, OidcClientsConfig, OidcIssuerConfig, SecretProvidersConfig, }; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifier, - TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use serde::{Deserialize, Deserializer, Serialize}; use std::{ @@ -186,7 +187,8 @@ impl AccessConfig { ) -> Vec { let mut errors = Vec::new(); for result in [ - self.issuer.check("deployment.authentication", local), + self.issuer + .check_without_posture("deployment.authentication", local), self.clients().check("deployment.authentication"), ] { if let Err(error) = result { @@ -307,14 +309,25 @@ impl AccessConfig { IssuerNetworkPolicy::new(self.issuer.issuer.as_str(), self.issuer.allow_insecure_http) .map_err(|_| refused())?; let keys = match &self.issuer.jwks_source { - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let value = secrets .resolver() .map_err(|_| refused())? .resolve(document_ref) .map_err(|_| refused())?; Arc::new(JwksFetcher::new_static( - parse_static_jwks(value.expose_secret()).map_err(|_| refused())?, + parse_static_jwks(value.expose_secret()).map_err(|error| match error { + // The text names the rule broken, and the key's position for a rule about + // one key, never key material. + OidcError::StaticKeySet(_) => CoordinatorError::new( + "access.configuration", + error.to_string(), + ) + .suggest( + "Correct the document that deployment.authentication.jwksSource.documentRef names.", + ), + _ => refused(), + })?, JwksFetcherConfig::defaults(), )) } @@ -382,6 +395,8 @@ pub struct Authenticator { verifier: TokenVerifier, policies: BTreeMap, assertion_issuers: bool, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, } pub struct Caller { pub actor: Actor, @@ -397,7 +412,7 @@ impl Caller { if !self.policy.actions.contains(&action) || workflow.is_some_and(|workflow| !self.policy.workflows.iter().any(|f| f == workflow)) { - return Err(denied()); + return Err(denied(FailedCheck::Operation)); } Ok(()) } @@ -411,16 +426,37 @@ impl Caller { || !self.policy.operator || !self.policy.actions.contains(&action) { - return Err(denied()); + return Err(denied(FailedCheck::Operation)); } Ok(()) } } -fn denied() -> CoordinatorError { +/// A resolved caller for tests that need no token: the policy lists +/// `actions` on `workflows`. +#[cfg(test)] +pub(crate) fn synthetic_caller(actions: Vec, workflows: &[&str], operator: bool) -> Caller { + Caller { + actor: Actor { + issuer: "https://issuer.example".into(), + subject: "subject".into(), + client_id: "client".into(), + operator, + }, + policy: ClientPolicy { + subjects: vec!["subject".into()], + required_scopes: vec!["coordinator:operate".into()], + workflows: workflows.iter().map(|w| (*w).to_owned()).collect(), + actions, + operator, + }, + } +} +fn denied(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "access.denied", "the caller policy does not authorize this operation", ) + .failing(check) } /// The bound admission puts on a token subject, and so on every subject a /// policy may list: non-empty, at most 512 bytes, no control characters. @@ -435,6 +471,7 @@ impl Authenticator { assertion_issuers: bool, ) -> Self { Self { + scope_claim: profile.scope_claim.clone(), verifier: TokenVerifier::new(profile, keys), policies, assertion_issuers, @@ -442,10 +479,12 @@ impl Authenticator { } pub async fn authenticate(&self, token: &str) -> Result { registry_platform_authcommon::validate_compact_access_token(token) - .map_err(|_| unauthenticated())?; - let verified = self.verifier.verify(token).await.map_err(|error| { - use registry_platform_oidc::OidcError; - match error { + .map_err(|_| unauthenticated(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| match error { OidcError::Transport(_) | OidcError::BoundedRead(_) | OidcError::FetchUrl(_) @@ -458,45 +497,48 @@ impl Authenticator { | OidcError::ConflictingEndpointConfiguration => CoordinatorError::new( "access.unavailable", "the configured verifier cannot answer", - ), - _ => unauthenticated(), - } - })?; + ) + .failing(FailedCheck::KeySourceUnavailable), + _ => unauthenticated(error.failed_check()), + })?; if !self.assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - return Err(unauthenticated()); + return Err(unauthenticated(FailedCheck::TokenAssertionIssuer)); } let client = verified .matched_client_id() - .map_err(|_| unauthenticated())? - .ok_or_else(unauthenticated)?; + .map_err(|_| unauthenticated(FailedCheck::TokenClient))? + .ok_or_else(|| unauthenticated(FailedCheck::TokenClient))?; let issuer = verified .claims .iss .as_deref() .filter(|s| !s.is_empty()) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .as_deref() .filter(|s| admitted_subject(s)) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::TokenClaims))?; // A token carrying `act` was issued for someone other than the client // that presents it, typically a person delegated to that client. The // Coordinator admits only a client's own identities. if verified.claims.extra.contains_key("act") { - return Err(denied()); + return Err(denied(FailedCheck::Delegation)); } let p = self .policies .get(client) .filter(|p| p.subjects.iter().any(|s| s == subject)) - .filter(|p| { - p.required_scopes - .iter() - .all(|s| verified.scopes.contains(s)) - }) - .ok_or_else(denied)?; + .ok_or_else(|| denied(FailedCheck::AccessProfile))?; + if let Some(missing) = p + .required_scopes + .iter() + .find(|s| !verified.scopes.contains(s)) + { + return Err(denied(FailedCheck::Scope) + .declaring(DeclaredScope::new(&self.scope_claim).with_required_scope(missing))); + } Ok(Caller { actor: Actor { issuer: issuer.into(), @@ -522,11 +564,12 @@ fn access_error(field: &str, advice: &str) -> CoordinatorError { .at("runtime.yaml", crate::runtime::pointer(field)) .suggest(advice) } -fn unauthenticated() -> CoordinatorError { +pub(crate) fn unauthenticated(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "access.unauthenticated", "a verified access token is required", ) + .failing(check) } fn unique_actions<'de, D: Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { @@ -556,6 +599,9 @@ impl Serialize for AccessConfig { } } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] mod tests { use super::*; @@ -563,24 +609,7 @@ mod tests { use registry_platform_yaml::Url; fn caller(actions: Vec, workflows: &[&str], operator: bool) -> Caller { - Caller { - actor: Actor { - issuer: "https://issuer.example".into(), - subject: "subject".into(), - client_id: "client".into(), - operator, - }, - policy: ClientPolicy { - subjects: vec!["subject".into()], - required_scopes: vec!["coordinator:operate".into()], - workflows: workflows - .iter() - .map(|workflow| (*workflow).to_owned()) - .collect(), - actions, - operator, - }, - } + synthetic_caller(actions, workflows, operator) } #[test] @@ -642,4 +671,21 @@ mod tests { ["workflow-a"] ); } + + #[test] + fn a_policy_denial_after_authentication_names_the_operation_check() { + let scoped = caller(vec![Action::Status, Action::Doctor], &["workflow-a"], true); + let not_operator = caller(vec![Action::Doctor], &[], false); + for denial in [ + scoped.authorize(Action::Start, Some("workflow-a")), + scoped.authorize(Action::Status, Some("workflow-b")), + scoped.authorized_workflows(Action::Start).map(|_| ()), + scoped.authorize_deployment(Action::Status), + not_operator.authorize_deployment(Action::Doctor), + ] { + let denial = denial.unwrap_err(); + assert_eq!(denial.code, "access.denied"); + assert_eq!(denial.check, Some(FailedCheck::Operation)); + } + } } diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs new file mode 100644 index 0000000000..d292ce50c5 --- /dev/null +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Characterises which identity-provider tokens the Coordinator's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds the authenticator the server builds, through +//! `AccessConfig::authenticator`, over a static key set holding the corpus +//! signer's public keys, and presents the fixture to `Authenticator::authenticate`. +//! The module sits under `access` so it can also ask the authenticator's own +//! verifier for the check that refused a token and compare it with the check +//! the refusal carries. +use super::*; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use registry_platform_yaml::Url; +use serde_json::Value; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:coordinator:test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SUBJECT: &str = "placeholder-subject"; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn first_scope(fixture: &TokenFixture) -> Option { + fixture.read_scope("scope") +} + +async fn authenticator_for(case: &FixtureCase, secrets: &SecretProvidersConfig) -> Authenticator { + let scope_claim = match case.configuration { + Configuration::Recipe => "scope", + _ => "registry_scopes", + }; + let policy = ClientPolicy { + subjects: vec![literal(&case.fixture, "sub").unwrap_or_else(|| PLACEHOLDER_SUBJECT.into())], + required_scopes: vec![ + first_scope(&case.fixture).unwrap_or_else(|| PLACEHOLDER_SCOPE.into()) + ], + workflows: vec!["follow-up".into()], + actions: vec![Action::Start, Action::Status], + operator: false, + }; + let client = client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into()); + let access = AccessConfig { + issuer: OidcIssuerConfig { + issuer: Url::new(case.issuer.clone()).expect("issuer URL"), + audience: case.audience.clone(), + jwks_source: JwksSource::Static { + document_ref: format!("secret:file/{KEY_FILE}"), + }, + allow_insecure_http: false, + }, + assertion_issuers: BTreeMap::new(), + scope_claim: scope_claim.into(), + policies: BTreeMap::from([(client, policy)]), + }; + access + .authenticator(secrets, false) + .await + .expect("the authenticator builds over the static key set") +} + +async fn observe(authenticator: &Authenticator, token: &str) -> Outcome { + let verdict = authenticator.verifier.verify(token).await; + let admission = authenticator.authenticate(token).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(refusal), Err(error)) => { + assert_eq!( + refusal.check, + Some(error.failed_check()), + "the refusal names the verifier's check" + ); + Outcome::refused_by(&error) + } + (Err(error), Ok(_)) => { + let (outcome, checks): (_, &[FailedCheck]) = match error.code.as_str() { + "access.denied" => ( + "refused/scope", + &[ + FailedCheck::Delegation, + FailedCheck::AccessProfile, + FailedCheck::Scope, + ], + ), + "access.unauthenticated" => ( + "refused/claims", + &[ + FailedCheck::TokenAssertionIssuer, + FailedCheck::TokenClient, + FailedCheck::TokenClaims, + ], + ), + "access.unavailable" => { + ("refused/unavailable", &[FailedCheck::KeySourceUnavailable]) + } + other => panic!("authenticate refused with the unexpected code {other}"), + }; + assert!( + error.check.is_some_and(|check| checks.contains(&check)), + "{} carries a check from {checks:?}, not {:?}", + error.code, + error.check + ); + outcome.parse().expect("result value") + } + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let root = tempfile::tempdir().expect("key directory"); + let root_path = root.path().canonicalize().expect("physical key directory"); + let key_file = root_path.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let secrets = SecretProvidersConfig { + file: Some(registry_platform_config::FileSecretProviderConfig { root: root_path }), + environment: None, + }; + let secrets = &secrets; + let report = corpus + .run_product_async( + "coordinator", + &signer, + ISSUER, + AUDIENCE, + |case| async move { + let authenticator = authenticator_for(&case, secrets).await; + observe(&authenticator, case.token.expose()).await + }, + ) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index a22bc778a8..b73c12e7ae 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -89,6 +89,7 @@ struct TaskConnection { } pub struct HttpAdapters { + event_keys: crate::event_trigger::EventKeys, connections: BTreeMap, digest: String, config: RuntimeConfig, @@ -106,7 +107,7 @@ fn config_error() -> CoordinatorError { // reject metadata addresses. Cleartext remains numeric loopback only. fn configured_endpoint_policy(endpoint: &Url) -> FetchUrlPolicy { if endpoint.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], @@ -167,6 +168,14 @@ impl HttpAdapters { } pub fn new(config: &RuntimeConfig) -> Result { + config.validate()?; + Self::with_event_keys(config, crate::event_trigger::resolve_keys(config)?) + } + + pub(crate) fn with_event_keys( + config: &RuntimeConfig, + event_keys: crate::event_trigger::EventKeys, + ) -> Result { config.validate()?; let secrets = Arc::new( config @@ -335,23 +344,26 @@ impl HttpAdapters { crate::runtime::DEFAULT_RESULT_CHECK_SECONDS, registry_platform_yaml::BoundedU32::get, ); - let completion = match &binding.completion { - Some(completion) => { - let bytes = secrets - .resolve_reference(&completion.bearer_token_ref) - .map_err(|_| config_error())?; - let token = std::str::from_utf8(bytes.expose_secret()) - .map_err(|_| config_error())?; - if !valid_completion_token(token) { - return Err(config_error()); - } - Some(crate::review::CompletionSender { - token: zeroize::Zeroizing::new(token.to_owned()), + let completion = binding + .completion + .map(|completion| { + let ingress = crate::event_trigger::IngressKeys::resolve( + &secrets, + format!("connections.{name}.completion"), + &completion.hmac_sha256_key_ref, + completion.previous_hmac_sha256_key_ref.as_ref(), + |path, advice| { + config_error() + .at("runtime.yaml", crate::runtime::pointer(path)) + .suggest(advice) + }, + )?; + Ok(crate::review::CompletionSender { + ingress, recipient: completion.recipient_binding.clone(), }) - } - None => None, - }; + }) + .transpose()?; let tokens = tokens(&auth, key, &auth.resource, &auth.scopes) .map_err(|_| config_error())?; let client = CaseworkClient::new( @@ -376,8 +388,22 @@ impl HttpAdapters { }; connections.insert(name.clone(), connection); } + let completion_keys = connections + .values() + .filter_map(|connection| match connection { + Connection::Casework(connection) => connection.completion(), + _ => None, + }); + registry_platform_crypto::delivery_signature::distinct_delivery_keys( + event_keys + .values() + .flat_map(|keys| keys.labelled()) + .chain(completion_keys.flat_map(|sender| sender.ingress.labelled())), + ) + .map_err(|error| crate::event_trigger::duplicate_key(error.first(), error.second()))?; let digest = config.binding_digest()?; Ok(Self { + event_keys, connections, digest, config: config.clone(), @@ -385,14 +411,6 @@ impl HttpAdapters { } } -/// A completion token is a bearer token Casework can send unchanged: the -/// header grammar holds it and it is at most 4096 bytes. -fn valid_completion_token(token: &str) -> bool { - token.len() <= 4096 - && registry_platform_authcommon::parse_bearer_token(&format!("Bearer {token}")) - .is_ok_and(|parsed| parsed == token) -} - pub(crate) fn refused(code: &str) -> CallOutcome { CallOutcome::Refused { code: code.to_owned(), @@ -1302,24 +1320,30 @@ impl AdapterSet for HttpAdapters { } } - fn review_completion(&self, token: &str, recipient: &str) -> Option { - // Every connection is compared, so the time taken does not depend on - // which one matched. - let mut matched = None; - let mut ambiguous = false; - for (name, connection) in &self.connections { - if let Connection::Casework(connection) = connection { - if connection.completion_matches(token, recipient) { - ambiguous |= matched.is_some(); - matched = Some(name.clone()); - } - } - } - if ambiguous { - None - } else { - matched - } + fn event_keys( + &self, + workflow: &str, + trigger: &str, + ) -> Option<®istry_platform_crypto::delivery_signature::DeliveryKeys> { + use registry_platform_yaml::LocalId; + let path = (LocalId::new(workflow).ok()?, LocalId::new(trigger).ok()?); + self.event_keys.get(&path).map(|ingress| &ingress.keys) + } + + fn review_completion( + &self, + recipient: &str, + ) -> Option<( + &str, + ®istry_platform_crypto::delivery_signature::DeliveryKeys, + )> { + self.connections.iter().find_map(|(name, connection)| { + let Connection::Casework(connection) = connection else { + return None; + }; + let sender = connection.completion()?; + (sender.recipient == recipient).then_some((name.as_str(), &sender.ingress.keys)) + }) } async fn reconcile( diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 5ecc377b5f..1a7c20660c 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -2390,12 +2390,13 @@ pub(crate) fn positioned(document: &Document, error: CoordinatorError) -> Coordi error.code.as_str(), "function.value_limit" | "function.json" ) - && error.file.as_deref() != Some(Path::new("workflow.yaml")) + && error.file.as_deref().map(std::path::PathBuf::as_path) + != Some(Path::new("workflow.yaml")) { let mut error = error; error .file - .get_or_insert_with(|| Path::new("functions.rhai").into()); + .get_or_insert_with(|| Box::new(std::path::PathBuf::from("functions.rhai"))); return CoordinatorError::from_report(error.report()); } let exit = error.exit_code; diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index 9cd9351217..64690ac757 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -192,6 +192,9 @@ enum Command { /// Active workflow to retire because its package is no longer listed; repeat for each workflow. remove_workflow: Vec, }, + /// Create the database, the migration and runtime roles, and the grants `apply` expects, as a PostgreSQL administrator. + #[command(mut_arg("runtime_config", |argument| argument.required(false)))] + Provision(registry_platform_provision::cli::ProvisionArgs), /// Apply every listed workflow's package and least-privileged runtime grants using migration credentials. Apply { #[arg(long = "remove-workflow", value_name = "WORKFLOW")] @@ -380,6 +383,7 @@ impl Command { Self::Test { .. } => "test", Self::Package { .. } => "package", Self::Plan { .. } => "plan", + Self::Provision(_) => "provision", Self::Apply { .. } => "apply", Self::DeploymentStatus => "deployment-status", Self::Openapi => "openapi", @@ -587,12 +591,15 @@ fn runtime(cli: &Cli) -> Result { .suggest("Add --runtime-config with the deployment's runtime.yaml.") })?) } -/// `--runtime-config` made absolute against the working directory, with `.` -/// and `..` resolved by name, as the runtime loader requires. fn runtime_config(cli: &Cli) -> Result> { - let Some(path) = cli.runtime_config.as_deref() else { - return Ok(None); - }; + cli.runtime_config + .as_deref() + .map(absolute_runtime_path) + .transpose() +} +/// A `--runtime-config` path made absolute against the working directory, with +/// `.` and `..` resolved by name, as the runtime loader requires. +pub(crate) fn absolute_runtime_path(path: &Path) -> Result { let absolute = std::path::absolute(path).map_err(|_| { CoordinatorError::new( "runtime-config-unresolved", @@ -610,7 +617,7 @@ fn runtime_config(cli: &Cli) -> Result> { other => normal.push(other), } } - Ok(Some(normal)) + Ok(normal) } async fn remote( service: &Service, @@ -627,8 +634,12 @@ async fn remote( .suggest("Add --url with the Coordinator service origin, such as --url https://coordinator.example.org.") })?; let loopback = match url.host() { - Some(url::Host::Ipv4(ip)) => ip.is_loopback(), - Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + Some(url::Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(url::Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; if !(url.scheme() == "https" || url.scheme() == "http" && loopback) @@ -781,9 +792,8 @@ fn refusal_advice(problem: ProblemCode) -> Option<&'static str> { ProblemCode::RunDefinitionIncompatible => "This service's Coordinator version cannot interpret the run's pinned definition, so it holds the run and refuses to retry, reconcile or cancel it; only a Coordinator release that accepts that definition can.", ProblemCode::ReceiptExpired => "Consult the receiving product's own records for the original command rather than inferring it was not sent, and cancel the run when no further execution is appropriate.", ProblemCode::EventInvalid => "Correct the producer event contract or the reviewed trigger's event schema and input mapping before retrying delivery.", - ProblemCode::EventSourceUnavailable => "Restore the event source signing key and its enabled secret provider in runtime.yaml before retrying delivery.", ProblemCode::EventTooLarge => "Project fewer or smaller fields into the producer's event so it fits the 131072-byte event value profile, then redeliver it.", - ProblemCode::EventUnauthenticated => "Use the exact configured event source, accepted event type and data schema, and a fresh signature covering the received method, target, headers and canonical body.", + ProblemCode::EventUnauthenticated => "Sign the webhook ID, timestamp and exact body with the key configured for this trigger URL, within 300 seconds.", ProblemCode::EvaluationUncertain => "Inspect the run and cancel it when no further execution is appropriate; retry-same never reevaluates an evaluation that may have completed.", ProblemCode::MutationUncertain => "Inspect the run and cancel it when no further execution is appropriate; retry-same never repeats an unkeyed mutation that may have completed.", ProblemCode::RunPayloadErased => "Retention erased this run's payloads; inspect it, but it can no longer be retried or reconciled.", @@ -818,6 +828,9 @@ async fn execute(cli: &Cli) -> Result { Command::Serve { .. } => { unreachable!("serve replaces the ctl process before report dispatch") } + Command::Provision(_) => { + unreachable!("provision writes its own report before report dispatch") + } Command::Init { directory, id } => { let created = project::init(directory, id.as_deref())?; Ok(json!({"status":"initialized","project":directory,"created":created})) @@ -1066,6 +1079,13 @@ fn usage(error: &clap::Error, arguments: &[String]) -> CoordinatorError { format!("missing required argument {all}"), format!("Add {all}; {help} describes it."), ), + // A required argument the command's own definition relaxes, so that a + // global flag given before the command satisfies it, is checked when + // its value is read and names no argument. + (ErrorKind::MissingRequiredArgument, None) => ( + "missing required argument".to_owned(), + format!("Add the missing argument; {help} describes it."), + ), (ErrorKind::InvalidValue | ErrorKind::ValueValidation, Some(name)) => ( format!("invalid value for {name}"), match error.get(ContextKind::ValidValue) { @@ -1168,6 +1188,13 @@ pub async fn run() -> std::process::ExitCode { if let Command::Serve { coordinator_bin } = &cli.command { return serve(&cli, coordinator_bin.as_deref(), format_requested); } + if let Command::Provision(args) = &cli.command { + let format = match cli.format { + Format::Human => registry_platform_provision::cli::OutputFormat::Human, + Format::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + return crate::provision::run(args.clone(), format).await; + } let cli = match cli { Cli { command: Command::Api(args), diff --git a/crates/registry-coordinator/src/completion.rs b/crates/registry-coordinator/src/completion.rs index a12923ec35..a6013d1308 100644 --- a/crates/registry-coordinator/src/completion.rs +++ b/crates/registry-coordinator/src/completion.rs @@ -5,7 +5,7 @@ //! the connection's producer credential, and only that read can settle it. use crate::{ - http::{problem, single_header}, + http::{problem, single_header, WEBHOOK_CHALLENGE}, metrics::AuthenticationRefusal, protocol::AdapterSet, store::Store, @@ -16,6 +16,10 @@ use axum::{ response::{IntoResponse, Response}, }; use chrono::{DateTime, Utc}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_crypto::delivery_signature::{ + self, DeliverySignatureError, SignedContent, DELIVERY_TOLERANCE, +}; use registry_review_protocol::ReviewCompletion; use uuid::Uuid; @@ -70,7 +74,6 @@ pub(crate) fn interpret_poll( /// The header naming the recipient binding Casework's destination declares. pub const RECIPIENT_BINDING_HEADER: &str = "registry-recipient-binding"; -const IDEMPOTENCY_KEY_HEADER: &str = "idempotency-key"; const MAXIMUM_BODY_BYTES: usize = 2048; /// The oldest completion still accepted: Casework retries a delivery for at /// most this long. @@ -90,12 +93,18 @@ pub async fn receive_review_completion( let (connection, request) = match authenticate(adapters, headers, body, Utc::now()) { Ok(event) => event, Err(error) => { - if error.code == "access.unauthenticated" { + let refused = error.code == "access.unauthenticated"; + let mut response = problem(error); + if refused { store .metrics() .record_authentication_refusal(AuthenticationRefusal::Refused); + response.headers_mut().insert( + header::WWW_AUTHENTICATE, + HeaderValue::from_static(WEBHOOK_CHALLENGE), + ); } - return problem(error); + return response; } }; match store.wake(&connection, request).await { @@ -113,47 +122,70 @@ pub async fn receive_review_completion( } } -/// The connection whose completion credential and recipient binding the -/// sender presented, and the request its event names. The sender is -/// authenticated before the media type or body is examined. +/// Verify the signature using the connection selected by the recipient binding, +/// then return that connection and the request to wake. pub(crate) fn authenticate( adapters: &dyn AdapterSet, headers: &HeaderMap, body: Option<&[u8]>, now: DateTime, ) -> Result<(String, Uuid), CoordinatorError> { - let refused = || { + let refused = |check: FailedCheck| { CoordinatorError::new( "access.unauthenticated", - "a configured completion credential and recipient binding are required", + "a fresh signed completion for a configured recipient binding is required", ) + .failing(check) }; - let token = single_header(headers, header::AUTHORIZATION.as_str()) - .and_then(|value| registry_platform_authcommon::parse_bearer_token(value).ok()) - .ok_or_else(refused)?; - let recipient = single_header(headers, RECIPIENT_BINDING_HEADER).ok_or_else(refused)?; - let connection = adapters - .review_completion(token, recipient) - .ok_or_else(refused)?; - if single_header(headers, header::CONTENT_TYPE.as_str()) != Some("application/json") { - return Err(CoordinatorError::new( - "request.content-type-invalid", - "supply application/json", - )); - } + let signature_refused = || refused(FailedCheck::DeliverySignature); let invalid = || { CoordinatorError::new( "request.invalid", "supply one bounded review completion event", ) }; - let key = single_header(headers, IDEMPOTENCY_KEY_HEADER).ok_or_else(invalid)?; - let body = body - .filter(|body| !body.is_empty() && body.len() <= MAXIMUM_BODY_BYTES) - .ok_or_else(invalid)?; + let body = body.ok_or_else(invalid)?; + if body.len() > MAXIMUM_BODY_BYTES { + return Err(CoordinatorError::new( + "request.body-too-large", + format!("supply a review completion event of at most {MAXIMUM_BODY_BYTES} bytes"), + )); + } + let recipient = + single_header(headers, RECIPIENT_BINDING_HEADER).ok_or_else(signature_refused)?; + let (connection, keys) = adapters + .review_completion(recipient) + .ok_or_else(signature_refused)?; + let id = single_header(headers, "webhook-id").ok_or_else(signature_refused)?; + let timestamp = single_header(headers, "webhook-timestamp").ok_or_else(signature_refused)?; + let signature = single_header(headers, "webhook-signature").ok_or_else(signature_refused)?; + delivery_signature::verify( + keys, + SignedContent { + id, + timestamp, + signature, + body, + }, + now.into(), + DELIVERY_TOLERANCE, + ) + .map_err(|error| match error { + DeliverySignatureError::StaleDelivery | DeliverySignatureError::InvalidTimestamp => { + refused(FailedCheck::DeliveryFreshness) + } + _ => signature_refused(), + })?; + if single_header(headers, header::CONTENT_TYPE.as_str()) != Some("application/json") { + return Err(CoordinatorError::new( + "request.content-type-invalid", + "supply application/json", + )); + } let value = registry_platform_canonical_json::parse_json_strict(body).map_err(|_| invalid())?; + let id_matches = value["eventId"].as_str() == Some(id); let event: ReviewCompletion = serde_json::from_value(value).map_err(|_| invalid())?; - if key != event.event_id.to_string() + if !id_matches || event.event_id.is_nil() || event.request_id.is_nil() || event.result_id.is_nil() @@ -161,7 +193,7 @@ pub(crate) fn authenticate( { return Err(invalid()); } - Ok((connection, event.request_id)) + Ok((connection.to_owned(), event.request_id)) } fn completed_at_is_acceptable(completed_at: DateTime, now: DateTime) -> bool { @@ -176,10 +208,15 @@ mod tests { use async_trait::async_trait; use serde_json::json; - const TOKEN: &str = "synthetic-completion-token-0123456789abcdef"; + use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; + const RECIPIENT: &str = "coordinator-v1"; - struct Receiver; + struct Receiver(DeliveryKeys); + + fn receiver() -> Receiver { + Receiver(DeliveryKeys::new(DeliveryKey::new(&[0x29; 32]).unwrap(), None).unwrap()) + } #[async_trait] impl AdapterSet for Receiver { @@ -191,29 +228,36 @@ mod tests { unreachable!("the receiver never calls a product") } - fn review_completion(&self, token: &str, recipient: &str) -> Option { - (token == TOKEN && recipient == RECIPIENT).then(|| "review".to_owned()) + fn review_completion(&self, recipient: &str) -> Option<(&str, &DeliveryKeys)> { + (recipient == RECIPIENT).then_some(("review", &self.0)) } } - fn headers(event: Uuid) -> HeaderMap { + fn headers( + receiver: &Receiver, + event: Uuid, + body: &[u8], + delivered_at: DateTime, + ) -> HeaderMap { let mut headers = HeaderMap::new(); - headers.insert( - header::AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {TOKEN}")).unwrap(), - ); - headers.insert( - RECIPIENT_BINDING_HEADER, - HeaderValue::from_static(RECIPIENT), - ); - headers.insert( - header::CONTENT_TYPE, - HeaderValue::from_static("application/json"), - ); - headers.insert( - IDEMPOTENCY_KEY_HEADER, - HeaderValue::from_str(&event.to_string()).unwrap(), - ); + let id = event.to_string(); + let timestamp = delivered_at.timestamp().to_string(); + let signature = sign( + &receiver.0, + &id, + delivered_at.timestamp().try_into().unwrap(), + body, + ) + .unwrap(); + for (name, value) in [ + (RECIPIENT_BINDING_HEADER, RECIPIENT), + ("content-type", "application/json"), + ("webhook-id", &id), + ("webhook-timestamp", ×tamp), + ("webhook-signature", &signature), + ] { + headers.insert(name, HeaderValue::from_str(value).unwrap()); + } headers } @@ -236,65 +280,108 @@ mod tests { } #[test] - fn an_authentic_event_names_its_connection_and_request() { + fn a_completion_signed_with_its_connection_key_is_accepted() { let (event, request, now) = (Uuid::new_v4(), Uuid::new_v4(), Utc::now()); - let accepted = authenticate( - &Receiver, - &headers(event), - Some(&body(event, request, now)), - now, - ) - .unwrap(); - assert_eq!(accepted, ("review".to_owned(), request)); + let receiver = receiver(); + let body = body(event, request, now); + let headers = headers(&receiver, event, &body, now); + assert_eq!( + authenticate(&receiver, &headers, Some(&body), now).unwrap(), + ("review".to_owned(), request) + ); } #[test] - fn a_sender_without_the_configured_credential_and_binding_is_refused_before_its_body() { - let event = Uuid::new_v4(); - let mut cases = Vec::new(); - let mut forged = headers(event); - forged.insert( - header::AUTHORIZATION, - HeaderValue::from_static("Bearer another-synthetic-token-0123456789"), - ); - cases.push(("forged token", forged)); - let mut basic = headers(event); - basic.insert( - header::AUTHORIZATION, - HeaderValue::from_static("Basic c3ludGhldGlj"), - ); - cases.push(("another scheme", basic)); - let mut absent = headers(event); - absent.remove(header::AUTHORIZATION); - cases.push(("no credential", absent)); - let mut doubled = headers(event); - doubled.append( - header::AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {TOKEN}")).unwrap(), - ); - cases.push(("two credentials", doubled)); - let mut other = headers(event); - other.insert( + fn an_unknown_recipient_binding_gets_the_signature_refusal() { + let receiver = receiver(); + let (event, now) = (Uuid::new_v4(), Utc::now()); + let body = body(event, Uuid::new_v4(), now); + let original = headers(&receiver, event, &body, now); + for (name, value) in [ + (RECIPIENT_BINDING_HEADER, "other-recipient"), + ("webhook-signature", "v1,invalid"), + ] { + let mut headers = original.clone(); + headers.insert(name, HeaderValue::from_static(value)); + let refusal = authenticate(&receiver, &headers, Some(&body), now).unwrap_err(); + assert_eq!(refusal.code, "access.unauthenticated"); + assert_eq!(refusal.check, Some(FailedCheck::DeliverySignature)); + } + for name in [ RECIPIENT_BINDING_HEADER, - HeaderValue::from_static("another-recipient"), + "webhook-id", + "webhook-timestamp", + "webhook-signature", + ] { + let mut repeated = original.clone(); + repeated.append(name, original[name].clone()); + let mut missing = original.clone(); + missing.remove(name); + for headers in [repeated, missing] { + let refusal = authenticate(&receiver, &headers, Some(&body), now).unwrap_err(); + assert_eq!( + refusal.check, + Some(FailedCheck::DeliverySignature), + "{name}" + ); + } + } + } + + #[test] + fn oversized_completions_are_refused_independently_of_the_recipient() { + let receiver = receiver(); + let now = Utc::now(); + let body = vec![b'x'; MAXIMUM_BODY_BYTES + 1]; + for recipient in [RECIPIENT, "other-recipient"] { + let mut headers = headers(&receiver, Uuid::new_v4(), &body, now); + headers.insert( + RECIPIENT_BINDING_HEADER, + HeaderValue::from_static(recipient), + ); + assert_eq!( + code(authenticate(&receiver, &headers, Some(&body), now)), + "request.body-too-large" + ); + } + } + + #[test] + fn a_completion_whose_event_id_differs_from_webhook_id_is_refused() { + let receiver = receiver(); + let now = Utc::now(); + let body = body(Uuid::new_v4(), Uuid::new_v4(), now); + let headers = headers(&receiver, Uuid::new_v4(), &body, now); + assert_eq!( + code(authenticate(&receiver, &headers, Some(&body), now)), + "request.invalid" ); - cases.push(("another recipient", other)); - let mut unbound = headers(event); - unbound.remove(RECIPIENT_BINDING_HEADER); - cases.push(("no recipient", unbound)); - let mut two = headers(event); - two.append( - RECIPIENT_BINDING_HEADER, - HeaderValue::from_static(RECIPIENT), + } + + #[test] + fn the_completion_window_is_300_seconds_in_both_directions() { + let receiver = receiver(); + let (event, now) = ( + Uuid::new_v4(), + DateTime::from_timestamp(1_800_000_000, 0).unwrap(), ); - cases.push(("two recipients", two)); - for (case, headers) in cases { - // The body is not even JSON: authentication answers first. - assert_eq!( - code(authenticate(&Receiver, &headers, Some(b"{"), Utc::now())), - "access.unauthenticated", - "{case}" + let body = body(event, Uuid::new_v4(), now); + for delta in [-301_i64, -300, 300, 301] { + let headers = headers( + &receiver, + event, + &body, + now + chrono::Duration::seconds(delta), ); + let result = authenticate(&receiver, &headers, Some(&body), now); + if delta.abs() == 301 { + assert_eq!( + result.unwrap_err().check, + Some(FailedCheck::DeliveryFreshness) + ); + } else { + result.unwrap(); + } } } @@ -307,7 +394,8 @@ mod tests { Some("application/json; charset=utf-8"), None, ] { - let mut headers = headers(event); + let receiver = receiver(); + let mut headers = headers(&receiver, event, &body, now); match media { Some(media) => { headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(media)); @@ -317,7 +405,7 @@ mod tests { } } assert_eq!( - code(authenticate(&Receiver, &headers, Some(&body), now)), + code(authenticate(&receiver, &headers, Some(&body), now)), "request.content-type-invalid", "{media:?}" ); @@ -375,84 +463,26 @@ mod tests { )), ), ]; + let receiver = receiver(); for (case, body) in cases { + let headers = headers(&receiver, event, body.as_deref().unwrap_or_default(), now); + let expected = if case == "an oversized body" { + "request.body-too-large" + } else { + "request.invalid" + }; assert_eq!( - code(authenticate( - &Receiver, - &headers(event), - body.as_deref(), - now - )), - "request.invalid", - "{case}" - ); - } - let mut replayed = headers(event); - replayed.insert( - IDEMPOTENCY_KEY_HEADER, - HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap(), - ); - let mut unkeyed = headers(event); - unkeyed.remove(IDEMPOTENCY_KEY_HEADER); - for (case, headers) in [("another event key", replayed), ("no event key", unkeyed)] { - assert_eq!( - code(authenticate(&Receiver, &headers, Some(&valid), now)), - "request.invalid", + code(authenticate(&receiver, &headers, body.as_deref(), now)), + expected, "{case}" ); } let nil = Uuid::nil(); + let body = body(nil, request, now); + let headers = headers(&receiver, nil, &body, now); assert_eq!( - code(authenticate( - &Receiver, - &headers(nil), - Some(&body(nil, request, now)), - now - )), - "request.invalid", - "a nil event" - ); - } - - #[test] - fn a_completion_within_its_delivery_window_is_accepted() { - let now = Utc::now(); - for completed_at in [ - now - chrono::Duration::days(OLDEST_COMPLETION_DAYS), - now, - now + chrono::Duration::minutes(FUTURE_COMPLETION_MINUTES), - ] { - assert!(completed_at_is_acceptable(completed_at, now)); - } - } - - #[test] - fn a_refusal_carries_no_presented_value() { - let event = Uuid::new_v4(); - let mut forged = headers(event); - forged.insert( - header::AUTHORIZATION, - HeaderValue::from_static("Bearer forged-canary-token-0123456789"), + code(authenticate(&receiver, &headers, Some(&body), now)), + "request.invalid" ); - let request = Uuid::new_v4(); - for headers in [forged, headers(Uuid::new_v4())] { - let error = authenticate( - &Receiver, - &headers, - Some(&body(event, request, Utc::now())), - Utc::now(), - ) - .unwrap_err(); - let rendered = format!("{} {:?}", error.message, error.suggested_action); - for secret in [ - "forged-canary", - TOKEN, - RECIPIENT, - &event.to_string(), - &request.to_string(), - ] { - assert!(!rendered.contains(secret), "{rendered}"); - } - } } } diff --git a/crates/registry-coordinator/src/decision.rs b/crates/registry-coordinator/src/decision.rs index c75a87f5c5..b097f20325 100644 --- a/crates/registry-coordinator/src/decision.rs +++ b/crates/registry-coordinator/src/decision.rs @@ -92,8 +92,12 @@ impl DecisionConfig { pub fn findings(&self, prefix: &str) -> Vec { let loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; let mut errors = Vec::new(); @@ -311,7 +315,7 @@ impl DecisionConnection { timeout: Duration, ) -> std::result::Result { let policy = if self.endpoint.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index d4608d6446..e29e334bf4 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -327,6 +327,33 @@ impl Workflows { for package in self.packages.values() { runtime.validate_workflow(&package.definition.workflow)?; } + for (alias, source) in &runtime.event_sources { + for (workflow, triggers) in &source.triggers { + let package = self.get(workflow.as_str()); + for trigger in triggers.0.keys() { + let deployed = package.and_then(|package| { + package + .definition + .workflow + .event_triggers + .get(trigger.as_str()) + }); + if deployed.is_none_or(|trigger| trigger.source != *alias) { + let field = format!( + "eventSources.{alias}.triggers.{workflow}.{trigger}.hmacSha256KeyRef" + ); + return Err(CoordinatorError::new( + "coordinator.event.configuration", + "the event trigger configuration was refused", + ) + .at("runtime.yaml", format!("/{}", field.replace('.', "/"))) + .suggest(format!( + "Remove {field} or deploy the corresponding trigger bound to {alias}." + ))); + } + } + } + } Ok(()) } } @@ -510,7 +537,7 @@ async fn open_named( } else { destination }; - let audit = AuditWriter::open(destination) + let audit = AuditWriter::open_without_posture(destination) .await .map_err(audit_open_refusal)?; let security = StoreSecurity { @@ -580,7 +607,7 @@ const SCHEMA_VERSION: i64 = crate::store::SCHEMA_VERSION as i64; /// with the namespace as the search path. Pinned with the protected state /// schema it records. pub(crate) fn activation_ledger_statements() -> String { - format!("CREATE TABLE IF NOT EXISTS coordinator_migrations(version bigint PRIMARY KEY); INSERT INTO coordinator_migrations VALUES({SCHEMA_VERSION}) ON CONFLICT DO NOTHING; CREATE TABLE IF NOT EXISTS coordinator_activations(activation_id uuid PRIMARY KEY,apply_order bigint UNIQUE NOT NULL,package_digest text NOT NULL,predecessor_package_digest text,database_id text NOT NULL,plan_kind text NOT NULL,applied_at timestamptz NOT NULL,operator_reference_hash text,backup_references text[] NOT NULL,role_mode text NOT NULL,runtime_role text NOT NULL)") + format!("CREATE TABLE IF NOT EXISTS coordinator_migrations(version bigint PRIMARY KEY); INSERT INTO coordinator_migrations VALUES({SCHEMA_VERSION}) ON CONFLICT DO NOTHING; CREATE TABLE IF NOT EXISTS coordinator_activations(activation_id uuid PRIMARY KEY,apply_order bigint UNIQUE NOT NULL,package_digest text NOT NULL,predecessor_package_digest text,database_id text NOT NULL,plan_kind text NOT NULL,applied_at timestamptz NOT NULL,operator_reference_hash text,backup_references text[] NOT NULL,role_mode text NOT NULL,runtime_role text NOT NULL,posture text NOT NULL CHECK(posture IN ('development','production'))); DO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='coordinator_activations' AND column_name='posture') THEN ALTER TABLE coordinator_activations ADD COLUMN posture text NOT NULL DEFAULT 'production' CHECK(posture IN ('development','production')); END IF; END $$") } fn layout() -> Result { @@ -624,7 +651,7 @@ pub async fn check( .suggest("restore database connectivity") })?; let l = layout()?; - let active = activation::check_active_package(&*client, &l, &d.database_id, digest) + let active = activation::check_active_package_without_posture(&*client, &l, &d.database_id, digest) .await .map_err(|_| { fail("run coordinatorctl plan/apply with the correct database identity and packages, then restart every service") @@ -957,15 +984,15 @@ pub async fn apply( "runtime role must not own the schema, migrate or write activation ledgers", )); } - let request = NewActivation { - activation_id: Uuid::new_v4(), - package_digest: workflows.digest(), - database_id: &d.database_id, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Split, - runtime_role: Some(&d.runtime_role), - }; + let request = NewActivation::without_posture( + Uuid::new_v4(), + workflows.digest(), + &d.database_id, + None, + &[], + RoleMode::Split, + Some(&d.runtime_role), + ); let active = activation::append_activation(&tx, &l, &request) .await .map_err(|_| fail("restore activation ledger"))?; @@ -1081,8 +1108,10 @@ mod tests { AuditDestination::File(FileDestination::new(root.path().join("audit.jsonl")).unwrap()) .for_process("apply") .unwrap(); - let first = AuditWriter::open(destination.clone()).await.unwrap(); - let error = match AuditWriter::open(destination.clone()).await { + let first = AuditWriter::open_without_posture(destination.clone()) + .await + .unwrap(); + let error = match AuditWriter::open_without_posture(destination.clone()).await { Ok(_) => panic!("a second writer must not acquire the same companion"), Err(error) => error, }; @@ -1093,7 +1122,9 @@ mod tests { Some("restore writable durable audit custody (sink-locked)") ); drop(first); - let reopened = AuditWriter::open(destination).await.unwrap(); + let reopened = AuditWriter::open_without_posture(destination) + .await + .unwrap(); drop(reopened); root.close().unwrap(); } diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index 965a82973d..249bb05c59 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_yaml::{Diagnostic, Report, Severity}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; /// A category, authored location and repair action, without run payload /// values. A restore refusal's operator message names the run id or package @@ -10,11 +11,18 @@ use std::path::{Path, PathBuf}; pub struct CoordinatorError { pub code: String, pub message: String, - pub file: Option>, + pub file: Option>, pub field: Option>, pub suggested_action: Option>, pub diagnostics: Box<[Diagnostic]>, pub exit_code: u8, + /// The check that refused a caller, set by the constructors of the + /// authentication, authorization and event-delivery refusals and read + /// where the refusal is answered. A fixed member, never a caller value. + pub check: Option, + /// What the deployment declared about a scope refusal, for the operator's + /// log line only: never a caller value, never written to an answer. + pub declared: Option>, } impl CoordinatorError { @@ -30,6 +38,8 @@ impl CoordinatorError { "service-unavailable" | "output-unavailable" | "definition.read" => 3, _ => 1, }, + check: None, + declared: None, } } /// Preserve all shared-reader findings and their authored positions. @@ -50,7 +60,7 @@ impl CoordinatorError { file: deciding .source .as_ref() - .map(|source| PathBuf::from(&source.file).into_boxed_path()), + .map(|source| Box::new(PathBuf::from(&source.file))), field: Some(deciding.path.clone().into_boxed_str()), suggested_action: Some(deciding.suggested_action.clone().into_boxed_str()), diagnostics: diagnostics.into(), @@ -62,8 +72,22 @@ impl CoordinatorError { } else { 1 }, + check: None, + declared: None, } } + /// Name the check that refused the caller. + #[must_use] + pub(crate) fn failing(mut self, check: FailedCheck) -> Self { + self.check = Some(check); + self + } + /// Attach the declared values of a scope refusal. + #[must_use] + pub(crate) fn declaring(mut self, declared: DeclaredScope) -> Self { + self.declared = Some(Box::new(declared)); + self + } pub(crate) fn with_exit(mut self, exit_code: u8) -> Self { self.exit_code = exit_code; self @@ -116,7 +140,7 @@ impl CoordinatorError { Report::new(vec![diagnostic]) } pub fn at(mut self, file: impl Into, field: impl Into) -> Self { - self.file = Some(file.into().into_boxed_path()); + self.file = Some(Box::new(file.into())); self.field = Some(field.into().into_boxed_str()); self } diff --git a/crates/registry-coordinator/src/event_trigger.rs b/crates/registry-coordinator/src/event_trigger.rs index 37bdb4586a..a4471cae12 100644 --- a/crates/registry-coordinator/src/event_trigger.rs +++ b/crates/registry-coordinator/src/event_trigger.rs @@ -2,30 +2,28 @@ //! Authenticated committed product events admitted into the ordinary Run machine. //! //! Products own event capture and disclosure. A reviewed trigger names one exact -//! source, event contract and typed mapping; deployment configuration supplies -//! only that source's authentication. Neither the event nor its signature grants -//! authority for a later product call. +//! source, event contract and typed mapping. Deployment configuration supplies +//! a distinct delivery key for each trigger URL. Authority for later product +//! calls comes from the receiving product. -use std::{ - collections::BTreeMap, - time::{Duration, SystemTime}, -}; +use std::{collections::BTreeMap, time::SystemTime}; use axum::{ body::Bytes, - extract::{OriginalUri, Path, State}, - http::{HeaderMap, HeaderValue, Method, StatusCode}, + extract::{Path, State}, + http::{HeaderMap, HeaderValue, StatusCode}, response::{IntoResponse, Response}, }; -use registry_platform_config::{sha256_uri, SecretProvidersConfig, SecretReference}; -use registry_platform_crypto::delivery_signature::{MAX_BODY_BYTES, MIN_HMAC_SHA256_KEY_BYTES}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_config::{ + sha256_uri, SecretProvidersConfig, SecretReference, SecretResolver, +}; +use registry_platform_crypto::delivery_signature::{ + DeliveryKey, DeliveryKeyError, DeliveryKeys, DeliverySignatureError, MAX_BODY_BYTES, +}; use registry_platform_dispatch::idempotency_key; -use registry_platform_hooks::{ - receiver::{ - verify_delivery as verify_signed_delivery, DeliveryFreshness, SignedDelivery, - VerifiedDelivery, - }, - EnvelopeLimits, HookEnvelope, +use registry_platform_hooks::receiver::{ + verify_hook_delivery, DeliveryFreshness, HookDelivery, HookDeliveryError, VerifiedHookDelivery, }; use registry_platform_yaml::{ExternalId, LocalId}; use serde::{Deserialize, Serialize}; @@ -38,13 +36,9 @@ use crate::{ CoordinatorError, Result, }; -/// The Version 1 signable bound, so every event a producer can sign can be -/// verified. The admitted event value is then held to the structured-value -/// profile. +/// Signed event bodies are bounded to 1 MiB. Admitted values also fit the +/// structured-value profile. pub const MAXIMUM_EVENT_BYTES: usize = MAX_BODY_BYTES; -/// Delivery time is refreshed by the producer for every attempt. Event commit -/// time is immutable and may be older after an outage or operator replay. -pub const DELIVERY_SKEW: Duration = Duration::from_secs(30); const EVENT_KEY_DOMAIN: &[u8] = b"registry-coordinator-event-start/v1"; const EVENT_OWNER_DOMAIN: &[u8] = b"registry-coordinator-event-owner/v1"; @@ -55,8 +49,157 @@ const EVENT_OWNER_DOMAIN: &[u8] = b"registry-coordinator-event-owner/v1"; pub struct EventSourceConfig { /// Exact absolute producer URI that signed event envelopes must declare. pub source: ExternalId, - /// Protected reference to the raw HMAC-SHA-256 key, at least 32 bytes. - pub signing_key_ref: SecretReference, + /// Workflow IDs and trigger names identify the keys for each event URL. + #[cfg_attr(feature = "schema", schemars(extend("maxProperties" = 16)))] + pub triggers: BTreeMap, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(transparent)] +pub struct WorkflowTriggerKeys( + #[cfg_attr(feature = "schema", schemars(extend("maxProperties" = 16)))] + pub BTreeMap, +); + +/// Standard Webhooks keys for one event trigger URL. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TriggerKeyConfig { + /// Reference to 32 to 64 exact key bytes shared only with this trigger's sender. + pub hmac_sha256_key_ref: SecretReference, + /// Optional previous key accepted during rotation. + #[serde( + default, + deserialize_with = "present_hook_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, +} + +pub(crate) fn present_hook_key_reference<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + SecretReference::deserialize(deserializer).map(Some) +} + +/// Resolved Standard Webhooks keys and the operator paths that identify them. +pub(crate) struct IngressKeys { + pub keys: DeliveryKeys, + path: String, + previous_path: String, +} + +pub(crate) type EventKeys = BTreeMap<(LocalId, LocalId), IngressKeys>; + +impl IngressKeys { + pub(crate) fn resolve( + resolver: &SecretResolver, + path: String, + current: &SecretReference, + previous: Option<&SecretReference>, + refuse: fn(&str, &str) -> CoordinatorError, + ) -> Result { + let current_path = format!("{path}.hmacSha256KeyRef"); + let previous_path = format!("{path}.previousHmacSha256KeyRef"); + let current = resolve_key(resolver, ¤t_path, current, refuse)?; + let previous = previous + .map(|reference| resolve_key(resolver, &previous_path, reference, refuse)) + .transpose()?; + let keys = DeliveryKeys::new(current, previous).map_err(|_| { + refuse( + &previous_path, + &format!("{previous_path} holds the same bytes as {current_path}. To rotate, write 32 new random bytes to the secret {current_path} references and keep the old bytes behind {previous_path}."), + ) + })?; + Ok(Self { + keys, + path: current_path, + previous_path, + }) + } + + pub(crate) fn labelled(&self) -> impl Iterator { + std::iter::once((self.path.as_str(), self.keys.current())).chain( + self.keys + .previous() + .map(|key| (self.previous_path.as_str(), key)), + ) + } +} + +fn resolve_key( + resolver: &SecretResolver, + path: &str, + reference: &SecretReference, + refuse: fn(&str, &str) -> CoordinatorError, +) -> Result { + let secret = resolver + .resolve_binary_reference(reference) + .map_err(|error| { + refuse( + path, + &format!( + "{path} could not be resolved: {error}. {}", + error.suggested_action() + ), + ) + })?; + let bytes = secret.expose_secret(); + let length = bytes.len(); + let trailing_newline = bytes.ends_with(b"\n"); + DeliveryKey::new(bytes) + .map_err(|error| refuse(path, &key_diagnostic(path, length, trailing_newline, error))) +} + +fn key_diagnostic( + path: &str, + length: usize, + trailing_newline: bool, + error: DeliveryKeyError, +) -> String { + let suffix = if trailing_newline { + ", ending in a newline" + } else { + "" + }; + let reason = match error { + DeliveryKeyError::TooShort { .. } | DeliveryKeyError::TooLong { .. } => { + "Supply 32 to 64 exact key bytes." + } + DeliveryKeyError::SecretText => "Supply exact key bytes without the whsec_ encoding.", + DeliveryKeyError::PreviousEqualsCurrent => "Use distinct current and previous keys.", + }; + format!("{path} resolved to {length} bytes{suffix}. {reason}") +} + +pub(crate) fn duplicate_key(first: &str, second: &str) -> CoordinatorError { + CoordinatorError::new( + "adapter.configuration", + format!("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there."), + ) +} + +pub(crate) fn check_key_references( + errors: &mut Vec, + secrets: &SecretProvidersConfig, + path: &str, + current: &SecretReference, + previous: Option<&SecretReference>, +) { + for (name, reference) in std::iter::once(("hmacSha256KeyRef", current)) + .chain(previous.map(|reference| ("previousHmacSha256KeyRef", reference))) + { + let field = format!("{path}.{name}"); + if secrets.check_reference(&field, reference.as_str()).is_err() { + errors.push(configuration( + &field, + "Enable the secretProviders entry named by the delivery key reference.", + )); + } + } } /// Resolved governed trigger. The package revision covers every member, the @@ -112,37 +255,69 @@ pub(crate) fn source_findings( { errors.push(configuration(&format!("{field}.source"), "Bind each exact absolute event source URI once, without credentials, whitespace or fragment.")); } - if secrets - .check_reference( - &format!("{field}.signingKeyRef"), - source.signing_key_ref.as_str(), - ) - .is_err() - { + if source.triggers.len() > 16 { errors.push(configuration( - &format!("{field}.signingKeyRef"), - "Enable the secret provider named by the event signing key reference.", + &format!("{field}.triggers"), + "Declare keys for at most sixteen workflows per source.", )); } + for (workflow, triggers) in &source.triggers { + let workflow_path = format!("{field}.triggers.{workflow}"); + if triggers.0.len() > 16 { + errors.push(configuration( + &workflow_path, + "Declare at most sixteen trigger keys per workflow.", + )); + } + for (trigger, key) in &triggers.0 { + check_key_references( + &mut errors, + secrets, + &format!("{workflow_path}.{trigger}"), + &key.hmac_sha256_key_ref, + key.previous_hmac_sha256_key_ref.as_ref(), + ); + } + } } errors } -/// Startup readiness checks the same secret references the receiver consumes. -pub(crate) fn check_keys(config: &crate::runtime::RuntimeConfig) -> Result<()> { - let resolver = config - .secret_providers - .resolver() - .map_err(|_| source_unavailable())?; - for source in config.event_sources.values() { - let key = resolver - .resolve_reference(&source.signing_key_ref) - .map_err(|_| source_unavailable())?; - if key.len() < MIN_HMAC_SHA256_KEY_BYTES { - return Err(source_unavailable()); +pub(crate) fn resolve_keys(config: &crate::runtime::RuntimeConfig) -> Result { + let mut keys = BTreeMap::new(); + if config.event_sources.is_empty() { + return Ok(keys); + } + let resolver = config.secret_providers.resolver().map_err(|_| { + configuration( + "eventSources", + "Make the event source secret providers available.", + ) + })?; + for (alias, source) in &config.event_sources { + for (workflow, triggers) in &source.triggers { + for (trigger, key) in &triggers.0 { + let path = format!("eventSources.{alias}.triggers.{workflow}.{trigger}"); + let keys_for_trigger = IngressKeys::resolve( + &resolver, + path.clone(), + &key.hmac_sha256_key_ref, + key.previous_hmac_sha256_key_ref.as_ref(), + configuration, + )?; + if keys + .insert((workflow.clone(), trigger.clone()), keys_for_trigger) + .is_some() + { + return Err(configuration( + &path, + "Configure only one source for this workflow trigger.", + )); + } + } } } - Ok(()) + Ok(keys) } /// Reuse the ordinary mapping validator with a single synthetic finish whose @@ -245,79 +420,45 @@ pub struct VerifiedEvent { pub actor: Actor, } -#[expect( - clippy::too_many_arguments, - reason = "The verifier binds exact received wire fields, configured producer, subscription, and receiver clock" -)] pub fn verify_delivery( source: &EventSourceConfig, - source_name: &str, trigger: &EventTrigger, trigger_name: &str, - method: &Method, - request_target: &str, headers: &HeaderMap, body: &[u8], - key: &[u8], + keys: &DeliveryKeys, now: SystemTime, ) -> Result { - if body.len() > MAXIMUM_EVENT_BYTES { - return Err(body_too_large()); - } - if body.is_empty() || method != Method::POST { - return Err(invalid_event()); - } - let VerifiedDelivery { - id, - source: event_source, - event_type, - time, - data_schema, - content_type, - idempotency_key: delivery_key, - .. - } = verify_signed_delivery( - SignedDelivery { - method: method.as_str(), - request_target, + check_body(body)?; + let VerifiedHookDelivery { id, envelope, .. } = verify_hook_delivery( + HookDelivery { headers: headers .iter() .map(|(name, value)| (name.as_str(), value.as_bytes())), body, - key, - }, - DeliveryFreshness::Within { - now, - skew: DELIVERY_SKEW, + keys, }, + DeliveryFreshness::default_at(now), ) - .map_err(|_| unauthenticated())?; - if content_type != "application/json" - || event_source != source.source.as_ref() - || trigger.source != source_name - || event_type != trigger.event_type - || data_schema != trigger.data_schema - || delivery_key.is_empty() - || delivery_key.len() > 256 + .map_err(|error| match error { + HookDeliveryError::InvalidEnvelope => invalid_event(), + HookDeliveryError::IdMismatch | HookDeliveryError::InvalidContentType => { + unauthenticated(FailedCheck::DeliveryBinding) + } + HookDeliveryError::Signature( + DeliverySignatureError::StaleDelivery | DeliverySignatureError::InvalidTimestamp, + ) => unauthenticated(FailedCheck::DeliveryFreshness), + HookDeliveryError::Signature(DeliverySignatureError::BodyTooLarge) => body_too_large(), + _ => unauthenticated(FailedCheck::DeliverySignature), + })?; + if envelope.source != source.source.as_ref() + || envelope.event_type != trigger.event_type + || envelope.dataschema != trigger.data_schema { - return Err(unauthenticated()); + return Err(unauthenticated(FailedCheck::DeliveryBinding)); } - let envelope = HookEnvelope::from_canonical_bytes( - body, - &EnvelopeLimits::tightened_to(MAXIMUM_EVENT_BYTES), - ) - .map_err(|_| invalid_event())?; + let event_source = envelope.source.as_str(); let value = serde_json::to_value(&envelope).map_err(|_| invalid_event())?; - if envelope.id != id - || envelope.source != event_source - || envelope.event_type != event_type - || envelope.dataschema != data_schema - || value["time"].as_str() != Some(time) - { - return Err(invalid_event()); - } - // Signed deliveries may reach the signable bound, but an admitted event - // is a workflow value, so it must also fit the structured-value profile. crate::functions::check_value(&value).map_err(|error| { if error.code == "function.value_limit" { event_too_large() @@ -356,8 +497,6 @@ pub fn verify_delivery( pub async fn receive( State(state): State, Path((workflow_name, trigger_name)): Path<(String, String)>, - OriginalUri(uri): OriginalUri, - method: Method, headers: HeaderMap, body: Bytes, ) -> Response { @@ -368,39 +507,33 @@ pub async fn receive( "event admissions are disabled during recovery", )); } + check_body(&body)?; let package = state .workflows .get(&workflow_name) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; let trigger = package .definition .workflow .event_triggers .get(&trigger_name) - .ok_or_else(unauthenticated)?; + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; let source = state .runtime .event_sources .get(&trigger.source) - .ok_or_else(source_unavailable)?; - let resolver = state - .runtime - .secret_providers - .resolver() - .map_err(|_| source_unavailable())?; - let key = resolver - .resolve_reference(&source.signing_key_ref) - .map_err(|_| source_unavailable())?; + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; + let keys = state + .adapters + .event_keys(&workflow_name, &trigger_name) + .ok_or_else(|| unauthenticated(FailedCheck::DeliveryBinding))?; let verified = verify_delivery( source, - &trigger.source, trigger, &trigger_name, - &method, - &uri.to_string(), &headers, &body, - key.expose_secret(), + keys, SystemTime::now(), )?; crate::deployment::check(&state.store, &state.runtime, state.workflows.digest()).await?; @@ -441,7 +574,7 @@ fn event_problem(error: CoordinatorError) -> Response { if signature_refused { response.headers_mut().insert( axum::http::header::WWW_AUTHENTICATE, - HeaderValue::from_static("Registry-Signature version=\"v1\""), + HeaderValue::from_static(crate::http::WEBHOOK_CHALLENGE), ); } response @@ -471,21 +604,25 @@ fn body_too_large() -> CoordinatorError { CoordinatorError::new( "request.body-too-large", format!( - "the signed event delivery exceeds the {MAXIMUM_EVENT_BYTES}-byte Version 1 signable bound; send a smaller event" + "the signed event delivery exceeds the {MAXIMUM_EVENT_BYTES}-byte body bound; send a smaller event" ), ) } -fn unauthenticated() -> CoordinatorError { +fn unauthenticated(check: FailedCheck) -> CoordinatorError { CoordinatorError::new( "event-unauthenticated", "a fresh signed delivery from the configured event source is required", ) + .failing(check) } -fn source_unavailable() -> CoordinatorError { - CoordinatorError::new( - "event-source-unavailable", - "the configured event source authentication is unavailable", - ) +fn check_body(body: &[u8]) -> Result<()> { + if body.len() > MAXIMUM_EVENT_BYTES { + return Err(body_too_large()); + } + if body.is_empty() { + return Err(invalid_event()); + } + Ok(()) } fn configuration(field: &str, advice: &str) -> CoordinatorError { CoordinatorError::new( diff --git a/crates/registry-coordinator/src/event_trigger_tests.rs b/crates/registry-coordinator/src/event_trigger_tests.rs index 97a92da81a..b2c188c15d 100644 --- a/crates/registry-coordinator/src/event_trigger_tests.rs +++ b/crates/registry-coordinator/src/event_trigger_tests.rs @@ -1,20 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 use super::*; +use registry_platform_authcommon::RefusalNote; use registry_platform_canonical_json::canonicalize_json; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; +use registry_platform_crypto::delivery_signature::sign; use serde_json::json; +use std::time::{Duration, UNIX_EPOCH}; use uuid::Uuid; const KEY: &[u8] = &[0x5a; 32]; const BREG_SOURCE: &str = "urn:registrystack:registry:synthetic:instance:local"; const EVENT_TYPE: &str = "contact-created-v1"; const DATA_SCHEMA: &str = "urn:example:contact-created:v1"; -const TARGET: &str = "/v1/events/record-follow-up/record-saved"; fn source() -> EventSourceConfig { EventSourceConfig { source: ExternalId::new(BREG_SOURCE).unwrap(), - signing_key_ref: SecretReference::parse("secret:file/event-key").unwrap(), + triggers: BTreeMap::new(), } } fn trigger() -> EventTrigger { @@ -44,88 +45,69 @@ fn event() -> Value { "causation":{"root":id,"hop":0} }) } -fn signed( - value: &Value, - target: &str, - generation: u32, - delivery_key: &str, -) -> (Vec, HeaderMap) { +fn keys(current: &[u8], previous: Option<&[u8]>) -> DeliveryKeys { + DeliveryKeys::new( + DeliveryKey::new(current).unwrap(), + previous.map(|key| DeliveryKey::new(key).unwrap()), + ) + .unwrap() +} + +fn signed(value: &Value) -> (Vec, HeaderMap) { let body = canonicalize_json(value).unwrap(); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let headers = signed_headers( + &keys(KEY, None), + value["id"].as_str().unwrap(), + timestamp, + &body, + ); + (body, headers) +} + +fn signed_headers(keys: &DeliveryKeys, id: &str, timestamp: u64, body: &[u8]) -> HeaderMap { + let signature = sign(keys, id, timestamp, body).unwrap(); let mut headers = HeaderMap::new(); - for (name, text) in [ - ("content-type", "application/json".to_owned()), - ("ce-specversion", "1.0".to_owned()), - ("ce-id", value["id"].as_str().unwrap().to_owned()), - ("ce-source", value["source"].as_str().unwrap().to_owned()), - ("ce-type", value["type"].as_str().unwrap().to_owned()), - ("ce-time", value["time"].as_str().unwrap().to_owned()), - ( - "ce-dataschema", - value["dataschema"].as_str().unwrap().to_owned(), - ), - ("x-registry-event-generation", generation.to_string()), - ("x-registry-delivery-attempt", "1".to_owned()), - ( - "x-registry-delivery-time", - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - ), - ("idempotency-key", delivery_key.to_owned()), + for (name, value) in [ + ("content-type", "application/json"), + ("webhook-id", id), + ("webhook-timestamp", ×tamp.to_string()), + ("webhook-signature", &signature), ] { - headers.insert(name, HeaderValue::from_str(&text).unwrap()); + headers.insert(name, HeaderValue::from_str(value).unwrap()); } - sign_headers(&mut headers, &body, target); - (body, headers) -} -fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { - headers.get(name).and_then(|value| value.to_str().ok()) -} -fn sign_headers(headers: &mut HeaderMap, body: &[u8], target: &str) { - let signature = sign_v1( - KEY, - SignatureFields { - id: header(headers, "ce-id").unwrap(), - source: header(headers, "ce-source").unwrap(), - event_type: header(headers, "ce-type").unwrap(), - time: header(headers, "ce-time").unwrap(), - data_schema: header(headers, "ce-dataschema").unwrap(), - generation: header(headers, "x-registry-event-generation").unwrap(), - attempt: header(headers, "x-registry-delivery-attempt").unwrap(), - delivery_time: header(headers, "x-registry-delivery-time").unwrap(), - method: "POST", - request_target: target, - content_type: "application/json", - idempotency_key: header(headers, "idempotency-key").unwrap(), - body, - }, - ) - .unwrap(); - headers.insert( - "x-registry-signature", - HeaderValue::from_str(&signature).unwrap(), - ); + headers } + fn verify(body: &[u8], headers: &HeaderMap) -> Result { verify_delivery( &source(), - "registry", &trigger(), "record-saved", - &Method::POST, - TARGET, headers, body, - KEY, + &keys(KEY, None), SystemTime::now(), ) } +#[test] +fn an_event_signed_with_its_trigger_key_is_admitted() { + let value = event(); + let (body, headers) = signed(&value); + assert_eq!(verify(&body, &headers).unwrap().value, value); +} + #[test] fn event_authentication_challenges_the_signature_transport() { - let response = event_problem(unauthenticated()); + let response = event_problem(unauthenticated(FailedCheck::DeliverySignature)); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); assert_eq!( response.headers()[axum::http::header::WWW_AUTHENTICATE], - "Registry-Signature version=\"v1\"" + "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" ); let bearer = crate::http::problem(CoordinatorError::new("access.unauthenticated", "synthetic")); assert_eq!( @@ -137,16 +119,16 @@ fn event_authentication_challenges_the_signature_transport() { #[test] fn exact_event_identity_survives_retry_replay_and_old_commit_time() { let value = event(); - let (body, headers) = signed(&value, TARGET, 1, "first-delivery"); + let (body, headers) = signed(&value); let first = verify(&body, &headers).unwrap(); - let (replay_body, replay_headers) = signed(&value, TARGET, 2, "operator-replay"); + let (replay_body, replay_headers) = signed(&value); let replay = verify(&replay_body, &replay_headers).unwrap(); assert_eq!(first.key, replay.key); assert_eq!(first.digest, replay.digest); let mut alias = value.clone(); alias["id"] = json!(value["id"].as_str().unwrap().to_ascii_uppercase()); alias["causation"]["root"] = alias["id"].clone(); - let (alias_body, alias_headers) = signed(&alias, TARGET, 1, "uuid-spelling-alias"); + let (alias_body, alias_headers) = signed(&alias); let alias = verify(&alias_body, &alias_headers).unwrap(); assert_eq!( first.key, alias.key, @@ -159,7 +141,7 @@ fn exact_event_identity_survives_retry_replay_and_old_commit_time() { assert!(!first.actor.operator); let mut changed = value; changed["data"]["values"]["name"] = json!("Changed ignored projection"); - let (body, headers) = signed(&changed, TARGET, 1, "other-delivery"); + let (body, headers) = signed(&changed); let changed = verify(&body, &headers).unwrap(); assert_eq!(changed.key, first.key); assert_ne!( @@ -171,20 +153,17 @@ fn exact_event_identity_survives_retry_replay_and_old_commit_time() { #[test] fn event_ownership_follows_the_authenticated_producer_across_source_aliases() { let value = event(); - let (body, headers) = signed(&value, TARGET, 1, "first-delivery"); + let (body, headers) = signed(&value); let first = verify(&body, &headers).unwrap(); let mut renamed = trigger(); renamed.source = "renamed-registry".into(); let replay = verify_delivery( &source(), - &renamed.source, &renamed, "record-saved", - &Method::POST, - TARGET, &headers, &body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap(); @@ -194,38 +173,18 @@ fn event_ownership_follows_the_authenticated_producer_across_source_aliases() { assert_eq!(first.actor.client_id, replay.actor.client_id); assert!(!replay.actor.operator); - assert!( - verify_delivery( - &source(), - "registry", - &renamed, - "record-saved", - &Method::POST, - TARGET, - &headers, - &body, - KEY, - SystemTime::now(), - ) - .is_err(), - "the trigger must still select the configured source alias" - ); - let mut other = value; other["source"] = json!("urn:example:another-authenticated-producer"); let mut other_source = source(); other_source.source = ExternalId::new(other["source"].as_str().unwrap()).unwrap(); - let (body, headers) = signed(&other, TARGET, 1, "other-producer"); + let (body, headers) = signed(&other); let other = verify_delivery( &other_source, - "registry", &trigger(), "record-saved", - &Method::POST, - TARGET, &headers, &body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap(); @@ -253,17 +212,14 @@ fn a_conforming_alternate_product_uses_the_same_verifier() { trigger.source = "appointments".into(); trigger.event_type = value["type"].as_str().unwrap().into(); trigger.data_schema = value["dataschema"].as_str().unwrap().into(); - let (body, headers) = signed(&value, TARGET, 1, "scheduling-delivery"); + let (body, headers) = signed(&value); let verified = verify_delivery( &source, - "appointments", &trigger, "appointment-saved", - &Method::POST, - TARGET, &headers, &body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap(); @@ -271,85 +227,164 @@ fn a_conforming_alternate_product_uses_the_same_verifier() { } #[test] -fn substituted_signature_destination_source_and_contract_are_refused() { +fn a_delivery_for_another_trigger_is_refused_by_that_triggers_key() { + let (body, headers) = signed(&event()); + let error = verify_delivery( + &source(), + &trigger(), + "other-trigger", + &headers, + &body, + &keys(&[0x78; 32], None), + SystemTime::now(), + ) + .err() + .unwrap(); + assert_eq!(error.check, Some(FailedCheck::DeliverySignature)); +} + +#[test] +fn a_webhook_id_that_differs_from_the_envelope_id_is_refused() { + let (body, _) = signed(&event()); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let headers = signed_headers( + &keys(KEY, None), + &Uuid::new_v4().to_string(), + timestamp, + &body, + ); + assert_eq!( + verify(&body, &headers).err().unwrap().check, + Some(FailedCheck::DeliveryBinding) + ); +} + +#[test] +fn the_event_window_is_300_seconds_in_both_directions() { + let timestamp = 1_800_000_000_u64; + let now = UNIX_EPOCH + Duration::from_secs(timestamp); let value = event(); - let (body, original) = signed(&value, TARGET, 1, "delivery"); - for (name, replacement) in [ + let body = canonicalize_json(&value).unwrap(); + let keys = keys(KEY, None); + for delta in [-301, -300, 300, 301] { + let headers = signed_headers( + &keys, + value["id"].as_str().unwrap(), + timestamp.checked_add_signed(delta).unwrap(), + &body, + ); + let result = verify_delivery( + &source(), + &trigger(), + "record-saved", + &headers, + &body, + &keys, + now, + ); + if delta.abs() == 301 { + assert_eq!( + result.err().unwrap().check, + Some(FailedCheck::DeliveryFreshness) + ); + } else { + result.unwrap(); + } + } +} + +#[test] +fn a_refused_delivery_names_the_check_that_failed() { + let value = event(); + let (body, original) = signed(&value); + let refusal = |headers: &HeaderMap| verify(&body, headers).err().expect("refused"); + for (name, replacement, check) in [ ( - "x-registry-signature", - "v1=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "webhook-signature", + "v1,invalid", + FailedCheck::DeliverySignature, + ), + ("webhook-timestamp", "01", FailedCheck::DeliveryFreshness), + ( + "content-type", + "application/json; charset=utf-8", + FailedCheck::DeliveryBinding, ), - ("ce-source", "urn:example:another-source"), - ("ce-type", "another-event-v1"), - ("ce-dataschema", "urn:example:another-schema"), - ("ce-specversion", "0.3"), - ("x-registry-event-generation", "0"), - ("x-registry-delivery-attempt", "-1"), ] { let mut headers = original.clone(); headers.insert(name, HeaderValue::from_static(replacement)); - assert!(verify(&body, &headers).is_err(), "{name}"); + let error = refusal(&headers); + assert_eq!(error.code, "event-unauthenticated", "{name}"); + assert_eq!(error.check, Some(check), "{name}"); + } + for name in ["webhook-id", "webhook-timestamp", "webhook-signature"] { + let mut duplicate = original.clone(); + duplicate.append(name, original[name].clone()); + let mut missing = original.clone(); + missing.remove(name); + for headers in [missing, duplicate] { + assert_eq!( + refusal(&headers).check, + Some(FailedCheck::DeliverySignature), + "{name}" + ); + } + } + for (name, replacement) in [ + ("source", "urn:example:another-source"), + ("type", "another-event-v1"), + ("dataschema", "urn:example:another-schema"), + ] { + let mut other = value.clone(); + other[name] = json!(replacement); + let (body, headers) = signed(&other); + assert_eq!( + verify(&body, &headers).err().unwrap().check, + Some(FailedCheck::DeliveryBinding), + "{name}" + ); } - assert!(verify_delivery( - &source(), - "registry", - &trigger(), - "record-saved", - &Method::POST, - "/different-target", - &original, - &body, - KEY, - SystemTime::now() - ) - .is_err()); - assert!(verify_delivery( - &source(), - "registry", - &trigger(), - "record-saved", - &Method::PUT, - TARGET, - &original, - &body, - KEY, - SystemTime::now() - ) - .is_err()); - let mut duplicate = original; - duplicate.append("ce-source", HeaderValue::from_static(BREG_SOURCE)); - assert!( - verify(&body, &duplicate).is_err(), - "ambiguous signed headers are refused" - ); } #[test] -fn stale_delivery_noncanonical_body_and_header_body_disagreement_are_refused() { +fn an_event_refusal_carries_its_check_in_the_response_extensions() { + for check in [ + FailedCheck::DeliverySignature, + FailedCheck::DeliveryFreshness, + FailedCheck::DeliveryBinding, + ] { + let response = event_problem(unauthenticated(check)); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + response.extensions().get::().map(|n| n.check), + Some(check) + ); + } +} + +#[test] +fn an_authentic_noncanonical_body_is_refused() { let value = event(); - let (body, mut headers) = signed(&value, TARGET, 1, "delivery"); - headers.insert( - "x-registry-delivery-time", - HeaderValue::from_static("2020-01-01T00:00:00Z"), + let (mut body, _) = signed(&value); + body.push(b' '); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let headers = signed_headers( + &keys(KEY, None), + value["id"].as_str().unwrap(), + timestamp, + &body, ); - sign_headers(&mut headers, &body, TARGET); - assert!(verify(&body, &headers).is_err()); - let (_, mut headers) = signed(&value, TARGET, 1, "delivery"); - let mut spaced = body.clone(); - spaced.push(b' '); - sign_headers(&mut headers, &spaced, TARGET); - assert!(verify(&spaced, &headers).is_err()); - let mut changed = value.clone(); - changed["id"] = json!(Uuid::new_v4().to_string()); - changed["causation"]["root"] = changed["id"].clone(); - let changed = canonicalize_json(&changed).unwrap(); - sign_headers(&mut headers, &changed, TARGET); - assert!(verify(&changed, &headers).is_err()); - assert!(verify(&vec![b' '; MAXIMUM_EVENT_BYTES + 1], &headers).is_err()); + assert_eq!(verify(&body, &headers).err().unwrap().code, "event-invalid"); } #[test] -fn the_intake_bound_is_the_signable_bound_and_its_refusal_names_the_limit() { +fn the_intake_bound_is_one_mib_and_its_refusal_names_the_limit() { assert_eq!( MAXIMUM_EVENT_BYTES, registry_platform_crypto::delivery_signature::MAX_BODY_BYTES @@ -360,7 +395,7 @@ fn the_intake_bound_is_the_signable_bound_and_its_refusal_names_the_limit() { for index in 0..6 { value["data"]["values"][format!("field{index}")] = json!("x".repeat(15_000)); } - let (body, headers) = signed(&value, TARGET, 1, "large-delivery"); + let (body, headers) = signed(&value); assert!(body.len() > 65_536); verify(&body, &headers).unwrap(); let error = verify(&vec![b' '; MAXIMUM_EVENT_BYTES + 1], &headers) @@ -372,12 +407,12 @@ fn the_intake_bound_is_the_signable_bound_and_its_refusal_names_the_limit() { #[test] fn a_signed_event_over_the_value_profile_is_refused_naming_the_bound_and_fix() { - // Within the signable bound, but over the 131,072-byte event value profile. + // The body fits the intake bound and exceeds the 131,072-byte value profile. let mut value = event(); for index in 0..20 { value["data"]["values"][format!("field{index}")] = json!("x".repeat(15_000)); } - let (body, headers) = signed(&value, TARGET, 1, "oversized-value"); + let (body, headers) = signed(&value); assert!(body.len() > crate::functions::MAXIMUM_VALUE_BYTES); assert!(body.len() <= MAXIMUM_EVENT_BYTES); let error = verify(&body, &headers).err().unwrap(); @@ -418,30 +453,6 @@ fn a_signed_event_over_the_value_profile_is_refused_naming_the_bound_and_fix() { ); } -#[test] -fn delivery_counters_follow_the_shared_receiver_grammar() { - let value = event(); - for (counter, accepted) in [ - ("1", true), - ("4294967296", true), - ("9223372036854775807", true), - ("01", false), - ("0", false), - ("9223372036854775808", false), - ] { - for name in ["x-registry-event-generation", "x-registry-delivery-attempt"] { - let (body, mut headers) = signed(&value, TARGET, 1, "delivery"); - headers.insert(name, HeaderValue::from_static(counter)); - sign_headers(&mut headers, &body, TARGET); - assert_eq!( - verify(&body, &headers).is_ok(), - accepted, - "{name}={counter}" - ); - } - } -} - fn project_text() -> &'static str { r#" apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 @@ -696,7 +707,7 @@ mod postgres { "secretProviders":{"environment":{},"file":{"root":"/private/tmp"}}, "database":{"runtimeUrlRef":"secret:env/COORDINATOR_TEST_DATABASE_URL","migrationUrlRef":"secret:env/COORDINATOR_TEST_DATABASE_URL"}, "namespace":namespace, - "eventSources":{"registry":{"source":BREG_SOURCE,"signingKeyRef":"secret:file/event-key"}}, + "eventSources":{"registry":{"source":BREG_SOURCE,"triggers":{"record-follow-up":{"record-saved":{"hmacSha256KeyRef":"secret:file/event-key"}}}}}, "connections":{"source":{"type":"breg","baseUrl":"http://127.0.0.1:9999","profile":"synthetic-reader", "authorization":{"tokenEndpoint":"http://127.0.0.1:9998/token","clientId":"synthetic-client", "clientAssertionAudience":"http://127.0.0.1:9998", @@ -754,7 +765,7 @@ mod postgres { runtime.validate_workflow(&historical.workflow).unwrap(); let original_binding = runtime.binding_digest_for(&historical.workflow).unwrap(); let value = event(); - let (body, headers) = signed(&value, TARGET, 1, "before-ingress-revocation"); + let (body, headers) = signed(&value); let verified = verify(&body, &headers).unwrap(); let actor = verified.actor.clone(); let run = admit(&store, &historical, &runtime, verified) @@ -815,7 +826,7 @@ mod postgres { let original = definition(project_text()); runtime.validate_workflow(&original.workflow).unwrap(); let value = event(); - let (body, headers) = signed(&value, TARGET, 1, "before-alias-rename"); + let (body, headers) = signed(&value); let run = admit( &store, &original, @@ -842,19 +853,16 @@ mod postgres { assert_ne!(original.digest, renamed.digest); let store = Store::connect(&database, &namespace).await.unwrap(); store.check_runtime_bindings(&runtime).await.unwrap(); - let (body, headers) = signed(&value, TARGET, 2, "after-alias-rename"); + let (body, headers) = signed(&value); let trigger = &renamed.workflow.event_triggers["record-saved"]; let verify_renamed = || { verify_delivery( &runtime.event_sources[&trigger.source], - &trigger.source, trigger, "record-saved", - &Method::POST, - TARGET, &headers, &body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap() @@ -881,17 +889,14 @@ mod postgres { ); let mut conflict = value.clone(); conflict["data"]["values"]["name"] = json!("Changed ignored projection"); - let (conflict_body, conflict_headers) = signed(&conflict, TARGET, 3, "renamed-conflict"); + let (conflict_body, conflict_headers) = signed(&conflict); let conflict = verify_delivery( &runtime.event_sources[&trigger.source], - &trigger.source, trigger, "record-saved", - &Method::POST, - TARGET, &conflict_headers, &conflict_body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap(); @@ -907,17 +912,14 @@ mod postgres { other["source"] = json!("urn:example:another-authenticated-producer"); let mut other_source = runtime.event_sources[&trigger.source].clone(); other_source.source = ExternalId::new(other["source"].as_str().unwrap()).unwrap(); - let (other_body, other_headers) = signed(&other, TARGET, 1, "other-producer"); + let (other_body, other_headers) = signed(&other); let other = verify_delivery( &other_source, - &trigger.source, trigger, "record-saved", - &Method::POST, - TARGET, &other_headers, &other_body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap(); @@ -970,6 +972,90 @@ mod postgres { .unwrap(); } + async fn assert_one_run_for_deliveries(stages: &[(&DeliveryKeys, &[&DeliveryKeys])]) { + let database = std::env::var("COORDINATOR_TEST_DATABASE_URL") + .expect("a disposable real PostgreSQL database is required"); + let namespace = format!("coordinator_{}", Uuid::new_v4().simple()); + let store = Store::connect(&database, &namespace).await.unwrap(); + store.migrate().await.unwrap(); + let runtime = runtime(&namespace); + let definition = definition(project_text()); + let value = event(); + let body = canonicalize_json(&value).unwrap(); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut prior = None; + for (receiver, senders) in stages { + for sender in *senders { + let headers = + signed_headers(sender, value["id"].as_str().unwrap(), timestamp, &body); + let verified = verify_delivery( + &source(), + &trigger(), + "record-saved", + &headers, + &body, + receiver, + SystemTime::now(), + ) + .unwrap(); + let run = admit(&store, &definition, &runtime, verified) + .await + .unwrap(); + assert_eq!(*prior.get_or_insert(run), run); + } + } + if stages.len() > 1 { + let receiver = stages.last().unwrap().0; + let retired = stages.first().unwrap().0; + let headers = signed_headers(retired, value["id"].as_str().unwrap(), timestamp, &body); + let error = verify_delivery( + &source(), + &trigger(), + "record-saved", + &headers, + &body, + receiver, + SystemTime::now(), + ) + .err() + .expect("the retired key must be refused"); + assert_eq!(error.check, Some(FailedCheck::DeliverySignature)); + } + assert_eq!(store.list_runs(100).await.unwrap().len(), 1); + let (client, connection) = tokio_postgres::connect(&database, tokio_postgres::NoTls) + .await + .unwrap(); + tokio::spawn(async move { + connection.await.unwrap(); + }); + client + .batch_execute(&format!("DROP SCHEMA {namespace} CASCADE")) + .await + .unwrap(); + } + + #[tokio::test] + async fn a_repeated_webhook_id_admits_one_run() { + let initial = keys(KEY, None); + assert_one_run_for_deliveries(&[(&initial, &[&initial, &initial])]).await; + } + + #[tokio::test] + async fn an_event_from_a_rotating_source_is_admitted_once_through_all_three_steps() { + let initial = keys(KEY, None); + let overlap = keys(&[0x71; 32], Some(KEY)); + let rotated = keys(&[0x71; 32], None); + assert_one_run_for_deliveries(&[ + (&initial, &[&initial]), + (&overlap, &[&initial, &overlap]), + (&rotated, &[&rotated]), + ]) + .await; + } + #[tokio::test] async fn event_admission_is_atomic_deduplicated_and_recovers_after_restart_and_activation() { let database = std::env::var("COORDINATOR_TEST_DATABASE_URL") @@ -980,7 +1066,7 @@ mod postgres { let runtime = runtime(&namespace); let first = definition(project_text()); let value = event(); - let (body, headers) = signed(&value, TARGET, 1, "first-delivery"); + let (body, headers) = signed(&value); let (run, duplicate) = tokio::join!( admit(&store, &first, &runtime, verify(&body, &headers).unwrap()), admit(&store, &first, &runtime, verify(&body, &headers).unwrap()) @@ -994,7 +1080,7 @@ mod postgres { assert_eq!(store.list_runs(100).await.unwrap().len(), 1); drop(store); let reopened = Store::connect(&database, &namespace).await.unwrap(); - let (body, headers) = signed(&value, TARGET, 2, "operator-replay-after-restart"); + let (body, headers) = signed(&value); let replay = admit( &reopened, &first, @@ -1023,7 +1109,7 @@ mod postgres { ); let mut conflict = value.clone(); conflict["data"]["values"]["name"] = json!("Changed ignored projection"); - let (body, headers) = signed(&conflict, TARGET, 2, "conflicting-generation"); + let (body, headers) = signed(&conflict); let refused = admit( &reopened, &first, @@ -1035,7 +1121,7 @@ mod postgres { assert_eq!(refused.code, "start-conflict"); let mut invalid = event(); invalid["data"]["recordId"] = json!("synthetic-invalid-input"); - let (body, headers) = signed(&invalid, TARGET, 1, "invalid-new-event"); + let (body, headers) = signed(&invalid); assert!(admit( &reopened, &first, @@ -1064,7 +1150,7 @@ mod postgres { ); client.batch_execute(&format!("CREATE FUNCTION {namespace}.reject_event_job() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'synthetic job insertion failure'; END $$; CREATE TRIGGER reject_event_job BEFORE INSERT ON {namespace}.jobs FOR EACH ROW EXECUTE FUNCTION {namespace}.reject_event_job();")).await.unwrap(); let later = event(); - let (body, headers) = signed(&later, TARGET, 1, "rolled-back-new-event"); + let (body, headers) = signed(&later); assert!(admit( &reopened, &first, @@ -1234,17 +1320,14 @@ mod postgres { let definition = proposal_hold_definition(); let trigger = &definition.workflow.event_triggers["record-saved"]; let verify = |value: &Value| { - let (body, headers) = signed(value, TARGET, 1, "proposal-delivery"); + let (body, headers) = signed(value); verify_delivery( &source(), - "registry", trigger, "record-saved", - &Method::POST, - TARGET, &headers, &body, - KEY, + &keys(KEY, None), SystemTime::now(), ) .unwrap() diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index ba02c61ff5..0bc397e345 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -102,8 +102,12 @@ impl ExternalHttpConfig { }; let base = ServiceBaseUrl::new(self.base_url.clone()); let numeric_loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } + Some(Host::Ipv6(ip)) => { + registry_platform_httputil::loopback::loopback_address(ip.into()) + } _ => false, }; if base.is_err() || (self.base_url.scheme() == "http" && !numeric_loopback) { @@ -414,7 +418,7 @@ impl ExternalHttpConnection { // peers may be private, but metadata and non-loopback cleartext remain // denied. Each request connects to only the addresses validated here. let policy = if url.scheme() == "http" { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy { allowed_schemes: vec!["https".into()], diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 491f29d2e6..876fbfe5d9 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -25,9 +25,13 @@ use axum::{ routing::{get, post}, Json, Router, }; +use registry_platform_authcommon::{ + record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, RefusalRecorder, +}; use registry_platform_httpsec::{ normalize_framework_rejection, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::{json, Value}; use std::{future::Future, sync::Arc, time::Duration}; @@ -117,13 +121,17 @@ where )) } } +pub(crate) const WEBHOOK_CHALLENGE: &str = + "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\""; + pub fn router(state: HttpState) -> Router { + let refusals = state.store.metrics().refusal_recorder().clone(); let ready_state = state.clone(); let ready_bindings = Arc::new(BindingReadiness::default()); let routes = Router::new() - .route("/health", get(|| async { Json(json!({"live":true})) })) + .route(HEALTH_PATH, get(live)) .route( - "/ready", + READY_PATH, get(move || ready(ready_state.clone(), ready_bindings.clone())), ) .route("/v1/workflows/{workflow}", get(workflow_contract)) @@ -151,12 +159,11 @@ pub fn router(state: HttpState) -> Router { post(crate::event_trigger::receive), ) .with_state(state); - http_edge(routes, signed_events) + http_edge(routes, signed_events, refusals) } /// Every route takes at most 128 KiB, except the signed event route, which -/// takes up to the Version 1 signable bound so every event a producer can sign -/// reaches the verifier. -fn http_edge(router: Router, signed_events: Router) -> Router { +/// takes a body of up to 1 MiB. +fn http_edge(router: Router, signed_events: Router, refusals: Arc) -> Router { let signable = crate::event_trigger::MAXIMUM_EVENT_BYTES; router .layer(DefaultBodyLimit::max(131_072)) @@ -168,8 +175,9 @@ fn http_edge(router: Router, signed_events: Router) -> Router { ) .fallback(route_not_found) .method_not_allowed_fallback(method_not_allowed) + .layer(middleware::from_fn_with_state(refusals, record_refusals)) .layer(middleware::from_fn(http_boundary)) - .layer(registry_platform_httpsec::security_headers( + .layer(registry_platform_httpsec::security_headers_without_posture( registry_platform_httpsec::CspBuilder::deny_by_default(), )) } @@ -186,6 +194,28 @@ async fn http_boundary(request: axum::http::Request, next: Nex .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); response } +/// The one point where a refusal is counted and logged. A refusal answer +/// carries a `RefusalNote` in its response extensions, which is not part of +/// the serialized answer. The log line carries the fixed check and the request +/// trace, so it runs inside the request's trace scope and outside any span. +async fn record_refusals( + State(refusals): State>, + request: axum::http::Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + let trace = current_trace(); + let declared = response.extensions().get::(); + record_refusal!( + refusals, + *note, + trace_id = trace.trace_id, + declared = declared + ); + } + response +} /// Framework rejections carry axum's own bodies, which no Coordinator caller /// was promised. The statuses are kept; the body becomes the vocabulary's /// `request.*` problem for that status. @@ -225,7 +255,39 @@ pub(crate) fn problem(error: CoordinatorError) -> Response { "the service answered a server problem" ); } - problem_response(problem) + let check = refusal_check(&error, problem); + let mut response = problem_response(problem); + if let Some(check) = check { + response.extensions_mut().insert(RefusalNote::new(check)); + if let Some(declared) = error.declared { + response.extensions_mut().insert(*declared); + } + } + response +} +/// The check that refused the caller, for the answers that refuse one: a 401 +/// or 403, a service outage of the token verifier, and a concealed run. A run +/// that is absent or not visible is one code in every store path, so the +/// member is set here. Any other refusal must carry its member from the +/// constructor; one that does not is a defect and is reported, not counted +/// under a guess. +fn refusal_check(error: &CoordinatorError, problem: ProblemCode) -> Option { + if error.check.is_some() { + return error.check; + } + match problem { + ProblemCode::RunNotVisible => Some(FailedCheck::Visibility), + ProblemCode::AuthenticationRefused + | ProblemCode::OperationNotAuthorized + | ProblemCode::EventUnauthenticated => { + tracing::error!( + code = %error.code, + "a caller refusal carries no failed check and was not counted" + ); + None + } + _ => None, + } } pub(crate) fn current_trace() -> TraceContext { REQUEST_TRACE @@ -321,16 +383,43 @@ pub(crate) async fn caller(s: &HttpState, headers: &HeaderMap) -> Result result } async fn authenticated_caller(s: &HttpState, headers: &HeaderMap) -> Result { - let token = single_header(headers, axum::http::header::AUTHORIZATION.as_str()) - .and_then(|value| registry_platform_authcommon::parse_bearer_token(value).ok()) - .ok_or_else(|| { - CoordinatorError::new( - "access.unauthenticated", - "a verified access token is required", - ) - })?; + let token = bearer_token(headers).map_err(crate::access::unauthenticated)?; s.authenticator.authenticate(token).await } +/// The bearer credential an `Authorization` header carries, or the check that +/// refuses it: no header, or not the Bearer scheme, is a missing credential. A +/// repeated, unreadable or misshapen header is a malformed one. +pub(crate) fn bearer_token(headers: &HeaderMap) -> std::result::Result<&str, FailedCheck> { + let mut values = headers.get_all(axum::http::header::AUTHORIZATION).iter(); + let Some(value) = values.next() else { + return Err(FailedCheck::CredentialMissing); + }; + if values.next().is_some() { + return Err(FailedCheck::CredentialMalformed); + } + let value = value + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + registry_platform_authcommon::parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) +} +/// The shared probe object with the member this service has always answered. +fn probe_body(shared: &str, member: &str) -> Value { + let mut body: Value = serde_json::from_str(shared).expect("shared probe bodies are JSON"); + body[member] = json!(true); + body +} +fn live_body() -> Value { + probe_body(HEALTH_BODY, "live") +} +fn ready_body() -> Value { + probe_body(READY_BODY, "ready") +} +async fn live() -> Json { + Json(live_body()) +} async fn ready(s: HttpState, bindings: Arc) -> Response { if !s.recovery_only && deployment::check(&s.store, &s.runtime, s.workflows.digest()) @@ -341,7 +430,7 @@ async fn ready(s: HttpState, bindings: Arc) -> Response { .check(|| s.store.check_runtime_bindings(&s.runtime)) .await { - (StatusCode::OK, Json(json!({"ready":true}))).into_response() + (StatusCode::OK, Json(ready_body())).into_response() } else { ( StatusCode::SERVICE_UNAVAILABLE, @@ -357,6 +446,26 @@ mod readiness_tests { use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Notify; + #[tokio::test] + async fn the_health_route_answers_the_shared_status_member_and_its_own() { + use tower::ServiceExt as _; + let response = Router::new() + .route(HEALTH_PATH, get(live)) + .oneshot( + axum::http::Request::builder() + .uri(HEALTH_PATH) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!(&body[..], br#"{"live":true,"status":"ok"}"#); + } + #[tokio::test(start_paused = true)] async fn live_binding_readiness_refreshes_success_and_failure_at_the_fixed_deadline() { let cache = BindingReadiness::default(); @@ -661,6 +770,7 @@ mod problem_tests { }), ), Router::new(), + Arc::new(RefusalRecorder::new("coordinator").unwrap()), ) }; let traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; @@ -712,6 +822,7 @@ mod problem_tests { "/v1/events/{workflow}/{trigger}", post(|body: axum::body::Bytes| async move { body.len().to_string() }), ), + Arc::new(RefusalRecorder::new("coordinator").unwrap()), ) }; let signable = crate::event_trigger::MAXIMUM_EVENT_BYTES; @@ -749,8 +860,11 @@ mod problem_tests { .flat_map(|path| path.as_object().unwrap().values()) { if operation.get("security").is_some() { - let challenge = if operation["security"][0].get("eventSource").is_some() { - "Registry-Signature version=\"v1\"" + let security = &operation["security"][0]; + let challenge = if security.get("eventSource").is_some() + || security.get("reviewCompletion").is_some() + { + "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"" } else { "Bearer" }; @@ -775,6 +889,31 @@ mod problem_tests { .flat_map(|path| path.as_object().unwrap().iter()) } + #[test] + fn probe_bodies_keep_their_own_member_and_add_the_shared_status() { + assert_eq!(live_body(), json!({"live":true,"status":"ok"})); + assert_eq!(ready_body(), json!({"ready":true,"status":"ready"})); + } + + #[test] + fn probe_routes_use_the_shared_paths() { + let document = openapi(); + for (path, key, word) in [ + (registry_platform_httputil::probe::HEALTH_PATH, "live", "ok"), + ( + registry_platform_httputil::probe::READY_PATH, + "ready", + "ready", + ), + ] { + let schema = &document["paths"][path]["get"]["responses"]["200"]["content"] + ["application/json"]["schema"]; + assert_eq!(schema["required"], json!([key, "status"]), "{path}"); + assert_eq!(schema["properties"][key]["type"], "boolean", "{path}"); + assert_eq!(schema["properties"]["status"]["const"], word, "{path}"); + } + } + #[test] fn openapi_summarizes_every_operation_once() { let document = openapi(); @@ -1415,7 +1554,7 @@ async fn retain(State(s): State, headers: HeaderMap, body: BoundedBod ) } /// Casework's completion destination authenticates with the connection's -/// completion credential and recipient binding, never a caller access token. +/// Standard Webhooks keys selected by its recipient binding. async fn review_completion( State(s): State, headers: HeaderMap, @@ -1767,31 +1906,35 @@ pub fn openapi() -> Value { } paths.entry(path.to_owned()).or_insert_with(|| json!({}))[method] = op; } + let mut completion_parameters = vec![json!({ + "name":"Registry-Recipient-Binding","in":"header","required":true, + "description":"Selects the connection that verifies the delivery.", + "schema":{"type":"string","pattern":"^[!-~]{1,256}$","minLength":1,"maxLength":256} + })]; + completion_parameters.extend(admission_contracts::webhook_parameters()); paths.insert( registry_review_protocol::REVIEW_COMPLETIONS_PATH.into(), json!({"post":{ "operationId":"receiveReviewCompletion", "summary":summary("receiveReviewCompletion"), - "description":"Casework's completion destination for a review producer connection reports that a review result exists. The event only wakes the step waiting on that request, which then reads the result with the connection's producer credential. Every authentic, well-formed event answers 204 whether or not a step waits on its request.", + "description":"Casework's completion destination for a review producer connection reports that a review result exists. The event only wakes the step waiting on that request, which then reads the result with the connection's producer credential. The connection key verifies the signed webhook ID, Unix timestamp and exact body within 300 seconds in either direction. Every authentic, well-formed event answers 204 whether or not a step waits on its request.", "security":[{"reviewCompletion":[]}], - "parameters":[ - {"name":"Registry-Recipient-Binding","in":"header","required":true,"description":"The recipient binding configured for the connection's completion destination.","schema":{"type":"string","minLength":1}}, - {"name":"Idempotency-Key","in":"header","required":true,"description":"The event identifier.","schema":{"type":"string","format":"uuid"}} - ], + "parameters":completion_parameters, "requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}}}, "responses":{} }}), ); let mut responses = problem_responses(&REVIEW_COMPLETION_PROBLEMS); + responses["401"]["headers"]["WWW-Authenticate"] = admission_contracts::webhook_challenge(); responses.insert( "204".into(), json!({"description":"Authentic completion accepted"}), ); paths[registry_review_protocol::REVIEW_COMPLETIONS_PATH]["post"]["responses"] = Value::Object(responses); - for (path, key) in [("/health", "live"), ("/ready", "ready")] { + for (path, key, word) in [(HEALTH_PATH, "live", "ok"), (READY_PATH, "ready", "ready")] { let mut responses = problem_responses(&[ProblemCode::RequestMethodNotAllowed]); - responses.insert("200".into(), json!({"description":"Health result","content":{"application/json":{"schema":{"type":"object","required":[key],"properties":{key:{"type":"boolean"}}}}}})); + responses.insert("200".into(), json!({"description":"Health result","content":{"application/json":{"schema":{"type":"object","required":[key,"status"],"properties":{key:{"type":"boolean"},"status":{"const":word}}}}}})); responses.insert( "503".into(), json!({"description":"Deployment unavailable or in recovery hold"}), @@ -1837,5 +1980,290 @@ pub fn openapi() -> Value { schemas["CheckNow"] = json!({"type":"object","additionalProperties":false,"required":["step"],"properties":{"step":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9_-]+$","description":"The waiting step to read now, as inspect lists it under waits."}}}); schemas["CheckNowResult"] = json!({"type":"object","required":["runId","step","nextObservationAt","observations","observationLimit"],"properties":{"runId":{"type":"string","format":"uuid"},"step":{"type":"string"},"nextObservationAt":{"type":["string","null"],"format":"date-time","description":"When the early read is due, no sooner than the read floor after the last read; null while a read is already in flight."},"observations":{"type":"integer","minimum":0},"observationLimit":{"type":"integer","minimum":1}}}); admission_contracts::extend(&mut paths, &mut schemas); - json!({"openapi":"3.1.0","info":{"title":"Registry Coordinator","version":env!("CARGO_PKG_VERSION"),"description":"Registry Coordinator HTTP contract. Refusals use the closed problem vocabulary."},"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer","bearerFormat":"JWT"},"reviewCompletion":{"type":"http","scheme":"bearer","description":"The completion credential configured for a Casework review connection, presented with its recipient binding."},"eventSource":{"type":"apiKey","in":"header","name":"X-Registry-Signature","description":"The platform v1 HMAC delivery signature, bound to the canonical envelope, signed delivery headers, HTTP method and exact request target. The configured event source key is separate from caller bearer tokens."}},"schemas":schemas},"paths":paths}) + json!({"openapi":"3.1.0","info":{"title":"Registry Coordinator","version":env!("CARGO_PKG_VERSION"),"description":"Registry Coordinator HTTP contract. Refusals use the closed problem vocabulary."},"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer","bearerFormat":"JWT"},"reviewCompletion":{"type":"apiKey","in":"header","name":"webhook-signature","description":"Standard Webhooks signature verified by the completion key of the connection selected by Registry-Recipient-Binding."},"eventSource":{"type":"apiKey","in":"header","name":"webhook-signature","description":"Standard Webhooks signature verified by the event key configured for the workflow and trigger in the URL."}},"schemas":schemas},"paths":paths}) +} + +#[cfg(test)] +mod refusal_recording_tests { + use super::*; + use registry_platform_metrics::Exposition; + use std::sync::Mutex; + + /// A value no refusal may carry into the counter or the log. + const CANARY: &str = "canary-subject-7f3a91"; + + #[derive(Clone, Default)] + struct Captured(Arc>>); + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn exposition(recorder: &RefusalRecorder) -> String { + let mut out = Exposition::new(); + recorder.counter().write(&mut out).unwrap(); + out.finish() + } + + /// Send one request through the edge. Returns the status, the body, the + /// counter exposition and the captured log. + async fn refused(error: CoordinatorError) -> (StatusCode, Value, String, String) { + use tower::ServiceExt as _; + let recorder = Arc::new(RefusalRecorder::new("coordinator").unwrap()); + let error = Arc::new(Mutex::new(Some(error))); + let app = http_edge( + Router::new().route( + "/v1/refuse", + get(move || async move { problem(error.lock().unwrap().take().unwrap()) }), + ), + Router::new(), + recorder.clone(), + ); + let captured = Captured::default(); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt() + .with_writer(move || writer.clone()) + .with_ansi(false) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let response = app + .oneshot( + axum::http::Request::builder() + .uri("/v1/refuse") + .header( + "traceparent", + "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", + ) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 65_536) + .await + .unwrap(); + let body = serde_json::from_slice(&bytes).unwrap(); + let log = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + (status, body, exposition(&recorder), log) + } + + #[tokio::test] + async fn every_refusal_the_service_answers_is_counted_and_logged_under_its_check() { + for (error, status, code, check) in [ + ( + crate::access::unauthenticated(FailedCheck::CredentialMissing), + 401, + "authentication.refused", + "credential-missing", + ), + ( + crate::access::unauthenticated(FailedCheck::TokenSignature), + 401, + "authentication.refused", + "token-signature", + ), + ( + CoordinatorError::new("access.unavailable", CANARY) + .failing(FailedCheck::KeySourceUnavailable), + 503, + "service.unavailable", + "key-source-unavailable", + ), + ( + CoordinatorError::new("access.denied", CANARY).failing(FailedCheck::Operation), + 403, + "operation.not-authorized", + "operation", + ), + ( + CoordinatorError::new("access.denied", CANARY).failing(FailedCheck::Scope), + 403, + "operation.not-authorized", + "scope", + ), + ( + CoordinatorError::new("event-unauthenticated", CANARY) + .failing(FailedCheck::DeliverySignature), + 401, + "event.unauthenticated", + "delivery-signature", + ), + ( + // Every store path raises this one code for a run the caller + // cannot see, so the member is set where the answer is made. + CoordinatorError::new("run-absent", CANARY), + 404, + "run.not-visible", + "visibility", + ), + ] { + let (answered, body, counters, log) = refused(error).await; + assert_eq!(answered.as_u16(), status, "{check}"); + assert_eq!(body["code"], code, "{check}"); + assert_eq!(body["traceId"], "0af7651916cd43dd8448eb211c80319c"); + assert!( + counters.lines().any(|line| line + == format!("coordinator_request_refusals_total{{check=\"{check}\"}} 1")), + "{check}: {counters}" + ); + assert_eq!( + counters.lines().filter(|line| line.ends_with(" 1")).count(), + 1, + "{check}: one series moved" + ); + assert_eq!( + log.lines() + .filter(|line| line.contains("request refused")) + .count(), + 1, + "{check}: {log}" + ); + for field in [ + "request refused", + "decision=\"refused\"", + &format!("failed_check=\"{check}\""), + "suppressed=0", + "trace_id=0af7651916cd43dd8448eb211c80319c", + ] { + assert!(log.contains(field), "{check}: {field} in {log}"); + } + assert!(!log.contains(CANARY), "{check}: {log}"); + assert!(!body.to_string().contains(CANARY), "{check}"); + } + } + + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_values_and_nothing_else() { + let (answered, body, _, log) = refused( + CoordinatorError::new("access.denied", CANARY) + .failing(FailedCheck::Scope) + .declaring(DeclaredScope::new("scp").with_required_scope("coordinator:run")), + ) + .await; + assert_eq!(answered.as_u16(), 403); + for field in ["scope_claim=\"scp\"", "required_scope=\"coordinator:run\""] { + assert!(log.contains(field), "{field} in {log}"); + } + assert!(!log.contains("access_profile"), "{log}"); + assert!(!body.to_string().contains("coordinator:run"), "{body}"); + // A refusal that is not a scope refusal names no declared value. + let (_, _, _, other) = refused( + CoordinatorError::new("access.denied", CANARY) + .failing(FailedCheck::Operation) + .declaring(DeclaredScope::new("scp")), + ) + .await; + assert!(!other.contains("scope_claim"), "{other}"); + } + + #[tokio::test] + async fn an_answer_that_is_not_a_caller_refusal_is_not_counted() { + for error in [ + CoordinatorError::new("request.invalid", CANARY), + CoordinatorError::new("store-unavailable", CANARY), + ] { + let (_, _, counters, log) = refused(error).await; + assert!( + counters + .lines() + .all(|line| line.starts_with('#') || line.ends_with(" 0")), + "{counters}" + ); + assert!(!log.contains("request refused"), "{log}"); + } + } + + #[tokio::test] + async fn a_caller_refusal_without_a_check_is_reported_and_not_counted_under_a_guess() { + let (status, _, counters, log) = + refused(CoordinatorError::new("access.denied", CANARY)).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!( + counters + .lines() + .all(|line| line.starts_with('#') || line.ends_with(" 0")), + "{counters}" + ); + assert!(log.contains("carries no failed check"), "{log}"); + assert!(!log.contains(CANARY), "{log}"); + } + + #[tokio::test] + async fn a_policy_denial_after_authentication_is_counted() { + use tower::ServiceExt as _; + // The gap the authentication counter left: `Caller::authorize` runs + // after the caller is resolved, so its denial reached no counter. + let recorder = Arc::new(RefusalRecorder::new("coordinator").unwrap()); + let app = http_edge( + Router::new().route( + "/v1/denied", + get(|| async { + let caller = + crate::access::synthetic_caller(vec![Action::Start], &["workflow"], false); + answer( + caller + .authorize(Action::Start, Some("another-workflow")) + .map(|()| json!({})), + ) + }), + ), + Router::new(), + recorder.clone(), + ); + let response = app + .oneshot( + axum::http::Request::builder() + .uri("/v1/denied") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(exposition(&recorder) + .contains("coordinator_request_refusals_total{check=\"operation\"} 1")); + } + + #[test] + fn the_authorization_header_names_a_missing_or_a_malformed_credential() { + let headers = |values: &[&'static [u8]]| { + let mut headers = HeaderMap::new(); + for value in values { + headers.append( + axum::http::header::AUTHORIZATION, + HeaderValue::from_bytes(value).unwrap(), + ); + } + headers + }; + assert_eq!( + bearer_token(&headers(&[])), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + bearer_token(&headers(&[b"Basic c3ludGhldGlj"])), + Err(FailedCheck::CredentialMissing) + ); + for malformed in [ + &[b"Bearer a-token" as &[u8], b"Bearer another-token"][..], + &[b"Bearer"], + &[b"Bearer two-spaces"], + &[b"Bearer "], + &[b"Bearer has space"], + &[b"Bearer \xff\xfe"], + ] { + assert_eq!( + bearer_token(&headers(malformed)), + Err(FailedCheck::CredentialMalformed), + "{malformed:?}" + ); + } + assert_eq!(bearer_token(&headers(&[b"Bearer a-token"])), Ok("a-token")); + } } diff --git a/crates/registry-coordinator/src/http/admission_contracts.rs b/crates/registry-coordinator/src/http/admission_contracts.rs index b9dee58a1a..bf951c8edc 100644 --- a/crates/registry-coordinator/src/http/admission_contracts.rs +++ b/crates/registry-coordinator/src/http/admission_contracts.rs @@ -34,11 +34,25 @@ fn embed_refs(value: &mut Value, name: &str) { } } +pub(super) fn webhook_parameters() -> [Value; 3] { + [ + json!({"name":"webhook-id","in":"header","required":true,"schema":{"type":"string","format":"uuid"}}), + json!({"name":"webhook-timestamp","in":"header","required":true,"schema":{"type":"string","pattern":"^(0|[1-9][0-9]{0,19})$"}}), + json!({"name":"webhook-signature","in":"header","required":true,"schema":{"type":"string","minLength":1}}), + ] +} + +pub(super) fn webhook_challenge() -> Value { + json!({ + "description":"Authenticate the exact delivery with the configured Standard Webhooks key.", + "schema":{"type":"string","const":super::WEBHOOK_CHALLENGE} + }) +} + fn event_path(paths: &mut Map) { let mut responses = problem_responses(&[ P::EventInvalid, P::EventUnauthenticated, - P::EventSourceUnavailable, P::EventTooLarge, P::RequestInvalid, P::RequestBodyTooLarge, @@ -57,10 +71,7 @@ fn event_path(paths: &mut Map) { P::ServiceUnavailable, P::RuntimeFailure, ]); - responses["401"]["headers"]["WWW-Authenticate"] = json!({ - "description":"Authenticate the exact canonical event and delivery attempt with the configured source key.", - "schema":{"type":"string","const":"Registry-Signature version=\"v1\""} - }); + responses["401"]["headers"]["WWW-Authenticate"] = webhook_challenge(); responses.insert("204".into(), json!({ "description":"Run admission is committed, or the exact event was already admitted. Empty Hook response proposes no source mutation.", "headers":{"X-Coordinator-Run-Id":{"schema":{"type":"string","format":"uuid"}}} @@ -68,35 +79,10 @@ fn event_path(paths: &mut Map) { let mut parameters = ["workflow", "trigger"].into_iter().map(|name| { json!({"name":name,"in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}) }).collect::>(); - for (name, schema) in [ - ("ce-specversion", json!({"const":"1.0"})), - ("ce-id", json!({"type":"string","format":"uuid"})), - ("ce-source", json!({"type":"string","minLength":1})), - ("ce-type", json!({"type":"string","minLength":1})), - ("ce-time", json!({"type":"string","format":"date-time"})), - ("ce-dataschema", json!({"type":"string","minLength":1})), - ( - "X-Registry-Event-Generation", - json!({"type":"string","pattern":"^[1-9][0-9]{0,18}$"}), - ), - ( - "X-Registry-Delivery-Attempt", - json!({"type":"string","pattern":"^[1-9][0-9]{0,18}$"}), - ), - ( - "X-Registry-Delivery-Time", - json!({"type":"string","format":"date-time"}), - ), - ( - "Idempotency-Key", - json!({"type":"string","minLength":1,"maxLength":256}), - ), - ] { - parameters.push(json!({"name":name,"in":"header","required":true,"schema":schema})); - } + parameters.extend(webhook_parameters()); paths.insert("/v1/events/{workflow}/{trigger}".into(), json!({"post":{ "operationId":"admitEvent","summary":"Start a workflow from an authenticated product event", - "description":"Accept at most 1048576 canonical JSON bytes, the v1 signable bound, using the platform HookEnvelope and v1 delivery signature; the admitted event value is then held to the 131072-byte structured value profile. Envelope headers must match the body and the authored source, event type and data schema. Delivery time must be within 30 seconds; an older event may be redelivered. The exact source, event identity and trigger bind admission across retries. Every downstream call uses its own product authorization.", + "description":"Accept at most 1048576 canonical JSON bytes in a HookEnvelope, then hold the admitted event to the 131072-byte structured value profile. Standard Webhooks signs the webhook ID, Unix timestamp and exact body using the key for the trigger in the URL. The signed timestamp must be within 300 seconds in either direction. The webhook ID must equal the envelope ID, and the envelope must match the configured producer URI and authored event type and data schema. The source URI, event ID and trigger bind admission across retries. Every downstream call uses its own product authorization.", "security":[{"eventSource":[]}],"parameters":parameters, "requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HookEnvelope"}}}}, "responses":responses diff --git a/crates/registry-coordinator/src/lib.rs b/crates/registry-coordinator/src/lib.rs index 45fe4e3802..c71da85b3c 100644 --- a/crates/registry-coordinator/src/lib.rs +++ b/crates/registry-coordinator/src/lib.rs @@ -22,6 +22,7 @@ pub mod problem; pub mod project; mod project_check; pub mod protocol; +mod provision; mod read_in_force; mod record_read; mod review; diff --git a/crates/registry-coordinator/src/metrics.rs b/crates/registry-coordinator/src/metrics.rs index bd6e618792..d3666e577d 100644 --- a/crates/registry-coordinator/src/metrics.rs +++ b/crates/registry-coordinator/src/metrics.rs @@ -64,6 +64,7 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE}; use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::Router; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -84,6 +85,7 @@ pub struct Metrics { attempts: CounterVec, refusals: CounterVec, sample_failures: CounterVec, + refusals_by_check: Arc, } impl fmt::Debug for Metrics { @@ -125,6 +127,7 @@ impl Default for Metrics { "sample", SampleKind::ALL.map(SampleKind::as_str), ), + refusals_by_check: Arc::new(RefusalRecorder::new("coordinator").expect(DECLARATION)), } } } @@ -318,6 +321,13 @@ impl Metrics { count(&self.refusals, &[refusal.as_str()]); } + /// Counts every refused request by the check that failed, and admits a + /// bounded number of log lines per check. + #[must_use] + pub fn refusal_recorder(&self) -> &Arc { + &self.refusals_by_check + } + /// Count one scrape-time read that failed. pub fn record_sample_failure(&self, sample: SampleKind) { count(&self.sample_failures, &[sample.as_str()]); @@ -337,6 +347,10 @@ impl Metrics { ] { counter.write(&mut out).expect(DECLARATION); } + self.refusals_by_check + .counter() + .write(&mut out) + .expect(DECLARATION); out.header( "coordinator_dispatch_jobs", Some("Steps waiting to run, running, or held unknown, sampled at scrape."), @@ -516,7 +530,7 @@ pub fn metrics_router(store: Arc) -> Router { Router::new() .route(METRICS_PATH, get(serve_metrics)) .layer(registry_platform_httpsec::request_body_limit(65_536)) - .layer(registry_platform_httpsec::security_headers( + .layer(registry_platform_httpsec::security_headers_without_posture( registry_platform_httpsec::CspBuilder::deny_by_default(), )) .with_state(MetricsState { store }) @@ -525,6 +539,7 @@ pub fn metrics_router(store: Arc) -> Router { #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; /// Every sample line the exposition carries, without its value. fn series(text: &str) -> Vec<&str> { @@ -563,6 +578,12 @@ mod tests { sample.as_str() ) })); + expected.extend(FailedCheck::ALL.map(|check| { + format!( + "coordinator_request_refusals_total{{check=\"{}\"}}", + check.as_str() + ) + })); expected.extend( ["pending", "leased", "unknown"] .map(|state| format!("coordinator_dispatch_jobs{{state=\"{state}\"}}")), @@ -621,6 +642,10 @@ mod tests { metrics.record_run_finished(RunOutcome::CancelledAfterEffect); metrics.record_step_attempt(StepAttempt::Accepted); metrics.record_authentication_refusal(AuthenticationRefusal::Policy); + assert!(metrics + .refusal_recorder() + .record(FailedCheck::Operation) + .is_some()); let text = metrics.render( Some(DispatchDepth { pending: 5, @@ -636,9 +661,18 @@ mod tests { oldest_due_age_seconds: 90, }), ); - assert_eq!( - text, - "\ + let refusals_by_check: String = std::iter::once( + "# HELP coordinator_request_refusals_total Requests refused, by the check that failed.\n# TYPE coordinator_request_refusals_total counter\n".to_owned(), + ) + .chain(FailedCheck::ALL.map(|check| { + format!( + "coordinator_request_refusals_total{{check=\"{}\"}} {}\n", + check.as_str(), + u8::from(check == FailedCheck::Operation) + ) + })) + .collect(); + let head = "\ # HELP coordinator_runs_admitted_total Runs whose admission committed. # TYPE coordinator_runs_admitted_total counter coordinator_runs_admitted_total 2 @@ -665,6 +699,8 @@ coordinator_authentication_refusals_total{reason=\"unavailable\"} 0 # TYPE coordinator_metrics_sample_failures_total counter coordinator_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 coordinator_metrics_sample_failures_total{sample=\"run-holds\"} 0 +"; + let tail = "\ # HELP coordinator_dispatch_jobs Steps waiting to run, running, or held unknown, sampled at scrape. # TYPE coordinator_dispatch_jobs gauge coordinator_dispatch_jobs{state=\"pending\"} 5 @@ -684,8 +720,8 @@ coordinator_hold_active{hold=\"admissions\"} 0 # HELP coordinator_oldest_due_age_seconds Seconds since the oldest pending job was due, or 0 when none is overdue, sampled at scrape. # TYPE coordinator_oldest_due_age_seconds gauge coordinator_oldest_due_age_seconds 90 -" - ); +"; + assert_eq!(text, format!("{head}{refusals_by_check}{tail}")); } #[test] diff --git a/crates/registry-coordinator/src/problem.rs b/crates/registry-coordinator/src/problem.rs index 6445dca2ff..c3e0a4b170 100644 --- a/crates/registry-coordinator/src/problem.rs +++ b/crates/registry-coordinator/src/problem.rs @@ -52,7 +52,6 @@ pub const DEPLOYMENT_ACTIVATION_CHANGED_PROBLEM: &str = "deployment.activation-c pub const DEPLOYMENT_REFUSED_PROBLEM: &str = "deployment.refused"; pub const EVALUATION_UNCERTAIN_PROBLEM: &str = "evaluation.uncertain"; pub const EVENT_INVALID_PROBLEM: &str = "event.invalid"; -pub const EVENT_SOURCE_UNAVAILABLE_PROBLEM: &str = "event.source-unavailable"; pub const EVENT_TOO_LARGE_PROBLEM: &str = "event.too-large"; pub const EVENT_UNAUTHENTICATED_PROBLEM: &str = "event.unauthenticated"; pub const EXECUTION_HELD_PROBLEM: &str = "execution.held"; @@ -102,7 +101,6 @@ pub enum ProblemCode { DeploymentRefused, EvaluationUncertain, EventInvalid, - EventSourceUnavailable, EventTooLarge, EventUnauthenticated, ExecutionHeld, @@ -153,7 +151,6 @@ impl ProblemCode { Self::DeploymentRefused, Self::EvaluationUncertain, Self::EventInvalid, - Self::EventSourceUnavailable, Self::EventTooLarge, Self::EventUnauthenticated, Self::ExecutionHeld, @@ -204,7 +201,6 @@ impl ProblemCode { Self::DeploymentRefused => DEPLOYMENT_REFUSED_PROBLEM, Self::EvaluationUncertain => EVALUATION_UNCERTAIN_PROBLEM, Self::EventInvalid => EVENT_INVALID_PROBLEM, - Self::EventSourceUnavailable => EVENT_SOURCE_UNAVAILABLE_PROBLEM, Self::EventTooLarge => EVENT_TOO_LARGE_PROBLEM, Self::EventUnauthenticated => EVENT_UNAUTHENTICATED_PROBLEM, Self::ExecutionHeld => EXECUTION_HELD_PROBLEM, @@ -295,9 +291,7 @@ impl ProblemCode { Self::RequestUnsupportedMediaType => 415, Self::RequestUnprocessable => 422, Self::RuntimeFailure => 500, - Self::AuditResponseUnavailable - | Self::ServiceUnavailable - | Self::EventSourceUnavailable => 503, + Self::AuditResponseUnavailable | Self::ServiceUnavailable => 503, } } @@ -318,7 +312,6 @@ impl ProblemCode { Self::DeploymentRefused => "Deployment not serving", Self::EvaluationUncertain => "Evaluation outcome uncertain", Self::EventInvalid => "Event contract refused", - Self::EventSourceUnavailable => "Event source unavailable", Self::EventTooLarge => "Event too large", Self::EventUnauthenticated => "Event authentication refused", Self::ExecutionHeld => "Execution held", @@ -369,7 +362,7 @@ impl ProblemCode { "The operation may have completed, but its audited result could not be released. Inspect the run before repeating the operation." } Self::AuthenticationRefused => { - "The bearer credential is missing, invalid, or expired." + "The caller credential or completion signature is missing, invalid, or expired." } Self::BindingConflict => { "The run's original connection settings differ from this service's runtime configuration." @@ -391,7 +384,6 @@ impl ProblemCode { "An evaluation may have completed at its provider, so the run is never evaluated again." } Self::EventInvalid => "The signed event must satisfy the accepted canonical envelope and typed event contract.", - Self::EventSourceUnavailable => "Restore the configured event source signing key and its enabled secret provider before retrying delivery.", Self::EventTooLarge => "The signed event exceeds the event value profile: 131072 canonical bytes, 32 levels of nesting, 4096 values, 256 items per array, 256 members per object, and 16384 bytes per string. Have the producer project fewer or smaller fields into the event.", Self::EventUnauthenticated => "Send a fresh signed delivery from the exact configured source to its accepted trigger.", Self::ExecutionHeld => { @@ -498,7 +490,6 @@ pub(crate) fn for_error(code: &str) -> Option { "request.content-type-invalid" => ProblemCode::RequestUnsupportedMediaType, "list-limit-invalid" => ProblemCode::RequestLimitOutOfRange, "event-invalid" => ProblemCode::EventInvalid, - "event-source-unavailable" => ProblemCode::EventSourceUnavailable, "event-too-large" => ProblemCode::EventTooLarge, "event-unauthenticated" => ProblemCode::EventUnauthenticated, "reason-invalid" => ProblemCode::RequestReasonInvalid, @@ -730,7 +721,7 @@ mod tests { #[test] fn the_vocabulary_is_complete_and_closed() { - assert_eq!(ProblemCode::ALL.len(), 46); + assert_eq!(ProblemCode::ALL.len(), 45); for code in ProblemCode::ALL { assert_eq!(ProblemCode::from_code(code.code()), Some(*code)); } @@ -744,11 +735,6 @@ mod tests { ProblemCode::EventUnauthenticated, 401, ), - ( - "event-source-unavailable", - ProblemCode::EventSourceUnavailable, - 503, - ), ("event-too-large", ProblemCode::EventTooLarge, 413), ] { assert_eq!(for_error(internal), Some(public)); diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index af94d38dce..7ade965e2f 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -459,10 +459,23 @@ pub trait AdapterSet: Send + Sync { } } - /// The connection whose configured completion credential and recipient - /// binding both match, compared in constant time. Without exactly one - /// match the sender is not authenticated. - fn review_completion(&self, _token: &str, _recipient: &str) -> Option { + /// Keys for the event trigger named by its workflow and trigger path. + fn event_keys( + &self, + _workflow: &str, + _trigger: &str, + ) -> Option<®istry_platform_crypto::delivery_signature::DeliveryKeys> { + None + } + + /// The connection and completion keys selected by its recipient binding. + fn review_completion( + &self, + _recipient: &str, + ) -> Option<( + &str, + ®istry_platform_crypto::delivery_signature::DeliveryKeys, + )> { None } } diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs new file mode 100644 index 0000000000..f34de9a891 --- /dev/null +++ b/crates/registry-coordinator/src/provision.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision`: the database, roles and grants `apply` expects. +//! +//! The shared runner reads the role names, database and passwords from the +//! two URLs this module resolves out of the runtime file, so nothing is +//! written twice. When the file has a deployment block, its `runtimeRole` +//! must be the runtime URL's user. `apply` creates the schema the runtime +//! file's `namespace` names, so provisioning gives the migration role `CREATE` on the database +//! and the runtime role `CONNECT`, and leaves every other grant to `apply`. + +use std::path::Path; +use std::process::ExitCode; + +use registry_platform_config::SecretResolver; +use registry_platform_provision::cli::{ + run_provision, OutputFormat, ProvisionArgs, ProvisionInput, +}; +use registry_platform_provision::{ProductDatabase, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +use crate::runtime::RuntimeConfig; + +/// The diagnostic code the runtime file's own refusals carry. +const RUNTIME_CONFIG_REFUSED: &str = "coordinator.runtime-config.refused"; + +/// The runtime URL logs in as a role other than `deployment.runtimeRole`. +const RUNTIME_ROLE_MISMATCH: &str = "coordinator.runtime-config.runtime-role-mismatch"; + +/// Runs the verb. The shared runner owns a runtime of its own, so it runs off +/// the service's executor threads. +pub(crate) async fn run(args: ProvisionArgs, format: OutputFormat) -> ExitCode { + match tokio::task::spawn_blocking(move || { + run_provision( + "coordinatorctl", + registry_platform_buildinfo::DISPLAY_VERSION, + &args, + format, + load, + ) + }) + .await + { + Ok(exit) => exit, + Err(_) => { + eprintln!("coordinatorctl provision stopped unexpectedly"); + ExitCode::from(3) + } + } +} + +fn load(path: &Path) -> Result> { + let path = crate::cli::absolute_runtime_path(path).map_err(|error| first_diagnostic(&error))?; + let runtime = RuntimeConfig::load(&path).map_err(|error| first_diagnostic(&error))?; + let resolver = runtime.secret_providers.resolver().map_err(|_| { + refusal( + "/secretProviders", + "the secret providers could not be set up", + "Correct the secretProviders block of the runtime file.", + ) + })?; + let database = &runtime.database; + let migration_url = secret_text( + &resolver, + &database.migration_url_ref, + "/database/migrationUrlRef", + )?; + let runtime_url = secret_text( + &resolver, + &database.runtime_url_ref, + "/database/runtimeUrlRef", + )?; + if let Some(deployment) = &runtime.deployment { + require_runtime_role(&runtime_url, &deployment.runtime_role)?; + } + let ca_pem = match &database.ca_bundle_ref { + Some(reference) => Some( + secret_text(&resolver, reference, "/database/caBundleRef")? + .as_bytes() + .to_vec(), + ), + None => None, + }; + Ok(ProvisionInput { + product: ProductDatabase { + product: "coordinator", + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + }, + migration_url, + runtime_url, + ca_pem, + }) +} + +/// `apply` grants to `deployment.runtimeRole` and the service requires its +/// connection to log in as that role, so a runtime URL naming another user +/// would provision a role neither of them uses. A URL with no user, or one +/// that does not parse, gets its own message. The diagnostic names the +/// configured role, never the URL. +fn require_runtime_role(runtime_url: &str, expected: &str) -> Result<(), Box> { + let user = runtime_url + .trim() + .parse::() + .ok() + .and_then(|config| config.get_user().map(str::to_owned)); + match user.as_deref() { + Some(user) if user == expected => Ok(()), + Some(_) => Err(Box::new(Diagnostic::error( + RUNTIME_ROLE_MISMATCH, + "/database/runtimeUrlRef", + format!( + "the runtime database URL does not log in as deployment.runtimeRole ({expected})" + ), + "Use the runtimeRole as the user of the URL database.runtimeUrlRef names, or change deployment.runtimeRole to the URL's user.", + ))), + None => Err(Box::new(Diagnostic::error( + RUNTIME_ROLE_MISMATCH, + "/database/runtimeUrlRef", + format!( + "the runtime database URL names no user, or is not a PostgreSQL URL, so it cannot log in as deployment.runtimeRole ({expected})" + ), + "Put the runtimeRole in the URL database.runtimeUrlRef names, as a PostgreSQL URL with a user.", + ))), + } +} + +fn secret_text( + resolver: &SecretResolver, + reference: &str, + pointer: &str, +) -> Result, Box> { + let secret = resolver.resolve(reference).map_err(|_| { + refusal( + pointer, + "the referenced secret could not be read", + "Make the secret the runtime file names available to this command.", + ) + })?; + let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { + refusal( + pointer, + "the referenced secret is not UTF-8 text", + "Supply a UTF-8 PostgreSQL URL or PEM file.", + ) + })?; + Ok(Zeroizing::new(text.to_owned())) +} + +fn refusal(pointer: &str, message: &str, action: &str) -> Box { + Box::new(Diagnostic::error( + RUNTIME_CONFIG_REFUSED, + pointer, + message, + action, + )) +} + +/// The decisive finding of a runtime-file refusal. +fn first_diagnostic(error: &crate::error::CoordinatorError) -> Box { + let report = error.report(); + let diagnostics = report.diagnostics(); + Box::new( + diagnostics + .iter() + .find(|diagnostic| diagnostic.severity == registry_platform_yaml::Severity::Error) + .or_else(|| diagnostics.first()) + .cloned() + .unwrap_or_else(|| { + *refusal( + "", + "the runtime file was refused", + "Correct the runtime file.", + ) + }), + ) +} diff --git a/crates/registry-coordinator/src/review.rs b/crates/registry-coordinator/src/review.rs index 2c9976a693..f0ada0c962 100644 --- a/crates/registry-coordinator/src/review.rs +++ b/crates/registry-coordinator/src/review.rs @@ -6,6 +6,7 @@ use std::sync::Arc; +use crate::event_trigger::IngressKeys; use registry_casework_client::{ submission_digest, CaseworkAuth, CaseworkClient, CaseworkClientError, CaseworkProblemCode, ReviewCancelRequest, ReviewCreateRequest, ReviewRequestAccepted, ReviewResultResponse, @@ -13,7 +14,6 @@ use registry_casework_client::{ use registry_platform_httputil::client::{PrivateKeyJwt, RetryAfter, TokenProvider}; use serde::Deserialize; use serde_json::Value; -use zeroize::Zeroizing; use crate::{ adapters::{refused, retryable, token_failure, valid_key}, @@ -30,29 +30,12 @@ pub(crate) struct CancelReviewInput { reason: String, } -/// How Casework's completion destination for this producer authenticates: -/// the bearer token it sends and the recipient binding it names. +/// Verified delivery keys and routing binding for Casework completions. pub(crate) struct CompletionSender { - pub(crate) token: Zeroizing, + pub(crate) ingress: IngressKeys, pub(crate) recipient: String, } -impl CompletionSender { - /// Both values must match, each compared in time that depends only on - /// their lengths. - fn matches(&self, token: &str, recipient: &str) -> bool { - let token_matches = registry_platform_crypto::mac::constant_time_eq( - self.token.as_bytes(), - token.as_bytes(), - ); - let recipient_matches = registry_platform_crypto::mac::constant_time_eq( - self.recipient.as_bytes(), - recipient.as_bytes(), - ); - token_matches && recipient_matches - } -} - pub(crate) struct CaseworkConnection { client: CaseworkClient, tokens: Arc, @@ -85,10 +68,8 @@ impl CaseworkConnection { self.result_check_seconds } - pub(crate) fn completion_matches(&self, token: &str, recipient: &str) -> bool { - self.completion - .as_ref() - .is_some_and(|sender| sender.matches(token, recipient)) + pub(crate) fn completion(&self) -> Option<&CompletionSender> { + self.completion.as_ref() } /// Read the result of an accepted request. The client holds a 200 answer diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 11203b81c4..c947ca96ce 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -19,10 +19,29 @@ use zeroize::Zeroizing; pub const API_VERSION: &str = "id.registrystack.org/formats/coordinator/runtime/v1alpha1"; pub const KIND: &str = "CoordinatorRuntimeConfig"; -const REMOVED_KEYS: &[RemovedKey] = &[RemovedKey { - path: "deployment.authentication.jwksSource.kind", - replacement: "Write `deployment.authentication.jwksSource.type` with the same value.", -}]; +const EVENT_KEY_REPLACEMENT: &str = "Move the key under eventSources..triggers...hmacSha256KeyRef, one distinct key per trigger."; +const REMOVED_KEYS: &[RemovedKey] = &[ + RemovedKey { + path: "deployment.authentication.jwksSource.kind", + replacement: "Write `deployment.authentication.jwksSource.type` with the same value.", + }, + RemovedKey { + path: "eventSources.*.signingKeyRef", + replacement: EVENT_KEY_REPLACEMENT, + }, + RemovedKey { + path: "eventSources.*.hmacSha256KeyRef", + replacement: EVENT_KEY_REPLACEMENT, + }, + RemovedKey { + path: "eventSources.*.previousHmacSha256KeyRef", + replacement: EVENT_KEY_REPLACEMENT, + }, + RemovedKey { + path: "connections.*.completion.bearerTokenRef", + replacement: "Replace bearerTokenRef with hmacSha256KeyRef. Casework signs review completions with Standard Webhooks.", + }, +]; #[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -489,8 +508,16 @@ pub struct ReviewCompletionConfig { schemars(extend("pattern" = "^[!-~]{1,256}$", "minLength" = 1, "maxLength" = 256)) )] pub recipient_binding: String, - /// The bearer token Casework's completion destination sends. - pub bearer_token_ref: SecretReference, + /// The exact HMAC-SHA-256 key shared with Casework's completion destination. + pub hmac_sha256_key_ref: SecretReference, + /// Optional previous key accepted during rotation. + #[serde( + default, + deserialize_with = "crate::event_trigger::present_hook_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, } /// A completion recipient binding as Casework accepts one. @@ -544,7 +571,7 @@ fn minimum_observation_interval() -> registry_platform_yaml::BoundedU32<30, 86_4 /// The shared reader checks the envelope before directly decoding RuntimeConfig. impl RuntimeConfig { pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }) @@ -874,17 +901,13 @@ impl RuntimeConfig { "use a recipientBinding no other Casework connection declares, so every completion event names one connection", )); } - let member = format!("{field}.completion.bearerTokenRef"); - if self - .secret_providers - .check_reference(&member, completion.bearer_token_ref.as_str()) - .is_err() - { - errors.push(config_error( - &member, - "enable the secretProviders entry named by the completion token reference", - )); - } + crate::event_trigger::check_key_references( + &mut errors, + &self.secret_providers, + &format!("{field}.completion"), + &completion.hmac_sha256_key_ref, + completion.previous_hmac_sha256_key_ref.as_ref(), + ); } } _ => {} @@ -895,10 +918,18 @@ impl RuntimeConfig { pub fn validate_workflow(&self, workflow: &crate::definition::Workflow) -> Result<()> { for (id, trigger) in &workflow.event_triggers { - if !self.event_sources.contains_key(&trigger.source) { + let key = self.event_sources.get(&trigger.source).and_then(|source| { + let workflow_id = registry_platform_yaml::LocalId::new(workflow.id.clone()).ok()?; + let trigger_id = registry_platform_yaml::LocalId::new(id.clone()).ok()?; + source.triggers.get(&workflow_id)?.0.get(&trigger_id) + }); + if key.is_none() { return Err(config_error( - &format!("eventSources.{}", trigger.source), - &format!("configure the source named by event trigger {id}"), + &format!( + "eventSources.{}.triggers.{}.{id}.hmacSha256KeyRef", + trigger.source, workflow.id + ), + "Configure a distinct delivery key for this event trigger.", )); } } @@ -1168,8 +1199,8 @@ fn config_error(field: &str, action: &str) -> CoordinatorError { } fn is_loopback(url: &Url) -> bool { match url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), _ => false, } } @@ -1223,6 +1254,15 @@ pub fn runtime_schema() -> Result { schema["properties"]["eventSources"] = json!({"type":"object", "maxProperties":16, "description":"Optional trusted event producers keyed by the logical IDs used in Workflow triggers.", "propertyNames":{"$ref":"#/$defs/LocalId"}, "additionalProperties":{"$ref":"#/$defs/EventSourceConfig"}}); + schema["$defs"]["EventSourceConfig"]["properties"]["triggers"] = json!({ + "type":"object", "maxProperties":16, + "description":"Keys for event URLs, grouped by workflow ID.", + "propertyNames":{"$ref":"#/$defs/LocalId"}, "additionalProperties":{"$ref":"#/$defs/WorkflowTriggerKeys"} + }); + schema["$defs"]["WorkflowTriggerKeys"] = json!({ + "type":"object", "maxProperties":16, + "propertyNames":{"$ref":"#/$defs/LocalId"}, "additionalProperties":{"$ref":"#/$defs/TriggerKeyConfig"} + }); schema["properties"]["database"] = json!({"allOf":[ {"$ref":"#/$defs/DatabaseConfig"}, {"properties":{"testOnlyPlaintext":{"const":false}}} @@ -1449,3 +1489,32 @@ fn serialize_database( } map.end() } + +#[cfg(test)] +mod loopback_tests { + use super::*; + + #[test] + fn loopback_endpoints_are_the_shared_numeric_literals_and_never_names() { + for loopback in [ + "http://127.0.0.1:8080", + "http://127.9.9.9:8080", + "http://[::1]:8080", + "http://[::ffff:127.0.0.1]:8080", + ] { + let url = Url::parse(loopback).unwrap(); + assert!(is_loopback(&url), "{loopback}"); + check_endpoint(&url).unwrap_or_else(|error| panic!("{loopback}: {error}")); + } + for other in [ + "http://localhost:8080", + "http://10.0.0.1:8080", + "http://[::ffff:10.0.0.1]:8080", + "http://example.test:8080", + ] { + let url = Url::parse(other).unwrap(); + assert!(!is_loopback(&url), "{other}"); + assert!(check_endpoint(&url).is_err(), "{other}: cleartext refused"); + } + } +} diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index f3facadddb..1242e34e17 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -1864,7 +1864,9 @@ pub fn check(definition: &Definition, document: &ScenarioDocument) -> Result Vec { - if refused.file.as_deref() == Some(Path::new("workflow.yaml")) { + if refused.file.as_deref().map(std::path::PathBuf::as_path) == Some(Path::new("workflow.yaml")) + { return authoring::positioned(workflow, refused) .report() .into_diagnostics(); @@ -2065,7 +2068,9 @@ pub(crate) fn case_pointer(error: &CoordinatorError, index: usize) -> String { .field .as_deref() .filter(|field| { - field.starts_with('/') && error.file.as_deref() == Some(Path::new(SCENARIOS_FILE)) + field.starts_with('/') + && error.file.as_deref().map(std::path::PathBuf::as_path) + == Some(Path::new(SCENARIOS_FILE)) }) .unwrap_or_default(); format!("/cases/{index}{within}") diff --git a/crates/registry-coordinator/src/service.rs b/crates/registry-coordinator/src/service.rs index fe95dc5afa..22e498c33b 100644 --- a/crates/registry-coordinator/src/service.rs +++ b/crates/registry-coordinator/src/service.rs @@ -48,7 +48,7 @@ async fn execute(cli: Cli) -> Result<()> { let d = deployment::config(&runtime)?; let workflows = Arc::new(deployment::load_workflows(d)?); workflows.validate(&runtime)?; - check_event_ingress_keys(&runtime, cli.recovery_only)?; + let event_keys = event_ingress_keys(&runtime, cli.recovery_only)?; let authenticator = Arc::new( d.authentication .authenticator(&runtime.secret_providers, d.local()) @@ -65,7 +65,8 @@ async fn execute(cli: Cli) -> Result<()> { } else { deployment::check_serving(&store, &runtime, workflows.digest()).await?; } - let adapters: Arc = Arc::new(HttpAdapters::new(&runtime)?); + let adapters: Arc = + Arc::new(HttpAdapters::with_event_keys(&runtime, event_keys)?); let worker = Worker::new(store.clone(), adapters.clone()); let listener = tokio::net::TcpListener::bind(d.listener.bind.socket_addr()) .await @@ -203,11 +204,14 @@ async fn calendar_loop( /// Recovery disables event intake, so unavailable ingress secrets must not /// prevent an operator from inspecting and reconciling retained work. -fn check_event_ingress_keys(runtime: &RuntimeConfig, recovery_only: bool) -> Result<()> { +fn event_ingress_keys( + runtime: &RuntimeConfig, + recovery_only: bool, +) -> Result { if recovery_only { - Ok(()) + Ok(crate::event_trigger::EventKeys::new()) } else { - crate::event_trigger::check_keys(runtime) + crate::event_trigger::resolve_keys(runtime) } } @@ -410,13 +414,13 @@ mod tests { "signingKeyRef":"secret:file/client-key","resource":"urn:example:registry","scopes":["records:read"]}}}, "eventSources":{"registry":{ "source":"urn:example:synthetic-event-source", - "signingKeyRef":"secret:file/unavailable-event-key" + "triggers":{"workflow":{"trigger":{"hmacSha256KeyRef":"secret:file/unavailable-event-key"}}} }} })) .unwrap(); runtime.validate().unwrap(); - assert!(check_event_ingress_keys(&runtime, false).is_err()); - check_event_ingress_keys(&runtime, true).unwrap(); + assert!(event_ingress_keys(&runtime, false).is_err()); + event_ingress_keys(&runtime, true).unwrap(); } fn increment(counter: &AtomicUsize) { diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 143da455cb..03be4ea620 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -51,7 +51,7 @@ enum InspectionBinding<'a> { /// The protected state schema version. It is written once, when apply creates /// the namespace, to `control.schema_version` and to the activation migration /// ledger, and every state transaction fences on it. -pub(crate) const SCHEMA_VERSION: i32 = 6; +pub(crate) const SCHEMA_VERSION: i32 = 7; /// Identifies a namespace whose tables this runtime created and owns. const NAMESPACE_MARKER: &str = "registry-coordinator protected-state"; @@ -719,7 +719,7 @@ impl Store { StoreSecurity { database_id: namespace.to_owned(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32])?, - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -746,11 +746,10 @@ impl Store { let config: tokio_postgres::Config = database_url.parse().map_err(unavailable)?; let local = !config.get_hosts().is_empty() && config.get_hosts().iter().all(|host| match host { + // The name `localhost` is accepted without a pin: a database + // address is checked here by spelling only. tokio_postgres::config::Host::Tcp(name) => { - name == "localhost" - || name - .parse::() - .is_ok_and(|ip| ip.is_loopback()) + registry_platform_httputil::loopback::loopback_host(name).is_some() } #[cfg(unix)] tokio_postgres::config::Host::Unix(_) => true, @@ -3557,15 +3556,15 @@ mod tests { /// every statement that creates the schema, including the shared dispatch /// job table, its product widening, and the activation ledger. #[test] - fn schema_version_6_is_pinned() { + fn schema_version_7_is_pinned() { let mut ddl = schema_statements("coordinator_pin").expect("a valid namespace"); ddl.push(crate::deployment::activation_ledger_statements()); let digest = hex::encode(Sha256::digest(ddl.join("\n"))); assert_eq!( (SCHEMA_VERSION, digest.as_str()), ( - 6, - "c9e4c5df5c2d5f5dfe4a1db6ee69e05f637bc74e98a7a2f2db0bdc42b931ec91" + 7, + "ccc850397a0304baf054aa3315a789ac7889afa953abb3f93a32ccef8d181b48" ), "the protected state schema DDL changed at this SCHEMA_VERSION; {MIGRATION_PIN_RULE}" ); diff --git a/crates/registry-coordinator/src/store/recovery.rs b/crates/registry-coordinator/src/store/recovery.rs index eb7010f1ac..d97e6ed601 100644 --- a/crates/registry-coordinator/src/store/recovery.rs +++ b/crates/registry-coordinator/src/store/recovery.rs @@ -3,6 +3,7 @@ use super::*; use crate::protocol::{AdapterSet, ReconciliationOutcome}; use registry_platform_audit::AuditRequest; +use registry_platform_authcommon::FailedCheck; use serde_json::json; use std::future::Future; @@ -74,20 +75,27 @@ pub struct ProposalWaitsByTurn { pub unobserved: i64, } +/// The bound the authenticator already puts on every identity it admits. +fn bounded_identity(actor: &Actor) -> Result<()> { + if [&actor.issuer, &actor.subject, &actor.client_id] + .iter() + .any(|v| v.is_empty() || v.len() > 512) + { + return Err(refused( + "access.denied", + "verified bounded caller identity is required", + ) + .failing(FailedCheck::TokenClaims)); + } + Ok(()) +} + impl Store { pub fn audit_writer(&self) -> AuditWriter { self.security.audit.clone() } pub(super) fn owner(&self, actor: &Actor) -> Result { - if [&actor.issuer, &actor.subject, &actor.client_id] - .iter() - .any(|v| v.is_empty() || v.len() > 512) - { - return Err(refused( - "access.denied", - "verified bounded caller identity is required", - )); - } + bounded_identity(actor)?; Ok(self.security.keys.commitment( "owner", &[ @@ -127,7 +135,8 @@ impl Store { return Err(refused( "access.denied", "this operation requires the configured operator policy", - )); + ) + .failing(FailedCheck::Operation)); } Ok(()) } @@ -1154,3 +1163,35 @@ impl Store { }).await } } + +#[cfg(test)] +mod tests { + use super::*; + + fn actor(subject: &str, operator: bool) -> Actor { + Actor { + issuer: "https://issuer.example.test".to_owned(), + subject: subject.to_owned(), + client_id: "client".to_owned(), + operator, + } + } + + #[test] + fn a_caller_without_the_operator_policy_is_refused_under_operation() { + let error = Store::operator(&actor("subject", false)).unwrap_err(); + assert_eq!(error.code, "access.denied"); + assert_eq!(error.check, Some(FailedCheck::Operation)); + assert!(Store::operator(&actor("subject", true)).is_ok()); + } + + #[test] + fn an_identity_outside_the_bound_is_refused_under_token_claims() { + for subject in ["", &"s".repeat(513)] { + let error = bounded_identity(&actor(subject, false)).unwrap_err(); + assert_eq!(error.code, "access.denied"); + assert_eq!(error.check, Some(FailedCheck::TokenClaims)); + } + assert!(bounded_identity(&actor(&"s".repeat(512), false)).is_ok()); + } +} diff --git a/crates/registry-coordinator/tests/breg_event_native.rs b/crates/registry-coordinator/tests/breg_event_native.rs index e68a841018..bf62497ba0 100644 --- a/crates/registry-coordinator/tests/breg_event_native.rs +++ b/crates/registry-coordinator/tests/breg_event_native.rs @@ -13,7 +13,7 @@ use registry_breg_client::{ BRegRecordFormat, BRegRecordOptions, }; use registry_coordinator::{deployment, runtime::RuntimeConfig}; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; +use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; use serde_json::{json, Value}; use std::{ path::Path, @@ -23,12 +23,14 @@ use std::{ }; const TARGET: &str = "/v1/events/proposal-event-proof/submitted"; +const OTHER_TARGET: &str = "/v1/events/proposal-event-proof/other-submitted"; const KEY: &[u8] = &[0x5a; 32]; type Delivery = (HeaderMap, Vec, u16); #[derive(Clone, Default)] struct Relay { destination: Arc>>, deliveries: Arc>>, + wrong_trigger: Arc>>, } async fn forward( State(relay): State, @@ -42,7 +44,18 @@ async fn forward( .unwrap() .clone() .expect("ingress started before Submit"); - let response = reqwest::Client::new() + let client = reqwest::Client::new(); + let refused = client + .post(format!("{origin}{OTHER_TARGET}")) + .headers(headers.clone()) + .body(body.clone()) + .send() + .await + .unwrap(); + let status = refused.status().as_u16(); + let problem = refused.json().await.unwrap_or(Value::Null); + *relay.wrong_trigger.lock().unwrap() = Some((status, problem)); + let response = client .post(format!("{origin}{TARGET}")) .headers(headers.clone()) .body(body.clone()) @@ -137,34 +150,13 @@ async fn start(config: &Path, origin: &str) -> Process { } } fn refresh_signature(headers: &mut HeaderMap, body: &[u8]) { - headers.insert( - "x-registry-delivery-time", - chrono::Utc::now() - .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - .parse() - .unwrap(), - ); - let value = |name| headers.get(name).unwrap().to_str().unwrap(); - let signature = sign_v1( - KEY, - SignatureFields { - id: value("ce-id"), - source: value("ce-source"), - event_type: value("ce-type"), - time: value("ce-time"), - data_schema: value("ce-dataschema"), - generation: value("x-registry-event-generation"), - attempt: value("x-registry-delivery-attempt"), - delivery_time: value("x-registry-delivery-time"), - method: "POST", - request_target: TARGET, - content_type: "application/json", - idempotency_key: value("idempotency-key"), - body, - }, - ) - .unwrap(); - headers.insert("x-registry-signature", signature.parse().unwrap()); + headers.remove("content-length"); + let id = headers["webhook-id"].to_str().unwrap(); + let timestamp = chrono::Utc::now().timestamp().try_into().unwrap(); + let keys = DeliveryKeys::new(DeliveryKey::new(KEY).unwrap(), None).unwrap(); + let signature = sign(&keys, id, timestamp, body).unwrap(); + headers.insert("webhook-timestamp", timestamp.to_string().parse().unwrap()); + headers.insert("webhook-signature", signature.parse().unwrap()); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -196,7 +188,7 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority let projection = json!({"type":"object","required":["proposalId","revision","transition"], "properties":{"proposalId":schema["properties"]["proposalId"], "revision":schema["properties"]["revision"],"transition":schema["properties"]["transition"]}}); - let workflow = json!({"apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1","kind":"CoordinatorProject", + let mut workflow = json!({"apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1","kind":"CoordinatorProject", "project":{"id":"proposal-event-proof","version":"1"}, "workflow":{"input":{"type":"object","additionalProperties":false,"required":["proposalId"],"properties":{"proposalId":{"type":"string","format":"uuid"}}}, "eventTriggers":{"submitted":{"source":"registry","eventType":"proposal.submitted","dataSchema":"https://id.registrystack.org/contracts/breg/proposal-event/v1", @@ -204,6 +196,8 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority "input":{"type":"fields","fields":{"proposalId":{"type":"input","path":"/data/proposalId"}}}}}, "deadlineSeconds":300,"start":"observed","steps":{"observed":{"type":"finish","outcome":"observed","output":{"type":"input"}}}, "outcomes":{"observed":{"type":"object","additionalProperties":false,"required":["proposalId"],"properties":{"proposalId":{"type":"string","format":"uuid"}}}}}}); + workflow["workflow"]["eventTriggers"]["other-submitted"] = + workflow["workflow"]["eventTriggers"]["submitted"].clone(); std::fs::write( project.join("workflow.yaml"), serde_norway::to_string(&workflow).unwrap(), @@ -233,6 +227,7 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority ("admission-key", 72), ("audit-key", 73), ("event-key", 0x5a), + ("other-event-key", 0x5b), ] { support::private_file(&root.as_path().join(name), &[byte; 32]); } @@ -254,7 +249,7 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority .remove("notices"); runtime["connections"]["applications"]["profile"] = json!("reader"); runtime["database"] = json!({"runtimeUrlRef":"secret:file/runtime-url","migrationUrlRef":"secret:file/migration-url"}); - runtime["eventSources"] = json!({"registry":{"source":"urn:registrystack:registry:coordinator-action-proof:instance:coordinator-action-proof","signingKeyRef":"secret:file/event-key"}}); + runtime["eventSources"] = json!({"registry":{"source":"urn:registrystack:registry:coordinator-action-proof:instance:coordinator-action-proof","triggers":{"proposal-event-proof":{"submitted":{"hmacSha256KeyRef":"secret:file/event-key"},"other-submitted":{"hmacSha256KeyRef":"secret:file/other-event-key"}}}}}); runtime["deployment"] = json!({"databaseId":"native-event-proof","runtimeRole":role,"packages":[{"root":package,"expectedDigest":digest}], "listener":{"bind":address.to_string(),"tlsTermination":"development-loopback"}, "authentication":{"issuer":issuer.issuer(),"audience":"urn:coordinator:native-event","scopeClaim":"scope","jwksSource":{"type":"uri","uri":issuer.jwks_uri()}, @@ -350,6 +345,17 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority tokio::time::sleep(Duration::from_millis(50)).await; } let (headers, body, status) = relay.deliveries.lock().unwrap()[0].clone(); + let (wrong_status, problem) = relay.wrong_trigger.lock().unwrap().take().unwrap(); + assert_eq!(wrong_status, 401); + assert_eq!(problem["code"], "event.unauthenticated"); + let log = std::fs::read_to_string(config.with_extension("log")).unwrap(); + assert!(log + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .any(|entry| { + entry["fields"]["trace_id"] == problem["traceId"] + && entry["fields"]["failed_check"] == "delivery-signature" + })); assert_eq!(status, 204, "native producer signature passes real ingress"); let event: Value = serde_json::from_slice(&body).unwrap(); assert_eq!(event["data"]["proposalId"], proposal); @@ -405,7 +411,7 @@ async fn native_proposal_event_admits_one_run_without_conferring_apply_authority "authenticated changed event identity conflicts" ); let mut unauthenticated = headers.clone(); - unauthenticated.remove("x-registry-signature"); + unauthenticated.remove("webhook-signature"); assert_eq!( http.post(format!("{origin}{TARGET}")) .headers(unauthenticated) diff --git a/crates/registry-coordinator/tests/calendar_trigger_authoring.rs b/crates/registry-coordinator/tests/calendar_trigger_authoring.rs index e5e97b9e99..ba8bf30bfd 100644 --- a/crates/registry-coordinator/tests/calendar_trigger_authoring.rs +++ b/crates/registry-coordinator/tests/calendar_trigger_authoring.rs @@ -230,7 +230,7 @@ impl Fixture { [0x22; 32], ) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(sink)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(sink)), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/casework_adapter.rs b/crates/registry-coordinator/tests/casework_adapter.rs index 81e07f9387..4187874c8f 100644 --- a/crates/registry-coordinator/tests/casework_adapter.rs +++ b/crates/registry-coordinator/tests/casework_adapter.rs @@ -559,9 +559,9 @@ async fn a_result_read_without_an_accepted_request_or_casework_binding_sends_not .is_empty()); } -fn with_completion(config: &mut RuntimeConfig, root: &std::path::Path, name: &str, token: &str) { - let file = format!("{name}-completion-token"); - support::private_file(&root.join(&file), token.as_bytes()); +fn with_completion(config: &mut RuntimeConfig, root: &std::path::Path, name: &str, key: &[u8]) { + let file = format!("{name}-completion-key"); + support::private_file(&root.join(&file), key); let mut connection = config.connections["review"].clone(); let ConnectionConfig::CaseworkReviewProducer(ref mut binding) = connection else { panic!("Casework binding") @@ -569,7 +569,8 @@ fn with_completion(config: &mut RuntimeConfig, root: &std::path::Path, name: &st binding.result_check_seconds = None; binding.completion = Some(ReviewCompletionConfig { recipient_binding: format!("{name}-v1"), - bearer_token_ref: SecretReference::parse(format!("secret:file/{file}")).unwrap(), + hmac_sha256_key_ref: SecretReference::parse(format!("secret:file/{file}")).unwrap(), + previous_hmac_sha256_key_ref: None, }); config.connections.insert(name.into(), connection); } @@ -599,64 +600,35 @@ async fn completion_fixture() -> (HttpAdapters, tempfile::TempDir) { }, ), ); - with_completion( - &mut config, - root.path(), - "intake", - "completion-token-intake", - ); - with_completion( - &mut config, - root.path(), - "appeals", - "completion-token-shared", - ); - with_completion( - &mut config, - root.path(), - "renewals", - "completion-token-shared", - ); + with_completion(&mut config, root.path(), "intake", &[0x10; 32]); + with_completion(&mut config, root.path(), "appeals", &[0x20; 32]); let adapters = HttpAdapters::new(&config).unwrap(); issuer.stop().await; (adapters, root) } #[tokio::test] -async fn a_completion_names_one_connection_only_for_its_own_token_and_binding() { +async fn a_completion_verifies_only_under_its_own_bindings_key() { + use registry_platform_crypto::delivery_signature::{ + self, DeliveryKey, DeliveryKeys, SignedContent, + }; let (adapters, _root) = completion_fixture().await; - assert_eq!( - adapters - .review_completion("completion-token-intake", "intake-v1") - .as_deref(), - Some("intake") - ); - // Two connections may share a token; the binding still names one. - assert_eq!( - adapters - .review_completion("completion-token-shared", "appeals-v1") - .as_deref(), - Some("appeals") - ); - assert_eq!( - adapters - .review_completion("completion-token-shared", "renewals-v1") - .as_deref(), - Some("renewals") - ); - for (token, recipient) in [ - ("completion-token-intake", "appeals-v1"), - ("completion-token-shared", "intake-v1"), - ("completion-token-intak", "intake-v1"), - ("completion-token-intakee", "intake-v1"), - ("", "intake-v1"), - ("completion-token-intake", ""), - ("completion-token-intake", "intake-v2"), - ] { - assert!(adapters.review_completion(token, recipient).is_none()); - } - // A connection without a completion block accepts no completion at all. - assert!(adapters.review_completion("", "review-v1").is_none()); + let sender = DeliveryKeys::new(DeliveryKey::new(&[0x10; 32]).unwrap(), None).unwrap(); + let signature = delivery_signature::sign(&sender, "event-id", 1_800_000_000, b"{}").unwrap(); + let content = SignedContent { + id: "event-id", + timestamp: "1800000000", + signature: &signature, + body: b"{}", + }; + let (intake, intake_keys) = adapters.review_completion("intake-v1").unwrap(); + assert_eq!(intake, "intake"); + assert!(delivery_signature::verify_authenticity(intake_keys, content).is_ok()); + let (appeals, appeals_keys) = adapters.review_completion("appeals-v1").unwrap(); + assert_eq!(appeals, "appeals"); + assert!(delivery_signature::verify_authenticity(appeals_keys, content).is_err()); + assert!(adapters.review_completion("review-v1").is_none()); + assert!(adapters.review_completion("intake-v2").is_none()); assert_eq!(adapters.observation_interval("review", &completion()), 120); assert_eq!( adapters.observation_interval("intake", &completion()), @@ -664,43 +636,6 @@ async fn a_completion_names_one_connection_only_for_its_own_token_and_binding() ); } -#[tokio::test] -async fn a_completion_token_that_is_not_a_bearer_token_refuses_the_configuration() { - let root = tempfile::tempdir().unwrap(); - let issuer = support::issuer().await; - let mut config = support::config( - root.path(), - &issuer, - "http://127.0.0.1:9", - "http://127.0.0.1:9", - ); - config.connections.insert( - "review".into(), - ConnectionConfig::CaseworkReviewProducer( - registry_coordinator::runtime::CaseworkConnectionConfig { - base_url: "http://127.0.0.1:9".parse().unwrap(), - authorization: config.connections["applications"] - .authorization() - .unwrap() - .clone(), - profile: PROFILE.into(), - producer: PRODUCER.into(), - completion: None, - result_check_seconds: None, - }, - ), - ); - issuer.stop().await; - for token in ["completion token\n", "", "token with space"] { - with_completion(&mut config, root.path(), "intake", token); - let Err(error) = HttpAdapters::new(&config) else { - panic!("a completion token outside the bearer grammar is refused"); - }; - assert_eq!(error.code, "adapter.configuration"); - assert!(!error.to_string().contains("token with space")); - } -} - fn completion() -> CompletionDefinition { CompletionDefinition { kind: CompletionKind::CaseworkResult {}, diff --git a/crates/registry-coordinator/tests/cli_authoring.rs b/crates/registry-coordinator/tests/cli_authoring.rs index d5467fa175..7f1834761b 100644 --- a/crates/registry-coordinator/tests/cli_authoring.rs +++ b/crates/registry-coordinator/tests/cli_authoring.rs @@ -251,7 +251,7 @@ fn init_names_the_project_after_its_directory_and_writes_runtime_in_reading_orde ] ); assert!(runtime.contains("# Offline check reads references")); - let parsed = registry_platform_config::RuntimeConfigLoader::new( + let parsed = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: registry_coordinator::runtime::API_VERSION, kind: registry_coordinator::runtime::KIND, @@ -683,7 +683,7 @@ fn check_locates_a_missing_binding_without_printing_configured_values() { let directory = path.to_str().unwrap(); assert!(cli(&["init", "--directory", directory]).status.success()); let runtime = path.join("runtime.yaml"); - let mut document: Value = registry_platform_config::RuntimeConfigLoader::new( + let mut document: Value = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: registry_coordinator::runtime::API_VERSION, kind: registry_coordinator::runtime::KIND, diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index d4720a5869..60d78830d7 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -412,13 +412,11 @@ async fn assert_bounded_readiness( database: &str, namespace: &str, ) { + let ready = http.get(format!("{origin}/ready")).send().await.unwrap(); + assert_eq!(ready.status(), 200); assert_eq!( - http.get(format!("{origin}/ready")) - .send() - .await - .unwrap() - .status(), - 200 + ready.json::().await.unwrap(), + serde_json::json!({"ready": true, "status": "ready"}) ); let (mut locker, connection) = tokio_postgres::connect(database, tokio_postgres::NoTls) .await @@ -565,8 +563,8 @@ async fn assert_reapply_preserves_schema_and_work( .get(0); assert!(!before["runs"].as_array().unwrap().is_empty()); assert!(!before["jobs"].as_array().unwrap().is_empty()); - assert_eq!(before["ledger"], json!([6])); - assert_eq!(before["schemaVersion"], 6); + assert_eq!(before["ledger"], json!([7])); + assert_eq!(before["schemaVersion"], 7); for _ in 0..2 { deployment::apply(migration, runtime, workflows, &[]) .await @@ -865,7 +863,7 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re assert_eq!(checked["databaseId"], "router-test"); assert_eq!(checked["workflowsDigest"], workflows_digest); assert_eq!(checked["workflows"], json!({"delayed-follow-up": digest})); - assert_eq!(checked["schemaVersion"], 6); + assert_eq!(checked["schemaVersion"], 7); assert_eq!(checked["runtimeRole"], role); assert_eq!(checked["active"]["roleMode"], "split"); status_doc["deployment"]["runtimeRole"] = json!("wrong_runtime_role"); @@ -982,7 +980,7 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re admin .batch_execute(&format!( "ALTER TABLE {namespace}.control DROP CONSTRAINT control_schema_version_check; - UPDATE {namespace}.control SET schema_version=5" + UPDATE {namespace}.control SET schema_version=6" )) .await .unwrap(); @@ -993,8 +991,8 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re ); admin .batch_execute(&format!( - "UPDATE {namespace}.control SET schema_version=6; - ALTER TABLE {namespace}.control ADD CONSTRAINT control_schema_version_check CHECK(schema_version=6)" + "UPDATE {namespace}.control SET schema_version=7; + ALTER TABLE {namespace}.control ADD CONSTRAINT control_schema_version_check CHECK(schema_version=7)" )) .await .unwrap(); @@ -1003,8 +1001,8 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re // write authority all refuse status while plan still reports observation. for (damage, repair) in [ ( - format!("INSERT INTO {namespace}.coordinator_migrations VALUES(7)"), - format!("DELETE FROM {namespace}.coordinator_migrations WHERE version=7"), + format!("INSERT INTO {namespace}.coordinator_migrations VALUES(8)"), + format!("DELETE FROM {namespace}.coordinator_migrations WHERE version=8"), ), ( format!("REVOKE SELECT ON {namespace}.jobs FROM {role}"), @@ -1386,10 +1384,9 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re database_id: "router-test".into(), keys: StateKeys::new(1, BTreeMap::from([(1, state_key)]), admission_key) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(RefuseAcceptedResponse( - attempts.clone(), - "admit", - ))), + audit: AuditWriter::from_line_sink_without_posture(Box::new( + RefuseAcceptedResponse(attempts.clone(), "admit"), + )), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(fs::read(root_path.join("audit-key")).unwrap()), ) @@ -1476,10 +1473,9 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re database_id: "router-test".into(), keys: StateKeys::new(1, BTreeMap::from([(1, state_key)]), admission_key) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(RefuseAcceptedResponse( - status_attempts.clone(), - "status", - ))), + audit: AuditWriter::from_line_sink_without_posture(Box::new( + RefuseAcceptedResponse(status_attempts.clone(), "status"), + )), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(fs::read(root_path.join("audit-key")).unwrap()), ) @@ -4835,6 +4831,14 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in .await .unwrap(); assert_eq!(unadmitted.status(), 403); + // A verified client whose subject its policy does not list. + let unlisted = http + .get(format!("{origin}/v1/runs?limit=10")) + .bearer_auth(f.token("producer-a", "unlisted-subject", "coordinator:start")) + .send() + .await + .unwrap(); + assert_eq!(unlisted.status(), 403); let application = "00000000-0000-4000-8000-0000000000aa"; let (status, run) = start_run( &http, @@ -4855,12 +4859,22 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in ), ( "coordinator_authentication_refusals_total{reason=\"policy\"}", - 1, + 2, ), ( "coordinator_authentication_refusals_total{reason=\"unavailable\"}", 0, ), + // The request counter names the failed check of each refusal. + ( + "coordinator_request_refusals_total{check=\"credential-malformed\"}", + 1, + ), + ("coordinator_request_refusals_total{check=\"scope\"}", 1), + ( + "coordinator_request_refusals_total{check=\"access-profile\"}", + 1, + ), ("coordinator_runs_admitted_total", 1), ("coordinator_dispatch_jobs{state=\"pending\"}", 1), ] { @@ -4872,6 +4886,7 @@ async fn the_metrics_listener_counts_closed_series_and_leaves_the_gauge_stale_in application, "owner-a", "producer-a", + "unlisted-subject", ] { assert!( !body.contains(caller_text), diff --git a/crates/registry-coordinator/tests/deployment_surface.rs b/crates/registry-coordinator/tests/deployment_surface.rs index 033e601677..5153f7938a 100644 --- a/crates/registry-coordinator/tests/deployment_surface.rs +++ b/crates/registry-coordinator/tests/deployment_surface.rs @@ -137,7 +137,7 @@ async fn verified_subject_owns_runs_and_exact_policy_restricts_flow_action() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), @@ -183,7 +183,18 @@ async fn verified_subject_owns_runs_and_exact_policy_restricts_flow_action() { scope, Utc::now().timestamp() + 300, ); - assert!(auth.authenticate(&token).await.is_err()); + let refusal = auth.authenticate(&token).await.err().unwrap(); + // Only a scope refusal declares values, and they come from the + // configuration, never from the token. + match refusal.declared { + Some(declared) => { + assert_eq!(scope, "wrong-scope"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("coordinator:start")); + assert_eq!(declared.access_profile(), None); + } + None => assert_ne!(scope, "wrong-scope"), + } } issuer.stop().await; } @@ -201,7 +212,7 @@ async fn a_policy_admits_only_the_subjects_it_lists() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), @@ -353,7 +364,7 @@ async fn a_token_carrying_act_is_refused_and_an_exchange_without_one_is_not() { let keys = Arc::new(JwksFetcher::new_with_fetch_url_policy( issuer.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifierConfig::access_token_profile( issuer.issuer(), diff --git a/crates/registry-coordinator/tests/http_boundary.rs b/crates/registry-coordinator/tests/http_boundary.rs index cabeff004d..2239e1480e 100644 --- a/crates/registry-coordinator/tests/http_boundary.rs +++ b/crates/registry-coordinator/tests/http_boundary.rs @@ -113,7 +113,7 @@ async fn breg_malformed_success_and_product_refusals_remain_permanent() { ResponseTemplate::new(401) .insert_header("traceparent", TRACE) .insert_header("cache-control", "no-store") - .set_body_raw(json!({"type":"https://id.registrystack.org/problems/registry-breg/authentication/refused", "title":"Unauthorized", "status":401, "detail":"The bearer credential is missing or refused.", "code":"authentication.refused", "traceId":"4bf92f3577b34da6a3ce929d0e0e4736"}).to_string(), "application/problem+json"), + .set_body_raw(json!({"type":"https://id.registrystack.org/problems/registry-breg/authentication/refused", "title":"Unauthorized", "status":401, "detail":"The bearer token or delivery signature was not accepted.", "code":"authentication.refused", "traceId":"4bf92f3577b34da6a3ce929d0e0e4736"}).to_string(), "application/problem+json"), "product-forbidden", ), diff --git a/crates/registry-coordinator/tests/postgres_state.rs b/crates/registry-coordinator/tests/postgres_state.rs index 4c0418333a..1c96eaff1c 100644 --- a/crates/registry-coordinator/tests/postgres_state.rs +++ b/crates/registry-coordinator/tests/postgres_state.rs @@ -2691,7 +2691,7 @@ async fn terminal_retention_keeps_spent_idempotency_keys_across_payload_rotation [0x22; 32], ) .unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2886,7 +2886,7 @@ async fn audit_failure_prevents_admission_and_payload_release() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(Fails)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(Fails)), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2949,7 +2949,7 @@ async fn changing_admission_key_cannot_reopen_a_spent_identity() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x99; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) @@ -2965,7 +2965,7 @@ async fn changing_admission_key_cannot_reopen_a_spent_identity() { StoreSecurity { database_id: h.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x55; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs new file mode 100644 index 0000000000..58ff9383a5 --- /dev/null +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision` without a server: the printed plan and the +//! usage refusals. +use std::{fs, os::unix::fs::PermissionsExt, path::Path, process::Command}; + +const RUNTIME: &str = + include_str!("../../../products/coordinator/examples/single-flow-runtime.yaml"); +const MIGRATION_PASSWORD: &str = "migration-password-canary"; +const RUNTIME_PASSWORD: &str = "runtime-password-canary"; +const ADMIN_URL_VARIABLE: &str = "COORDINATOR_TEST_ADMIN_URL"; +/// Nothing listens here, so a command that reached the connection step would +/// fail with a connection error instead of the loader's refusal. +const ADMIN_URL: &str = + "postgres://admin:admin-password-canary@127.0.0.1:1/postgres?sslmode=verify-full"; + +/// A runtime file the loader accepts, whose database references resolve from +/// the environment the command is given. +fn runtime_file(directory: &Path) -> std::path::PathBuf { + let root = directory.canonicalize().unwrap(); + let secrets = root.join("secrets"); + fs::create_dir(&secrets).unwrap(); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).unwrap(); + let root_pem = secrets.join("postgres-root.pem"); + fs::write(&root_pem, "unused in print mode").unwrap(); + fs::set_permissions(&root_pem, fs::Permissions::from_mode(0o600)).unwrap(); + let path = root.join("runtime.yaml"); + fs::write( + &path, + RUNTIME.replace( + "/run/registry-coordinator/secrets", + secrets.to_str().unwrap(), + ), + ) + .unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + path +} + +fn database_url(user: &str, password: &str) -> String { + format!("postgres://{user}:{password}@db.example.org:5432/coordinator") +} + +/// Runs `provision` with the given database URLs in the environment. `None` +/// leaves the variable unset, so its secret reference cannot resolve. +fn provision_with( + runtime: &Path, + extra: &[&str], + migration_url: Option, + runtime_url: Option, +) -> std::process::Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_coordinatorctl")); + command + .arg("provision") + .arg("--runtime-config") + .arg(runtime) + .args(extra) + .env_remove("COORDINATOR_MIGRATION_URL") + .env_remove("COORDINATOR_DATABASE_URL") + .env(ADMIN_URL_VARIABLE, ADMIN_URL); + if let Some(url) = migration_url { + command.env("COORDINATOR_MIGRATION_URL", url); + } + if let Some(url) = runtime_url { + command.env("COORDINATOR_DATABASE_URL", url); + } + command.output().unwrap() +} + +fn provision(runtime: &Path, extra: &[&str]) -> std::process::Output { + provision_with( + runtime, + extra, + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coordinator_runtime", RUNTIME_PASSWORD)), + ) +} + +/// Asserts a loader refusal: exit 1, nothing on stdout, the code and the +/// pointer on stderr, and no password or URL anywhere. +fn assert_refused(output: &std::process::Output, code: &str, pointer: &str) { + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + assert!(stdout.is_empty(), "a refusal prints no plan: {stdout}"); + assert!(stderr.contains(code), "{stderr}"); + assert!(stderr.contains(pointer), "{stderr}"); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "admin-password-canary", + "postgres://", + ] { + assert!(!stderr.contains(secret), "stderr leaked a secret"); + } +} + +#[test] +fn print_sql_prints_the_plan_without_a_connection_or_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision(&runtime, &["--print-sql"]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stdout}{stderr}"); + assert!( + stdout.contains("CREATE ROLE \"coordinator_migration\""), + "{stdout}" + ); + assert!( + stdout.contains("CREATE ROLE \"coordinator_runtime\""), + "{stdout}" + ); + assert!( + stdout.contains("GRANT CREATE ON DATABASE \"coordinator\" TO \"coordinator_migration\""), + "the migration role creates the namespace schema: {stdout}" + ); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD, "postgres://"] { + assert!(!stdout.contains(secret), "the script leaked a secret"); + assert!(!stderr.contains(secret), "stderr leaked a secret"); + } +} + +#[test] +fn both_administrator_sources_are_a_usage_error() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision( + &runtime, + &[ + "--admin-url-file", + "/nonexistent/admin.url", + "--admin-url-env", + "ADMIN_URL", + ], + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!(output.stdout.is_empty()); + assert!( + stderr.contains("--admin-url"), + "the refusal names the flags: {stderr}" + ); +} + +#[test] +fn an_administrator_source_is_required_unless_printing() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision(&runtime, &[]); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!( + stderr.contains("--admin-url"), + "the refusal names the flags: {stderr}" + ); +} + +#[test] +fn a_runtime_url_user_that_is_not_the_deployment_runtime_role_is_refused_before_connecting() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + // With an administrator URL that could not connect, only the loader's + // refusal explains exit 1 with this code. + let output = provision_with( + &runtime, + &["--admin-url-env", ADMIN_URL_VARIABLE], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coord_rt", RUNTIME_PASSWORD)), + ); + assert_refused( + &output, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("coordinator_runtime"), + "the refusal names the configured role: {stderr}" + ); + assert!( + !stderr.contains("coord_rt:") && !stderr.contains("@db.example.org"), + "the refusal does not echo the URL: {stderr}" + ); + + let printed = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(database_url("coord_rt", RUNTIME_PASSWORD)), + ); + assert_refused( + &printed, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_runtime_url_that_names_no_user_is_refused_as_missing_its_user() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + for url in [ + "postgres://db.example.org:5432/coordinator", + "not a postgresql url", + ] { + let output = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + Some(url.to_owned()), + ); + assert_refused( + &output, + "coordinator.runtime-config.runtime-role-mismatch", + "/database/runtimeUrlRef", + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("names no user"), + "the refusal says the URL has no user: {stderr}" + ); + assert!( + !stderr.contains("does not log in as"), + "a missing user is not reported as another user: {stderr}" + ); + } +} + +/// Every other verb takes `--runtime-config` before or after its name, and +/// `provision` does too. +#[test] +fn the_runtime_file_may_be_given_before_the_verb() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let run = |arguments: &[&std::ffi::OsStr]| { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(arguments) + .env( + "COORDINATOR_MIGRATION_URL", + database_url("coordinator_migration", MIGRATION_PASSWORD), + ) + .env( + "COORDINATOR_DATABASE_URL", + database_url("coordinator_runtime", RUNTIME_PASSWORD), + ) + .output() + .unwrap() + }; + let before = run(&[ + "--runtime-config".as_ref(), + runtime.as_os_str(), + "provision".as_ref(), + "--print-sql".as_ref(), + ]); + let after = run(&[ + "provision".as_ref(), + "--runtime-config".as_ref(), + runtime.as_os_str(), + "--print-sql".as_ref(), + ]); + assert_eq!( + before.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&before.stderr) + ); + assert_eq!(before.stdout, after.stdout, "the same plan either way"); + + let missing = run(&["provision".as_ref(), "--print-sql".as_ref()]); + assert_eq!(missing.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&missing.stderr); + assert!( + stderr.contains("missing required argument") && stderr.contains("provision --help"), + "the usage error says an argument is missing and where to read: {stderr}" + ); +} + +#[test] +fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision_with( + &runtime, + &["--print-sql"], + Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), + None, + ); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn an_unreadable_migration_url_secret_is_refused_without_a_password() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let output = provision_with( + &runtime, + &["--print-sql"], + None, + Some(database_url("coordinator_runtime", RUNTIME_PASSWORD)), + ); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/migrationUrlRef", + ); +} + +#[test] +fn a_certificate_authority_file_that_is_not_text_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + let root_pem = directory.path().join("secrets/postgres-root.pem"); + fs::write(&root_pem, [0xff, 0xfe, 0xfd]).unwrap(); + let output = provision(&runtime, &["--print-sql"]); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/caBundleRef", + ); +} + +#[test] +fn a_missing_certificate_authority_file_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + fs::remove_file(directory.path().join("secrets/postgres-root.pem")).unwrap(); + let output = provision(&runtime, &["--print-sql"]); + assert_refused( + &output, + "coordinator.runtime-config.refused", + "/database/caBundleRef", + ); +} + +#[test] +fn a_runtime_file_the_service_would_refuse_is_refused_with_its_own_diagnostic() { + let directory = tempfile::tempdir().unwrap(); + let runtime = runtime_file(directory.path()); + fs::write(&runtime, "kind: NotARuntimeFile\n").unwrap(); + let output = provision(&runtime, &["--print-sql"]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + assert!(stdout.is_empty(), "{stdout}"); + assert!(!stderr.is_empty()); + assert!(!stderr.contains("postgres://")); +} diff --git a/crates/registry-coordinator/tests/provision_postgres.rs b/crates/registry-coordinator/tests/provision_postgres.rs new file mode 100644 index 0000000000..dbf678250a --- /dev/null +++ b/crates/registry-coordinator/tests/provision_postgres.rs @@ -0,0 +1,329 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `coordinatorctl provision` against a real server, then `apply` and the +//! service on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable superuser URL +//! with `sslmode=verify-full` and `PROVISION_TEST_DATABASE_CA` the +//! PEM file the server certificate chains to: provisioning always uses +//! verified TLS, so the suite's plaintext database cannot serve it. +#![cfg(feature = "postgres-test")] +use chrono::Utc; +use registry_coordinator::{ + adapters::HttpAdapters, + deployment, + http::{self, HttpState}, + project, + runtime::RuntimeConfig, +}; +use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use serde_json::{json, Value}; +use std::{fs, path::Path, process::Command, sync::Arc}; +use uuid::Uuid; + +const DELAYED: &str = "delayed-follow-up"; +const ADMIN_URL_VARIABLE: &str = "COORDINATOR_PROVISION_ADMIN_URL"; + +fn private(path: &Path, bytes: &[u8]) { + use std::os::unix::fs::PermissionsExt; + fs::write(path, bytes).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +fn yaml_value(text: &str, api_version: &str, kind: &str) -> Value { + use registry_platform_yaml::{ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader}; + let versions = [ApiVersion::current(api_version)]; + let format = FormatSpec { + kind, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &versions, + retired_api_versions: &[], + }, + removed_keys: &[], + }; + Reader::new("fixture.yaml") + .read(text.as_bytes(), &Expect::one(&format)) + .unwrap() + .to_json_value() +} + +fn ctl(runtime: &Path, args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(["--format", "json", "--runtime-config"]) + .arg(runtime) + .args(args) + .output() + .unwrap() +} + +fn provision(runtime: &Path, admin_url: &str) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(["--format", "json", "provision", "--runtime-config"]) + .arg(runtime) + .args(["--admin-url-env", ADMIN_URL_VARIABLE]) + .env(ADMIN_URL_VARIABLE, admin_url) + .output() + .unwrap() +} + +struct Names { + migration: String, + runtime: String, + owner: String, + database: String, + namespace: String, +} + +async fn drop_everything(admin: &tokio_postgres::Client, names: &Names) { + for statement in [ + format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", names.database), + format!("DROP ROLE IF EXISTS {}", names.runtime), + format!("DROP ROLE IF EXISTS {}", names.migration), + format!("DROP ROLE IF EXISTS {}", names.owner), + ] { + admin.batch_execute(&statement).await.unwrap(); + } +} + +/// The administrator is a role that can only create roles and databases, the +/// way a managed server's admin is, never the server's superuser. +#[tokio::test] +async fn provision_then_apply_then_serve_with_a_namespace_schema() { + let (superuser_url, ca_pem) = provision_test_env(); + let superuser = connect_verified(&superuser_url, &ca_pem, None).await; + let suffix = Uuid::new_v4().simple().to_string()[..12].to_owned(); + let names = Names { + migration: format!("coord_mig_{suffix}"), + runtime: format!("coord_run_{suffix}"), + owner: format!("coord_own_{suffix}"), + database: format!("coord_db_{suffix}"), + namespace: format!("coordinator_{suffix}"), + }; + let owner_password = Uuid::new_v4().simple().to_string(); + superuser + .batch_execute(&format!( + "CREATE ROLE {} LOGIN CREATEROLE CREATEDB NOSUPERUSER PASSWORD '{owner_password}'", + names.owner + )) + .await + .unwrap(); + let outcome = tokio::spawn(run( + superuser_url.clone(), + ca_pem.clone(), + owner_password, + Names { + migration: names.migration.clone(), + runtime: names.runtime.clone(), + owner: names.owner.clone(), + database: names.database.clone(), + namespace: names.namespace.clone(), + }, + )) + .await; + drop_everything(&superuser, &names).await; + outcome.unwrap(); +} + +async fn run(superuser_url: String, ca_pem: Vec, owner_password: String, names: Names) { + let mut endpoint = url::Url::parse(&superuser_url).unwrap(); + let (host, port) = ( + endpoint.host_str().unwrap().to_owned(), + endpoint.port().unwrap(), + ); + endpoint.set_username(&names.owner).unwrap(); + endpoint.set_password(Some(&owner_password)).unwrap(); + let admin_url = endpoint.to_string(); + + let root = tempfile::tempdir().unwrap(); + let root_path = root.path().canonicalize().unwrap(); + let project_path = root_path.join("project"); + project::init(&project_path, Some(DELAYED)).unwrap(); + let package_path = root_path.join("package"); + let digest = deployment::package(&project_path, &package_path).unwrap(); + let (migration_password, runtime_password) = ( + Uuid::new_v4().simple().to_string(), + Uuid::new_v4().simple().to_string(), + ); + private( + &root_path.join("migration-url"), + format!( + "postgres://{}:{migration_password}@{host}:{port}/{}?sslmode=require", + names.migration, names.database + ) + .as_bytes(), + ); + private( + &root_path.join("runtime-url"), + format!( + "postgres://{}:{runtime_password}@{host}:{port}/{}?sslmode=require", + names.runtime, names.database + ) + .as_bytes(), + ); + private(&root_path.join("ca.pem"), &ca_pem); + for (name, byte) in [("state-key", 71), ("admission-key", 72), ("audit-key", 73)] { + private(&root_path.join(name), &[byte; 32]); + } + for name in ["reader-jwk", "notices-jwk"] { + private( + &root_path.join(name), + registry_platform_testing::fixtures::ED25519_PRIVATE_JWK.as_bytes(), + ); + } + let issuer = TestAuthorizationServer::builder() + .with_signing_key(generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap()) + .client(TestClient::new("producer")) + .start() + .await; + let template = include_str!("../../../products/coordinator/examples/single-flow-runtime.yaml"); + let mut doc = yaml_value( + template, + registry_coordinator::runtime::API_VERSION, + registry_coordinator::runtime::KIND, + ); + doc["namespace"] = json!(names.namespace); + doc["secretProviders"]["file"]["root"] = json!(&root_path); + doc["database"]["runtimeUrlRef"] = json!("secret:file/runtime-url"); + doc["database"]["migrationUrlRef"] = json!("secret:file/migration-url"); + doc["database"]["caBundleRef"] = json!("secret:file/ca.pem"); + let d = &mut doc["deployment"]; + d["databaseId"] = json!("provision-test"); + d["runtimeRole"] = json!(names.runtime); + d["packages"] = json!([{"root":package_path,"expectedDigest":digest}]); + d["listener"] = json!({"bind":"127.0.0.1:0","tlsTermination":"development-loopback"}); + d["auditFile"] = json!(root_path.join("audit.jsonl")); + d["stateKeys"] = json!({"1":{"keyRef":"secret:file/state-key"}}); + d["admissionKeyRef"] = json!("secret:file/admission-key"); + d["auditKeyRef"] = json!("secret:file/audit-key"); + d["authentication"] = json!({"issuer":issuer.issuer(),"audience":"urn:coordinator:test","scopeClaim":"scope","jwksSource":{"type":"uri","uri":issuer.jwks_uri()},"policies":{"producer":{"subjects":["owner-a"],"requiredScopes":["coordinator:start"],"workflows":[DELAYED],"actions":["start","status"]}}}); + let path = root_path.join("runtime.yaml"); + fs::write(&path, serde_norway::to_string(&doc).unwrap()).unwrap(); + + // The first run creates both roles, the database and the grant that lets + // `apply` create the namespace schema. + let output = provision(&path, &admin_url); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stdout}{stderr}"); + let report: Value = serde_json::from_str(&stdout).unwrap(); + let outcome = |report: &Value, step: &str| { + report["statements"] + .as_array() + .unwrap() + .iter() + .find(|s| s["step"] == step) + .map(|s| s["outcome"].clone()) + }; + assert_eq!(outcome(&report, "role.migration"), Some("created".into())); + assert_eq!(outcome(&report, "role.runtime"), Some("created".into())); + assert_eq!(outcome(&report, "database.create"), Some("created".into())); + assert!( + outcome(&report, "database.grant-create").is_some(), + "{stdout}" + ); + assert_eq!(report["executed"], true); + for secret in [ + migration_password.as_str(), + runtime_password.as_str(), + owner_password.as_str(), + "postgres://", + ] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "the output leaked a secret" + ); + } + + // A second run finds everything present. + let output = provision(&path, &admin_url); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(outcome(&report, "database.create"), Some("present".into())); + assert_eq!(outcome(&report, "role.runtime"), Some("present".into())); + + // `apply` creates the namespace schema as the migration role. + let output = ctl(&path, &["apply"]); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + + // The runtime role holds CONNECT on the database and nothing else there. + let database_admin = connect_verified(&superuser_url, &ca_pem, Some(&names.database)).await; + let schema_owner: String = database_admin + .query_one( + "SELECT pg_get_userbyid(nspowner) FROM pg_namespace WHERE nspname = $1", + &[&names.namespace], + ) + .await + .unwrap() + .get(0); + assert_eq!(schema_owner, names.migration); + let (connect_privilege, create_privilege): (bool, bool) = { + let row = database_admin + .query_one( + "SELECT has_database_privilege($1, $2, 'CONNECT'), has_database_privilege($1, $2, 'CREATE')", + &[&names.runtime, &names.database], + ) + .await + .unwrap(); + (row.get(0), row.get(1)) + }; + assert!(connect_privilege); + assert!(!create_privilege); + + // The service runs as the runtime role and answers a route. + let runtime = Arc::new(RuntimeConfig::load(&path).unwrap()); + let workflows = + Arc::new(deployment::load_workflows(deployment::config(&runtime).unwrap()).unwrap()); + let store = deployment::open(&runtime, false).await.unwrap(); + // The serving check the service runs at startup and on every `/ready`. + deployment::check_serving(&store, &runtime, workflows.digest()) + .await + .unwrap(); + let authenticator = Arc::new( + deployment::config(&runtime) + .unwrap() + .authentication + .authenticator(&runtime.secret_providers, true) + .await + .unwrap(), + ); + let state = HttpState { + recovery_only: false, + store, + runtime: runtime.clone(), + workflows, + authenticator, + adapters: Arc::new(HttpAdapters::new(&runtime).unwrap()), + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, http::router(state)).await.unwrap(); + }); + let token = issuer.issue_access_token( + "producer", + "owner-a", + "urn:coordinator:test", + "coordinator:start", + Utc::now().timestamp() + 300, + ); + let response = reqwest::Client::new() + .get(format!("{origin}/v1/workflows/{DELAYED}")) + .bearer_auth(token) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let contract: Value = response.json().await.unwrap(); + assert!(contract["workflowRevision"].is_string()); + server.abort(); +} diff --git a/crates/registry-coordinator/tests/read_in_force_adapter.rs b/crates/registry-coordinator/tests/read_in_force_adapter.rs index a129db6c7f..7bc29be6f3 100644 --- a/crates/registry-coordinator/tests/read_in_force_adapter.rs +++ b/crates/registry-coordinator/tests/read_in_force_adapter.rs @@ -186,7 +186,7 @@ async fn a_refused_read_is_a_failure_never_none_in_force() { 401, "authentication.refused", "Unauthorized", - "The bearer credential is missing or refused.", + "The bearer token or delivery signature was not accepted.", ), "product-forbidden", ), diff --git a/crates/registry-coordinator/tests/read_in_force_postgres.rs b/crates/registry-coordinator/tests/read_in_force_postgres.rs index 5d65a64236..b7cba8d1a7 100644 --- a/crates/registry-coordinator/tests/read_in_force_postgres.rs +++ b/crates/registry-coordinator/tests/read_in_force_postgres.rs @@ -120,7 +120,7 @@ async fn two_records_in_force_hold_the_run_until_an_operator_retries() { database_id: namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]) .expect("test keys"), - audit: AuditWriter::from_line_sink(Box::new(std::io::sink())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), audit_profile: AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( vec![0x33; 32], )) diff --git a/crates/registry-coordinator/tests/read_lease_recovery.rs b/crates/registry-coordinator/tests/read_lease_recovery.rs index e5cd7b74fb..35dc5674ae 100644 --- a/crates/registry-coordinator/tests/read_lease_recovery.rs +++ b/crates/registry-coordinator/tests/read_lease_recovery.rs @@ -142,7 +142,7 @@ impl Harness { database_id: namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]) .expect("test keys"), - audit: AuditWriter::from_line_sink(Box::new(capture.clone())), + audit: AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())), audit_profile: AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(vec![0x33; 32]), ) diff --git a/crates/registry-coordinator/tests/recovery_audit.rs b/crates/registry-coordinator/tests/recovery_audit.rs index 946b4dd761..26edc4cbc4 100644 --- a/crates/registry-coordinator/tests/recovery_audit.rs +++ b/crates/registry-coordinator/tests/recovery_audit.rs @@ -99,7 +99,7 @@ impl Harness { StoreSecurity { database_id: self.namespace.clone(), keys: StateKeys::new(1, BTreeMap::from([(1, [0x11; 32])]), [0x22; 32]).unwrap(), - audit: AuditWriter::from_line_sink(Box::new(sink)), + audit: AuditWriter::from_line_sink_without_posture(Box::new(sink)), audit_profile: profile(), }, None, diff --git a/crates/registry-coordinator/tests/review_wait_postgres.rs b/crates/registry-coordinator/tests/review_wait_postgres.rs index fb376d88ed..60e91ceb2a 100644 --- a/crates/registry-coordinator/tests/review_wait_postgres.rs +++ b/crates/registry-coordinator/tests/review_wait_postgres.rs @@ -15,6 +15,7 @@ use registry_coordinator::{ store::{Actor, Store}, worker::Worker, }; +use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; use serde_json::{json, Value}; use std::{ collections::VecDeque, @@ -33,7 +34,8 @@ const REQUEST: &str = "6f1d4c1e-2b7a-4c55-9a3e-1d2c3b4a5f60"; const RESULT: &str = "0b9e8d7c-6a5f-4e3d-8c2b-1a0f9e8d7c6b"; const MESSAGE: &str = "3c2b1a0f-9e8d-4c7b-a6f5-e4d3c2b1a0f9"; const APPLICATION: &str = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"; -const TOKEN: &str = "synthetic-completion-token-canary-0123456789abcdef"; +const KEY: &[u8] = &[0xa7; 32]; +const OLD_KEY: &[u8] = &[0x31; 32]; const RECIPIENT: &str = "coordinator-v1"; const FUNCTIONS: &str = include_str!("fixtures/review-wait/functions.rhai"); @@ -116,6 +118,7 @@ fn result(status: &str) -> Value { } struct Fake { + completion_keys: DeliveryKeys, reads: Mutex>, cancel_results: Mutex>, read_count: AtomicUsize, @@ -144,6 +147,7 @@ impl Fake { release: Option, ) -> Self { Self { + completion_keys: keys(KEY, None), reads: Mutex::new(reads.into()), cancel_results: Mutex::new(cancel_results.into()), read_count: AtomicUsize::new(0), @@ -248,8 +252,8 @@ impl AdapterSet for Fake { 900 } - fn review_completion(&self, token: &str, recipient: &str) -> Option { - (token == TOKEN && recipient == RECIPIENT).then(|| "review".to_owned()) + fn review_completion(&self, recipient: &str) -> Option<(&str, &DeliveryKeys)> { + (recipient == RECIPIENT).then_some(("review", &self.completion_keys)) } } @@ -454,21 +458,28 @@ impl Harness { } } -fn completion_headers(token: &str, recipient: &str, event: Uuid) -> HeaderMap { +fn keys(current: &[u8], previous: Option<&[u8]>) -> DeliveryKeys { + DeliveryKeys::new( + DeliveryKey::new(current).unwrap(), + previous.map(|key| DeliveryKey::new(key).unwrap()), + ) + .unwrap() +} + +fn completion_headers(keys: &DeliveryKeys, recipient: &str, event: Uuid, body: &[u8]) -> HeaderMap { let mut headers = HeaderMap::new(); - headers.insert( - "authorization", - HeaderValue::from_str(&format!("Bearer {token}")).unwrap(), - ); - headers.insert( - "registry-recipient-binding", - HeaderValue::from_str(recipient).unwrap(), - ); - headers.insert("content-type", HeaderValue::from_static("application/json")); - headers.insert( - "idempotency-key", - HeaderValue::from_str(&event.to_string()).unwrap(), - ); + let id = event.to_string(); + let timestamp = Utc::now().timestamp().try_into().unwrap(); + let signature = sign(keys, &id, timestamp, body).unwrap(); + for (name, value) in [ + ("registry-recipient-binding", recipient), + ("content-type", "application/json"), + ("webhook-id", &id), + ("webhook-timestamp", ×tamp.to_string()), + ("webhook-signature", &signature), + ] { + headers.insert(name, HeaderValue::from_str(value).unwrap()); + } headers } @@ -486,11 +497,12 @@ fn completion_body(event: Uuid, request: &str) -> Vec { /// Deliver one authentic completion event for `request`. async fn complete(h: &Harness, adapters: &dyn AdapterSet, request: &str) -> StatusCode { let event = Uuid::new_v4(); + let body = completion_body(event, request); receive_review_completion( &h.store, adapters, - &completion_headers(TOKEN, RECIPIENT, event), - Some(&completion_body(event, request)), + &completion_headers(&keys(KEY, None), RECIPIENT, event, &body), + Some(&body), ) .await .status() @@ -640,6 +652,64 @@ async fn an_event_for_an_unknown_request_is_accepted_and_changes_nothing() { assert!(h.due_in(run).await.unwrap() > before - 5.0); } +#[tokio::test] +async fn a_repeated_completion_wakes_one_wait_once() { + let h = harness(true).await; + let fake = Fake::new(vec![ + CompletionObservation::Pending { retry_after: None }, + CompletionObservation::Settled(result("approved")), + ]); + let worker = Worker::new(h.store.clone(), fake.clone()); + let run = h.admit().await; + h.drain(&worker).await; + let event = Uuid::new_v4(); + let body = completion_body(event, REQUEST); + let headers = completion_headers(&keys(KEY, None), RECIPIENT, event, &body); + for _ in 0..2 { + assert_eq!( + receive_review_completion(&h.store, fake.as_ref(), &headers, Some(&body)) + .await + .status(), + StatusCode::NO_CONTENT + ); + } + assert!(h.wait_row(run).await.unwrap().woken); + h.make_due(run).await; + h.drain(&worker).await; + assert_eq!(fake.reads(), 2); + assert!(h.wait_row(run).await.is_none()); + assert_eq!( + receive_review_completion(&h.store, fake.as_ref(), &headers, Some(&body)) + .await + .status(), + StatusCode::NO_CONTENT + ); + h.drain(&worker).await; + assert_eq!(fake.reads(), 2); +} + +#[tokio::test] +async fn a_completion_signed_during_rotation_wakes_the_wait() { + let h = harness(true).await; + let fake = Arc::new(Fake { + completion_keys: keys(KEY, Some(OLD_KEY)), + ..Fake::with(vec![], vec![], false, None) + }); + let worker = Worker::new(h.store.clone(), fake.clone()); + let run = h.admit().await; + h.drain(&worker).await; + let event = Uuid::new_v4(); + let body = completion_body(event, REQUEST); + let headers = completion_headers(&keys(OLD_KEY, None), RECIPIENT, event, &body); + assert_eq!( + receive_review_completion(&h.store, fake.as_ref(), &headers, Some(&body)) + .await + .status(), + StatusCode::NO_CONTENT + ); + assert!(h.wait_row(run).await.unwrap().woken); +} + #[tokio::test] async fn an_inauthentic_or_malformed_event_is_refused_and_wakes_nothing() { let h = harness(true).await; @@ -651,37 +721,33 @@ async fn an_inauthentic_or_malformed_event_is_refused_and_wakes_nothing() { let body = completion_body(event, REQUEST); let mut cases: Vec<(&str, HeaderMap, Option>, StatusCode)> = vec![ ( - "a forged token", - completion_headers( - "another-synthetic-token-canary-0123456789", - RECIPIENT, - event, - ), + "a forged signature", + completion_headers(&keys(&[0x90; 32], None), RECIPIENT, event, &body), Some(body.clone()), StatusCode::UNAUTHORIZED, ), ( "another recipient", - completion_headers(TOKEN, "another-recipient", event), + completion_headers(&keys(KEY, None), "another-recipient", event, &body), Some(body.clone()), StatusCode::UNAUTHORIZED, ), ( "a replayed body under another event key", - completion_headers(TOKEN, RECIPIENT, Uuid::new_v4()), + completion_headers(&keys(KEY, None), RECIPIENT, Uuid::new_v4(), &body), Some(body.clone()), StatusCode::BAD_REQUEST, ), ]; - let mut missing = completion_headers(TOKEN, RECIPIENT, event); - missing.remove("authorization"); + let mut missing = completion_headers(&keys(KEY, None), RECIPIENT, event, &body); + missing.remove("webhook-signature"); cases.push(( - "no credential", + "no signature", missing, Some(body.clone()), StatusCode::UNAUTHORIZED, )); - let mut text = completion_headers(TOKEN, RECIPIENT, event); + let mut text = completion_headers(&keys(KEY, None), RECIPIENT, event, &body); text.insert("content-type", HeaderValue::from_static("text/plain")); cases.push(( "another media type", @@ -695,7 +761,11 @@ async fn an_inauthentic_or_malformed_event_is_refused_and_wakes_nothing() { assert_eq!(response.status(), expected, "{case}"); assert_eq!(response.headers()["cache-control"], "no-store", "{case}"); if expected == StatusCode::UNAUTHORIZED { - assert_eq!(response.headers()["www-authenticate"], "Bearer", "{case}"); + assert_eq!( + response.headers()["www-authenticate"], + "Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"", + "{case}" + ); } assert_eq!( response.headers()["content-type"], @@ -715,10 +785,15 @@ async fn an_inauthentic_or_malformed_event_is_refused_and_wakes_nothing() { }; assert_eq!(problem["code"], code, "{case}"); assert_eq!(problem["status"], expected.as_u16(), "{case}"); - assert!( - !problem.to_string().contains("canary"), - "a refusal repeats no credential: {case}" - ); + let response_body = problem.to_string(); + for name in ["webhook-signature", "webhook-id"] { + if let Some(value) = headers.get(name) { + assert!( + !response_body.contains(value.to_str().unwrap()), + "a refusal omits {name}: {case}" + ); + } + } } assert!(!h.wait_row(run).await.unwrap().woken); let due = h.due_in(run).await.unwrap(); diff --git a/crates/registry-coordinator/tests/runtime_config.rs b/crates/registry-coordinator/tests/runtime_config.rs index fabf017f38..342bd5545a 100644 --- a/crates/registry-coordinator/tests/runtime_config.rs +++ b/crates/registry-coordinator/tests/runtime_config.rs @@ -1548,11 +1548,11 @@ fn runtime_definition_maps_refuse_separator_lookalikes_at_both_keys() { document["eventSources"] = json!({ "event-source": { "source": "urn:example:coordinator:event-source:one", - "signingKeyRef": "secret:file/event-key" + "triggers": {} }, "event_source": { "source": "urn:example:coordinator:event-source:two", - "signingKeyRef": "secret:file/event-key" + "triggers": {} } }); let text = serde_norway::to_string(&document).unwrap(); @@ -1620,7 +1620,7 @@ fn runtime_connection_and_event_source_namespaces_remain_distinct() { document["eventSources"] = json!({ "shared_name": { "source": "urn:example:coordinator:event-source:one", - "signingKeyRef": "secret:file/event-key" + "triggers": {} } }); load(&serde_norway::to_string(&document).unwrap()) @@ -1846,7 +1846,7 @@ fn with_review_connection() -> Value { }, "completion": { "recipientBinding": "coordinator-v1", - "bearerTokenRef": "secret:file/review-completion-token" + "hmacSha256KeyRef": "secret:file/reviewed-notice-completion-key" }, "resultCheckSeconds": 900 }); @@ -1897,8 +1897,8 @@ fn reviewed_notice_runtime_receives_completions_for_its_review_connection_on_the let completion = review.completion.as_ref().unwrap(); assert_eq!(completion.recipient_binding, "coordinator-v1"); assert_eq!( - completion.bearer_token_ref.as_str(), - "secret:file/review-completion-token" + completion.hmac_sha256_key_ref.as_str(), + "secret:file/reviewed-notice-completion-key" ); assert!(config.connections["notices"] .product_binding() @@ -1997,7 +1997,7 @@ fn casework_connections_name_a_producer_profile_and_bounded_result_checks_offlin .remove("file"); let error = refused(&disabled.to_string()); assert!( - finding_at(&error, "/connections/review/completion/bearerTokenRef") + finding_at(&error, "/connections/review/completion/hmacSha256KeyRef") .contains("secretProviders") ); @@ -2081,8 +2081,8 @@ fn casework_binding_identity_pins_the_producer_but_not_delivery_settings() { // rotate the token, rename the recipient or tune result checks without // stranding runs admitted under the earlier settings. let mut delivery = original.clone(); - delivery["connections"]["review"]["completion"]["bearerTokenRef"] = - json!("secret:file/another-completion-token"); + delivery["connections"]["review"]["completion"]["hmacSha256KeyRef"] = + json!("secret:file/another-completion-key"); delivery["connections"]["review"]["completion"]["recipientBinding"] = json!("coordinator-v2"); delivery["connections"]["review"]["resultCheckSeconds"] = json!(60); assert_eq!( @@ -2304,7 +2304,7 @@ fn generated_runtime_schema_keeps_event_source_identifier_bounds() { .with_draft(jsonschema::Draft::Draft202012) .compile(&fragment) .unwrap(); - let source = json!({"source":"urn:test:producer", "signingKeyRef":"secret:file/event-key"}); + let source = json!({"source":"urn:test:producer", "triggers":{}}); assert!(validator.is_valid(&json!({"registry":source}))); for key in ["Invalid", "../registry", "", "123"] { let invalid = json!({(key):source}); @@ -2395,3 +2395,338 @@ fn breg_proposal_follow_settings_are_bounded_and_outside_the_binding_digest() { } const VALID_ID: &str = "018f2f9e-5d7a-7c3b-9a1e-2b3c4d5e6f70"; + +#[test] +fn an_event_source_signing_key_names_its_replacement() { + let mut document = yaml_value(RUNTIME).unwrap(); + document["eventSources"] = json!({ + "registry": { + "source": "urn:example:coordinator:registry", + "signingKeyRef": "secret:file/event-key" + } + }); + let error = refused(&document.to_string()); + let removed = error + .diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .expect("the obsolete event source key must be refused"); + assert_eq!(removed.path, "/eventSources/registry/signingKeyRef"); + assert!(removed + .suggested_action + .contains("eventSources..triggers...hmacSha256KeyRef")); +} + +#[test] +fn a_completion_bearer_token_names_its_replacement() { + let mut document = with_review_connection(); + let completion = document["connections"]["review"]["completion"] + .as_object_mut() + .unwrap(); + let reference = completion.remove("hmacSha256KeyRef").unwrap(); + completion.insert("bearerTokenRef".into(), reference); + let error = refused(&document.to_string()); + let diagnostic = finding_at(&error, "/connections/review/completion/bearerTokenRef"); + assert!(diagnostic.contains("config.removed-key")); + assert!(diagnostic.contains("hmacSha256KeyRef")); +} + +fn event_source() -> Value { + json!({"source":"urn:example:registry","triggers":{ + "delayed-follow-up":{ + "saved":{"hmacSha256KeyRef":"secret:file/event-key"} + } + }}) +} + +#[test] +fn an_explicit_null_previous_key_is_refused() { + let mut document = with_review_connection(); + document["eventSources"] = json!({"registry":event_source()}); + for (route, path) in [ + ( + "/eventSources/registry/triggers/delayed-follow-up/saved", + "/eventSources/registry/triggers/delayed-follow-up/saved/previousHmacSha256KeyRef", + ), + ( + "/connections/review/completion", + "/connections/review/completion/previousHmacSha256KeyRef", + ), + ] { + let mut invalid = document.clone(); + invalid.pointer_mut(route).unwrap()["previousHmacSha256KeyRef"] = Value::Null; + finding_at(&refused(&invalid.to_string()), path); + } +} + +#[test] +fn a_trigger_without_a_key_is_refused_with_its_path() { + let mut document = yaml_value(RUNTIME).unwrap(); + document["eventSources"] = json!({"registry":event_source()}); + let config = load(&document.to_string()).unwrap(); + let project = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/coordinator/examples/delayed-follow-up"); + let mut workflow = Definition::load(&project).unwrap().workflow.clone(); + workflow.event_triggers.insert( + "missing".into(), + serde_json::from_value(json!({ + "source":"registry", "eventType":"record.created", "dataSchema":"urn:example:event", + "event":{"type":"object"}, "input":{"type":"literal","value":{}} + })) + .unwrap(), + ); + let error = config.validate_workflow(&workflow).unwrap_err(); + assert_eq!( + error.field.as_deref(), + Some( + format!( + "/eventSources/registry/triggers/{}/missing/hmacSha256KeyRef", + workflow.id + ) + .as_str() + ) + ); +} + +#[test] +fn a_key_for_an_undeployed_trigger_is_refused() { + use registry_coordinator::deployment::{load_workflows, package}; + let root = tempfile::tempdir().unwrap(); + let project = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/coordinator/examples/delayed-follow-up"); + let package_root = root.path().canonicalize().unwrap().join("package"); + let digest = package(&project, &package_root).unwrap(); + let mut document = yaml_value(SINGLE_FLOW).unwrap(); + document["deployment"]["packages"] = json!([{"root":package_root,"expectedDigest":digest}]); + document["eventSources"] = json!({"registry":event_source()}); + let config = load(&document.to_string()).unwrap(); + let workflows = load_workflows(config.deployment.as_ref().unwrap()).unwrap(); + let error = workflows.validate(&config).unwrap_err(); + assert_eq!( + error.field.as_deref(), + Some("/eventSources/registry/triggers/delayed-follow-up/saved/hmacSha256KeyRef") + ); +} + +fn with_ingress_keys(document: &mut Value, root: &std::path::Path, key: &[u8]) { + use registry_platform_testing::fixtures::ED25519_PRIVATE_JWK; + let root = root.canonicalize().unwrap(); + document["secretProviders"]["file"]["root"] = json!(root); + document["eventSources"] = json!({"registry":event_source()}); + write_ingress_secret(&root, "event-key", key); + write_ingress_secret(&root, "client-key", ED25519_PRIVATE_JWK.as_bytes()); +} + +fn write_ingress_secret(root: &std::path::Path, name: &str, bytes: &[u8]) { + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; + let path = root.join(name); + fs::write(&path, bytes).unwrap(); + #[cfg(unix)] + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); +} + +fn startup_error(document: &Value) -> registry_coordinator::CoordinatorError { + let config = load(&document.to_string()).unwrap(); + match registry_coordinator::adapters::HttpAdapters::new(&config) { + Ok(_) => panic!("startup must refuse the ingress keys"), + Err(error) => error, + } +} + +const TRIGGER_KEY_PATH: &str = + "eventSources.registry.triggers.delayed-follow-up.saved.hmacSha256KeyRef"; + +const COMPLETION_KEY_PATH: &str = "connections.review.completion.hmacSha256KeyRef"; +const OTHER_TRIGGER_PATH: &str = "eventSources.registry.triggers.delayed-follow-up.other"; + +fn shared_key_message(first: &str, second: &str) -> String { + format!("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there.") +} + +#[test] +fn two_triggers_sharing_key_bytes_are_refused_naming_both_paths() { + let root = tempfile::tempdir().unwrap(); + let mut document = yaml_value(RUNTIME).unwrap(); + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + write_ingress_secret(root.path(), "other-key", &[0x78; 32]); + document["eventSources"]["registry"]["triggers"]["delayed-follow-up"]["other"] = + json!({"hmacSha256KeyRef":"secret:file/other-key"}); + assert_eq!( + startup_error(&document).message, + shared_key_message( + &format!("{OTHER_TRIGGER_PATH}.hmacSha256KeyRef"), + TRIGGER_KEY_PATH + ), + ); +} + +#[test] +fn a_triggers_previous_key_equal_to_another_triggers_current_key_is_refused() { + let root = tempfile::tempdir().unwrap(); + let mut document = yaml_value(RUNTIME).unwrap(); + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + write_ingress_secret(root.path(), "other-key", &[0x79; 32]); + write_ingress_secret(root.path(), "old-key", &[0x78; 32]); + document["eventSources"]["registry"]["triggers"]["delayed-follow-up"]["other"] = json!({"hmacSha256KeyRef":"secret:file/other-key","previousHmacSha256KeyRef":"secret:file/old-key"}); + assert_eq!( + startup_error(&document).message, + shared_key_message( + &format!("{OTHER_TRIGGER_PATH}.previousHmacSha256KeyRef"), + TRIGGER_KEY_PATH + ), + ); +} + +#[test] +fn a_trigger_key_equal_to_a_completion_key_is_refused() { + let root = tempfile::tempdir().unwrap(); + let mut document = with_review_connection(); + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + write_ingress_secret(root.path(), "completion-key", &[0x78; 32]); + document["connections"]["review"]["completion"]["hmacSha256KeyRef"] = + json!("secret:file/completion-key"); + assert_eq!( + startup_error(&document).message, + shared_key_message(TRIGGER_KEY_PATH, COMPLETION_KEY_PATH) + ); +} + +fn ingress_binding(document: &mut Value, completion: bool) -> &mut Value { + if completion { + &mut document["connections"]["review"]["completion"] + } else { + &mut document["eventSources"]["registry"]["triggers"]["delayed-follow-up"]["saved"] + } +} + +#[test] +fn a_previous_key_equal_to_its_current_key_names_the_rotation_steps() { + for completion in [false, true] { + let root = tempfile::tempdir().unwrap(); + let mut document = if completion { + with_review_connection() + } else { + yaml_value(RUNTIME).unwrap() + }; + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + write_ingress_secret(root.path(), "current-key", &[0x79; 32]); + write_ingress_secret(root.path(), "old-key", &[0x79; 32]); + let binding = ingress_binding(&mut document, completion); + binding["hmacSha256KeyRef"] = json!("secret:file/current-key"); + binding["previousHmacSha256KeyRef"] = json!("secret:file/old-key"); + let current = if completion { + COMPLETION_KEY_PATH + } else { + TRIGGER_KEY_PATH + }; + let previous = current.replace(".hmacSha256KeyRef", ".previousHmacSha256KeyRef"); + let error = startup_error(&document); + assert_eq!(error.suggested_action.as_deref(), Some(format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}." + ).as_str())); + } +} + +#[test] +fn missing_ingress_keys_explain_how_to_restore_them() { + assert_ingress_resolution_failure( + "the referenced secret is unavailable", + "Create the secret under the configured provider, or correct the name.", + |_| {}, + ); +} + +#[cfg(unix)] +#[test] +fn group_readable_ingress_keys_explain_how_to_secure_them() { + use registry_platform_config::SecretError; + use std::os::unix::fs::PermissionsExt; + assert_ingress_resolution_failure( + "the referenced secret file is unsafe", + SecretError::UnsafeFile(registry_platform_config::SecretFileCheck::GroupAccess) + .suggested_action(), + |root| { + write_ingress_secret(root, "refused-key", &[0x79; 32]); + fs::set_permissions(root.join("refused-key"), fs::Permissions::from_mode(0o640)) + .unwrap(); + }, + ); +} + +fn assert_ingress_resolution_failure( + reason: &str, + action: &str, + prepare: impl Fn(&std::path::Path), +) { + for completion in [false, true] { + let root = tempfile::tempdir().unwrap(); + let mut document = if completion { + with_review_connection() + } else { + yaml_value(RUNTIME).unwrap() + }; + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + prepare(root.path()); + ingress_binding(&mut document, completion)["hmacSha256KeyRef"] = + json!("secret:file/refused-key"); + let path = if completion { + COMPLETION_KEY_PATH + } else { + TRIGGER_KEY_PATH + }; + let error = startup_error(&document); + assert_eq!( + error.suggested_action.as_deref(), + Some(format!("{path} could not be resolved: {reason}. {action}").as_str()) + ); + } +} + +#[test] +fn a_65_byte_completion_key_is_refused_as_connection_configuration() { + let root = tempfile::tempdir().unwrap(); + let mut document = with_review_connection(); + with_ingress_keys(&mut document, root.path(), &[0x78; 32]); + write_ingress_secret(root.path(), "completion-key", &[0x79; 65]); + ingress_binding(&mut document, true)["hmacSha256KeyRef"] = json!("secret:file/completion-key"); + let error = startup_error(&document); + assert_eq!(error.code, "adapter.configuration"); + assert_eq!( + error.field.as_deref(), + Some("/connections/review/completion/hmacSha256KeyRef") + ); + assert_eq!( + error.suggested_action.as_deref(), + Some( + format!("{COMPLETION_KEY_PATH} resolved to 65 bytes. Supply 32 to 64 exact key bytes.") + .as_str() + ) + ); +} + +#[test] +fn a_65_byte_key_ending_in_a_newline_names_its_length_and_the_newline() { + let root = tempfile::tempdir().unwrap(); + let mut document = yaml_value(RUNTIME).unwrap(); + let mut key = vec![b'x'; 64]; + key.push(b'\n'); + with_ingress_keys(&mut document, root.path(), &key); + let error = startup_error(&document); + let advice = error.suggested_action.as_deref().unwrap(); + assert!(advice.contains(TRIGGER_KEY_PATH)); + assert!(advice.contains("65 bytes")); + assert!(advice.contains("newline")); + assert!(!advice.contains(&"x".repeat(64))); +} + +#[test] +fn a_verification_key_the_receiver_cannot_use_is_refused_at_startup() { + let root = tempfile::tempdir().unwrap(); + let mut document = yaml_value(RUNTIME).unwrap(); + with_ingress_keys(&mut document, root.path(), b"short"); + let error = startup_error(&document); + let advice = error.suggested_action.as_deref().unwrap(); + assert!(advice.contains(TRIGGER_KEY_PATH)); + assert!(advice.contains("5 bytes")); +} diff --git a/crates/registry-coordinator/tests/scheduling_event_native.rs b/crates/registry-coordinator/tests/scheduling_event_native.rs index ec65578a4c..91e9da72e8 100644 --- a/crates/registry-coordinator/tests/scheduling_event_native.rs +++ b/crates/registry-coordinator/tests/scheduling_event_native.rs @@ -13,7 +13,7 @@ use registry_coordinator::{ deployment, problem::ProblemCode as CoordinatorProblemCode, runtime::RuntimeConfig, }; use registry_platform_canonical_json::canonicalize_json; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; +use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; use registry_scheduling_client::{ AdmissionRequest, CancelAppointmentRequest, CreateAppointmentRequest, ProblemCode, RescheduleAppointmentRequest, SchedulingClientError, @@ -363,7 +363,17 @@ async fn coordinator( for (name, byte) in [("state-key", 81), ("admission-key", 82), ("audit-key", 83)] { support::private_file(&root.join(name), &[byte; 32]); } - support::private_file(&root.join("event-key"), support::scheduling::HOOK_KEY); + let trigger_keys: serde_json::Map<_, _> = support::scheduling::EVENT_KEYS + .iter() + .map(|(trigger, key)| { + let file = format!("{trigger}-key"); + support::private_file(&root.join(&file), key); + ( + trigger.to_string(), + json!({"hmacSha256KeyRef":format!("secret:file/{file}")}), + ) + }) + .collect(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); drop(listener); @@ -378,7 +388,7 @@ async fn coordinator( runtime["database"] = json!({"runtimeUrlRef":"secret:file/runtime-url","migrationUrlRef":"secret:file/migration-url"}); runtime["eventSources"] = json!({"scheduling":{ "source":format!("urn:registrystack:scheduling:{}", support::scheduling::SCHEDULING_ID), - "signingKeyRef":"secret:file/event-key" + "triggers":{"scheduling-lifecycle":trigger_keys} }}); runtime["deployment"] = json!({ "databaseId":format!("coordinator-scheduling-{}", uuid::Uuid::new_v4().simple()), @@ -510,10 +520,12 @@ async fn wait_for_delivery(relay: &Relay, event_type: &str) -> Delivery { .lock() .unwrap() .iter() - .find(|(_, headers, _, _, _)| { - headers - .get("ce-type") - .is_some_and(|value| value == event_type) + .find(|(_, headers, body, _, _)| { + serde_json::from_slice::(body).is_ok_and(|envelope| { + headers.get("webhook-id").and_then(|id| id.to_str().ok()) + == envelope["id"].as_str() + && envelope["type"] == event_type + }) }) .cloned() { @@ -528,34 +540,20 @@ async fn wait_for_delivery(relay: &Relay, event_type: &str) -> Delivery { } fn refresh_signature(headers: &mut HeaderMap, body: &[u8], target: &str) { - headers.insert( - "x-registry-delivery-time", - Utc::now() - .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - .parse() - .unwrap(), - ); - let value = |name| headers.get(name).unwrap().to_str().unwrap(); - let signature = sign_v1( - support::scheduling::HOOK_KEY, - SignatureFields { - id: value("ce-id"), - source: value("ce-source"), - event_type: value("ce-type"), - time: value("ce-time"), - data_schema: value("ce-dataschema"), - generation: value("x-registry-event-generation"), - attempt: value("x-registry-delivery-attempt"), - delivery_time: value("x-registry-delivery-time"), - method: "POST", - request_target: target, - content_type: "application/json", - idempotency_key: value("idempotency-key"), - body, - }, + headers.remove("content-length"); + let id = headers["webhook-id"].to_str().unwrap(); + let timestamp = chrono::Utc::now().timestamp().try_into().unwrap(); + let keys = DeliveryKeys::new( + DeliveryKey::new(support::scheduling::event_key( + target.rsplit('/').next().unwrap(), + )) + .unwrap(), + None, ) .unwrap(); - headers.insert("x-registry-signature", signature.parse().unwrap()); + let signature = sign(&keys, id, timestamp, body).unwrap(); + headers.insert("webhook-timestamp", timestamp.to_string().parse().unwrap()); + headers.insert("webhook-signature", signature.parse().unwrap()); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -690,7 +688,7 @@ async fn native_scheduling_lifecycle_drives_one_message_per_signed_event() { "duplicate event does not repeat Messaging" ); let mut unsigned = headers.clone(); - unsigned.remove("x-registry-signature"); + unsigned.remove("webhook-signature"); assert_eq!( http.post(format!("{coordinator_origin}{target}")) .headers(unsigned) @@ -702,15 +700,14 @@ async fn native_scheduling_lifecycle_drives_one_message_per_signed_event() { reqwest::StatusCode::UNAUTHORIZED ); let mut wrong_source = headers.clone(); - wrong_source.insert( - "ce-source", - "urn:registrystack:scheduling:untrusted".parse().unwrap(), - ); - refresh_signature(&mut wrong_source, &body, &target); + let mut wrong_envelope: Value = serde_json::from_slice(&body).unwrap(); + wrong_envelope["source"] = json!("urn:registrystack:scheduling:untrusted"); + let wrong_body = canonicalize_json(&wrong_envelope).unwrap(); + refresh_signature(&mut wrong_source, &wrong_body, &target); assert_eq!( http.post(format!("{coordinator_origin}{target}")) .headers(wrong_source) - .body(body) + .body(wrong_body) .send() .await .unwrap() @@ -801,8 +798,8 @@ async fn native_signed_scheduling_confirmation_drives_one_deduplicated_message() *relay.destination.lock().unwrap() = Some(coordinator_origin.clone()); let scheduling = Scheduling::start_with_signed_reminders( &relay_origin, - REMINDER_CONFIRMATION_TARGET, - None, + REMINDER_TARGET, + Some(REMINDER_CONFIRMATION_TARGET), None, ) .await; diff --git a/crates/registry-coordinator/tests/static_key_set.rs b/crates/registry-coordinator/tests/static_key_set.rs new file mode 100644 index 0000000000..8994e2485d --- /dev/null +++ b/crates/registry-coordinator/tests/static_key_set.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The static key set behind `deployment.authentication.jwksSource` loads +//! through the authenticator the server builds, and a refused set names the +//! key file's own problem at startup. +use registry_coordinator::access::{AccessConfig, Action, ClientPolicy}; +use registry_platform_config::{ + FileSecretProviderConfig, JwksSource, OidcIssuerConfig, SecretProvidersConfig, +}; +use registry_platform_testing::TokenSigner; +use registry_platform_yaml::Url; +use serde_json::{json, Value}; +use std::{collections::BTreeMap, fs, os::unix::fs::PermissionsExt}; + +const KEY_FILE: &str = "issuer-keys.json"; + +/// The corpus signer's public keys a static document may hold: RSA and EC +/// only, so its EdDSA key is left out. +fn public_keys() -> Value { + let mut keys = TokenSigner::new().public_key_set(); + keys["keys"] + .as_array_mut() + .unwrap() + .retain(|key| key["kty"] != "OKP"); + keys +} + +async fn build(document: &Value) -> Result<(), registry_coordinator::CoordinatorError> { + let root = tempfile::tempdir().unwrap(); + let root_path = root.path().canonicalize().unwrap(); + let file = root_path.join(KEY_FILE); + fs::write(&file, document.to_string()).unwrap(); + fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); + let secrets = SecretProvidersConfig { + file: Some(FileSecretProviderConfig { root: root_path }), + environment: None, + }; + let access = AccessConfig { + issuer: OidcIssuerConfig { + issuer: Url::new("https://issuer.example.test".to_owned()).unwrap(), + audience: "urn:coordinator:test".to_owned(), + jwks_source: JwksSource::Static { + document_ref: format!("secret:file/{KEY_FILE}"), + }, + allow_insecure_http: false, + }, + assertion_issuers: BTreeMap::new(), + scope_claim: "scope".to_owned(), + policies: BTreeMap::from([( + "journey-app".to_owned(), + ClientPolicy { + subjects: vec!["subject".to_owned()], + required_scopes: vec!["coordinator:start".to_owned()], + workflows: vec!["follow-up".to_owned()], + actions: vec![Action::Start], + operator: false, + }, + )]), + }; + access.authenticator(&secrets, false).await.map(|_| ()) +} + +#[tokio::test] +async fn a_public_key_set_with_an_ext_member_loads() { + let mut keys = public_keys(); + keys["keys"][0]["ext"] = json!(true); + build(&keys).await.expect("a public key set with ext loads"); +} + +#[tokio::test] +async fn a_key_set_holding_a_private_member_is_refused_with_the_key_files_own_text() { + let mut keys = public_keys(); + keys["keys"][0]["d"] = json!("AQAB"); + let error = match build(&keys).await { + Ok(()) => panic!("a key set with a private member is refused"), + Err(error) => error, + }; + assert_eq!(error.code, "access.configuration"); + assert!( + error.message.contains("static key set"), + "the refusal names the key set, not the issuer or policies: {}", + error.message + ); + assert!( + !error.message.contains("AQAB"), + "the refusal carries no key material: {}", + error.message + ); +} diff --git a/crates/registry-coordinator/tests/support/mod.rs b/crates/registry-coordinator/tests/support/mod.rs index 98a13e569f..d25b26659a 100644 --- a/crates/registry-coordinator/tests/support/mod.rs +++ b/crates/registry-coordinator/tests/support/mod.rs @@ -88,6 +88,7 @@ pub fn config( migration_url_ref: "secret:env/COORDINATOR_TEST_DATABASE_URL".into(), ca_bundle_ref: None, test_only_plaintext: false, + transport: None, }, namespace: format!("coordinator_{}", uuid::Uuid::new_v4().simple()), connections: BTreeMap::from([ diff --git a/crates/registry-coordinator/tests/support/scheduling.rs b/crates/registry-coordinator/tests/support/scheduling.rs index e8ed65693f..e9b9a08239 100644 --- a/crates/registry-coordinator/tests/support/scheduling.rs +++ b/crates/registry-coordinator/tests/support/scheduling.rs @@ -21,7 +21,20 @@ use serde_json::json; pub const AUDIENCE: &str = "urn:registry-scheduling:coordinator-lifecycle"; pub const CLIENT: &str = "lifecycle-agent"; -pub const HOOK_KEY: &[u8] = &[0x6b; 32]; +pub const EVENT_KEYS: [(&str, [u8; 32]); 5] = [ + ("confirmed", [0x6b; 32]), + ("rescheduled", [0x6c; 32]), + ("cancelled", [0x6d; 32]), + ("reminder", [0x6e; 32]), + ("reminder-confirmation", [0x6f; 32]), +]; + +pub fn event_key(trigger: &str) -> &'static [u8] { + EVENT_KEYS + .iter() + .find_map(|(name, key)| (*name == trigger).then_some(key.as_slice())) + .expect("synthetic trigger key") +} pub const SCHEDULING_ID: &str = "coordinator-lifecycle"; fn binary(variable: &str) -> PathBuf { @@ -135,7 +148,9 @@ impl Scheduling { &root.path().join("audit-key"), b"synthetic-scheduling-audit-key-32", ); - super::private_file(&root.path().join("hook-key"), HOOK_KEY); + for (trigger, key) in &EVENT_KEYS { + super::private_file(&root.path().join(format!("{trigger}-key")), key); + } let signing_key = generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap(); super::private_file( &root.path().join("jwks"), @@ -148,19 +163,21 @@ impl Scheduling { drop(listener); let path = root.path().join("scheduling-runtime.yaml"); let mut destinations = json!({"hooks":{ - "confirmed":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/confirmed"),"hmacSha256KeyRef":"secret:file/hook-key","maximumAttempts":1}, - "rescheduled":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/rescheduled"),"hmacSha256KeyRef":"secret:file/hook-key","maximumAttempts":1}, - "cancelled":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/cancelled"),"hmacSha256KeyRef":"secret:file/hook-key","maximumAttempts":1} + "confirmed":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/confirmed"),"hmacSha256KeyRef":"secret:file/confirmed-key","maximumAttempts":1}, + "rescheduled":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/rescheduled"),"hmacSha256KeyRef":"secret:file/rescheduled-key","maximumAttempts":1}, + "cancelled":{"url":format!("{relay_origin}/v1/events/scheduling-lifecycle/cancelled"),"hmacSha256KeyRef":"secret:file/cancelled-key","maximumAttempts":1} }}); if let Some(reminder_path) = reminder_path { let mut reminder_destination = json!({ "url":format!("{relay_origin}{reminder_path}"), - "hmacSha256KeyRef":"secret:file/hook-key" + "hmacSha256KeyRef":"secret:file/reminder-key" }); if let Some(confirmation_path) = confirmation_path { - reminder_destination["purposeUrls"] = json!({ - "confirmation":format!("{relay_origin}{confirmation_path}"), - "reminder":format!("{relay_origin}{reminder_path}") + reminder_destination["purposes"] = json!({ + "confirmation":{ + "url":format!("{relay_origin}{confirmation_path}"), + "hmacSha256KeyRef":"secret:file/reminder-confirmation-key" + } }); } destinations["reminders"] = reminder_destination; diff --git a/crates/registry-coordinator/tests/support/state_schema.rs b/crates/registry-coordinator/tests/support/state_schema.rs index c2e1d8bd23..68ff2cbf9c 100644 --- a/crates/registry-coordinator/tests/support/state_schema.rs +++ b/crates/registry-coordinator/tests/support/state_schema.rs @@ -51,7 +51,7 @@ async fn a_second_migration_changes_no_schema_object_or_protected_row() { assert_eq!(catalog(&h).await, before, "the second migration ran DDL"); assert_eq!(restored_current_job(&h, run).await, job); assert_eq!(restored_lease_identity(&h, run).await, identity); - assert_eq!(h.store.doctor().await.unwrap().schema_version, 6); + assert_eq!(h.store.doctor().await.unwrap().schema_version, 7); } #[tokio::test] diff --git a/crates/registry-discovery-client/src/client.rs b/crates/registry-discovery-client/src/client.rs index 174214164d..42431c4c49 100644 --- a/crates/registry-discovery-client/src/client.rs +++ b/crates/registry-discovery-client/src/client.rs @@ -14,7 +14,7 @@ use registry_platform_canonical_json::parse_json_strict; use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::header::{ACCEPT, CONTENT_TYPE}; use reqwest::{Method, StatusCode}; use serde::de::DeserializeOwned; @@ -257,7 +257,7 @@ impl DiscoveryClient { .send() .await .map_err(|error| DiscoveryClientError::transport(send_failure_kind(&error)))?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| DiscoveryClientError::Protocol)?; let status = response.status(); if status.is_success() && status != StatusCode::OK { diff --git a/crates/registry-discovery/src/cli.rs b/crates/registry-discovery/src/cli.rs new file mode 100644 index 0000000000..947723f471 --- /dev/null +++ b/crates/registry-discovery/src/cli.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The `discovery` command line, shared by the process entry point and the +//! generated CLI reference. + +use std::path::PathBuf; + +use clap::{CommandFactory, Parser}; + +/// Arguments of the `discovery` process. +#[derive(Debug, Parser)] +#[command( + name = "discovery", + about = "Serve one immutable Registry Discovery index", + version = crate::build_info::DISPLAY_VERSION +)] +pub struct Arguments { + /// Runtime configuration file. + #[arg(long = "runtime-config", value_name = "ABSOLUTE_FILE")] + pub runtime_config: PathBuf, +} + +/// The clap command tree, for the generated CLI reference. +#[must_use] +pub fn command() -> clap::Command { + Arguments::command() +} diff --git a/crates/registry-discovery/src/lib.rs b/crates/registry-discovery/src/lib.rs index 20daccd56d..2fce0fd7e5 100644 --- a/crates/registry-discovery/src/lib.rs +++ b/crates/registry-discovery/src/lib.rs @@ -17,6 +17,8 @@ pub mod build_info { include!(concat!(env!("OUT_DIR"), "/product_build_info.rs")); } +#[cfg(feature = "server")] +pub mod cli; pub mod model; pub mod openapi; #[cfg(feature = "server")] diff --git a/crates/registry-discovery/src/main.rs b/crates/registry-discovery/src/main.rs index 94febc44a6..4c3836b36c 100644 --- a/crates/registry-discovery/src/main.rs +++ b/crates/registry-discovery/src/main.rs @@ -1,25 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 //! Registry Discovery process entry point. -use std::path::PathBuf; - use clap::Parser; +use registry_discovery::cli::Arguments; use registry_discovery::{load_runtime, serve, LogLevel}; use tracing_subscriber::filter::{LevelFilter, Targets}; use tracing_subscriber::prelude::*; -#[derive(Debug, Parser)] -#[command( - name = "discovery", - about = "Serve one immutable Registry Discovery index", - version = registry_discovery::build_info::DISPLAY_VERSION -)] -struct Arguments { - /// Runtime configuration file. - #[arg(long = "runtime-config", value_name = "ABSOLUTE_FILE")] - runtime_config: PathBuf, -} - #[tokio::main] async fn main() { let arguments = Arguments::parse(); diff --git a/crates/registry-discovery/src/runtime_config.rs b/crates/registry-discovery/src/runtime_config.rs index c2311d03ed..7b932b5a84 100644 --- a/crates/registry-discovery/src/runtime_config.rs +++ b/crates/registry-discovery/src/runtime_config.rs @@ -169,7 +169,7 @@ pub enum LogLevel { /// retired apiVersions. #[must_use] pub const fn runtime_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RUNTIME_ENVELOPE) .removed_keys(REMOVED_RUNTIME_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() diff --git a/crates/registry-discovery/src/server.rs b/crates/registry-discovery/src/server.rs index b0251b7615..d765f2cf2a 100644 --- a/crates/registry-discovery/src/server.rs +++ b/crates/registry-discovery/src/server.rs @@ -12,7 +12,7 @@ use axum::middleware; use axum::routing::{get, post}; use axum::Router; use registry_platform_canonical_json::parse_json_strict; -use registry_platform_httpsec::{security_headers, CspBuilder}; +use registry_platform_httpsec::{security_headers_without_posture, CspBuilder}; use serde::de::DeserializeOwned; use serde::Serialize; use thiserror::Error; @@ -179,7 +179,7 @@ pub fn router( }, ), ) - .layer(security_headers(CspBuilder::restrictive()))) + .layer(security_headers_without_posture(CspBuilder::restrictive()))) } async fn enforce_http_limits( diff --git a/crates/registry-discoveryctl/src/build.rs b/crates/registry-discoveryctl/src/build.rs index 04902f2236..67a85630d2 100644 --- a/crates/registry-discoveryctl/src/build.rs +++ b/crates/registry-discoveryctl/src/build.rs @@ -11,7 +11,9 @@ use registry_discovery::{ MAXIMUM_PACKAGE_DEPTH, MAXIMUM_PACKAGE_FILES, PACKAGE_COMMAND, }; use registry_platform_config::{write_package, PackageError, PackageLimits, VerifiedPackage}; -use registry_platform_httputil::{read_bounded, validate_response_headers, FetchUrlPolicy}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, FetchUrlPolicy, +}; use reqwest::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; use sha2::{Digest as _, Sha256}; use thiserror::Error; @@ -162,7 +164,7 @@ async fn fetch_origins( fetch_timeout: Duration, ) -> Result<(Vec, Vec), BuildError> { let policy = if allow_loopback { - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() } else { FetchUrlPolicy::strict() }; @@ -183,7 +185,8 @@ async fn fetch_origins( .send() .await .map_err(|_| BuildError::Fetch)?; - validate_response_headers(response.headers()).map_err(|_| BuildError::Fetch)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| BuildError::Fetch)?; if response.status() != reqwest::StatusCode::OK || !exact_profile_media_type(response.headers()) || response diff --git a/crates/registry-discoveryctl/src/lib.rs b/crates/registry-discoveryctl/src/lib.rs index cce03ba7bd..1da0b33cc9 100644 --- a/crates/registry-discoveryctl/src/lib.rs +++ b/crates/registry-discoveryctl/src/lib.rs @@ -6,7 +6,7 @@ use std::io; use std::path::PathBuf; use std::process::{Command as ProcessCommand, ExitCode}; -use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum}; +use clap::{ArgGroup, Args, CommandFactory, Parser, Subcommand, ValueEnum}; use registry_platform_yaml::{Diagnostic, Report}; use serde_json::{json, Value}; @@ -49,6 +49,12 @@ struct Arguments { command: Command, } +/// The clap command tree, for the generated CLI reference. +#[must_use] +pub fn command() -> clap::Command { + Arguments::command() +} + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)] enum OutputFormat { /// Diagnostics with their position first, then a summary line. @@ -85,7 +91,7 @@ enum Command { /// directory, and every runtime file beside them. #[arg(long, value_name = "DIRECTORY")] project: Option, - /// One runtime file, checked on its own. + /// Runtime configuration file, checked on its own. #[arg(long, value_name = "FILE")] runtime_config: Option, /// One index file, as `discoveryctl package` wrote it, checked on @@ -108,10 +114,14 @@ enum Command { }, /// Fetch every enabled approved origin once and write one immutable package. Package { - #[arg(long)] + /// The authoring project directory: origins.yaml, the mappings + /// directory, and every runtime file beside them. + #[arg(long, value_name = "DIRECTORY")] project: PathBuf, - #[arg(long)] + /// The new directory the package is written to. + #[arg(long, value_name = "DIRECTORY")] output: PathBuf, + /// Accept an http loopback catalog URL, for development. #[arg(long)] allow_loopback: bool, /// Optional operator revision recorded in the package envelope. diff --git a/crates/registry-documents-client/src/client.rs b/crates/registry-documents-client/src/client.rs index d4705c4c89..34ed862761 100644 --- a/crates/registry-documents-client/src/client.rs +++ b/crates/registry-documents-client/src/client.rs @@ -17,7 +17,8 @@ use registry_platform_httputil::client::{ MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, BoundedReadError, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, + BoundedReadError, }; use registry_platform_yaml::Digest; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE}; @@ -31,6 +32,7 @@ use crate::{DocumentsClientError, DocumentsProtocolFailure}; const JSON_MEDIA_TYPE: &str = "application/json"; const PROBLEM_MEDIA_TYPE: &str = "application/problem+json"; const MAXIMUM_PROBLEM_BYTES: u64 = 8 * 1024; +const MAXIMUM_PROBE_BYTES: u64 = 4096; const DEFAULT_MAXIMUM_RESPONSE_BYTES: u64 = 4 * 1024 * 1024; const MAXIMUM_RESPONSE_BYTES: u64 = 16 * 1024 * 1024; const DEFAULT_MAXIMUM_DOWNLOAD_BYTES: u64 = 16 * 1024 * 1024; @@ -271,7 +273,8 @@ impl DocumentsClient { }) } - /// Whether the process answers at all. + /// Whether the process answers at all. The answer is 200 with an empty + /// body or a JSON object of at most 4096 bytes whose members are ignored. pub async fn health(&self) -> Result, DocumentsClientError> { let url = self.url(HEALTH_PATH, &[])?; let response = @@ -283,16 +286,16 @@ impl DocumentsClient { kind: send_failure_kind(&error), })?; let status = response.status(); - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(status, DocumentsProtocolFailure::HeaderBounds, None))?; if status != StatusCode::OK { return Err(problem_or_status(response).await); } let trace_id = response_trace(status, response.headers())?; - // The health answer has no body, so any byte is a protocol failure - // rather than a response the caller's bound was too small for. - match read_bounded(response, 0).await { - Ok(_) => {} + // The probe answers an empty body or a small JSON object. Its members + // are not read: the status code is the answer. + let body = match read_bounded(response, MAXIMUM_PROBE_BYTES).await { + Ok(body) => body, Err( BoundedReadError::ContentLengthExceeded { .. } | BoundedReadError::BodyTooLarge { .. }, @@ -308,6 +311,18 @@ impl DocumentsClient { kind: read_failure_kind(&error), }) } + }; + if !body.is_empty() + && !matches!( + serde_json::from_slice::(&body), + Ok(serde_json::Value::Object(_)) + ) + { + return Err(protocol( + status, + DocumentsProtocolFailure::Body, + Some(trace_id), + )); } Ok(DocumentsComplete { value: (), @@ -682,7 +697,7 @@ impl DocumentsClient { .map_err(|error| DocumentsClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), DocumentsProtocolFailure::HeaderBounds, diff --git a/crates/registry-documents-client/tests/http_boundary.rs b/crates/registry-documents-client/tests/http_boundary.rs index bb3922a7c2..12810930cf 100644 --- a/crates/registry-documents-client/tests/http_boundary.rs +++ b/crates/registry-documents-client/tests/http_boundary.rs @@ -183,3 +183,64 @@ async fn a_healthy_answer_with_a_body_is_a_protocol_failure() { ); server.abort(); } + +fn json_probe(body: String) -> Response { + ( + StatusCode::OK, + [ + (CONTENT_TYPE, "application/json"), + ( + axum::http::header::HeaderName::from_static("traceparent"), + TRACEPARENT, + ), + ], + body, + ) + .into_response() +} + +#[tokio::test] +async fn a_healthy_answer_with_a_json_object_body_is_accepted() { + let (client, server) = client_for(|| { + json_probe(r#"{"status":"ready","posture":"production","developmentSettings":[]}"#.into()) + }) + .await; + let complete = client.health().await.expect("a JSON object probe body"); + assert_eq!(complete.trace_id, TRACE_ID); + server.abort(); +} + +#[tokio::test] +async fn a_healthy_answer_with_a_json_body_that_is_not_an_object_is_a_protocol_failure() { + let (client, server) = client_for(|| json_probe("[1]".into())).await; + let error = client.health().await.unwrap_err(); + assert!( + matches!( + error, + DocumentsClientError::Protocol { + failure: DocumentsProtocolFailure::Body, + .. + } + ), + "{error:?}" + ); + server.abort(); +} + +#[tokio::test] +async fn a_healthy_answer_with_an_oversized_json_body_is_a_protocol_failure() { + let (client, server) = + client_for(|| json_probe(format!(r#"{{"note":"{}"}}"#, "a".repeat(8 * 1024)))).await; + let error = client.health().await.unwrap_err(); + assert!( + matches!( + error, + DocumentsClientError::Protocol { + failure: DocumentsProtocolFailure::Body, + .. + } + ), + "{error:?}" + ); + server.abort(); +} diff --git a/crates/registry-documents-core/src/project.rs b/crates/registry-documents-core/src/project.rs index 874f22232b..87ac3882cb 100644 --- a/crates/registry-documents-core/src/project.rs +++ b/crates/registry-documents-core/src/project.rs @@ -345,6 +345,9 @@ pub enum ActorKind { } impl ActorKind { + /// Every actor kind, so a caller that sweeps the kinds follows a new one. + pub const ALL: [Self; 2] = [Self::Service, Self::Human]; + /// The spelling the project and the store use. #[must_use] pub const fn as_str(self) -> &'static str { diff --git a/crates/registry-documents-core/tests/actor_kind_all.rs b/crates/registry-documents-core/tests/actor_kind_all.rs new file mode 100644 index 0000000000..16b0f28327 --- /dev/null +++ b/crates/registry-documents-core/tests/actor_kind_all.rs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `ActorKind::ALL` lists every actor kind. + +use registry_documents_core::ActorKind; + +/// An exhaustive match: a new kind fails to compile here until it is handled, +/// which is the reminder to list it in `ActorKind::ALL`. +fn listed(kind: ActorKind) -> bool { + match kind { + ActorKind::Service | ActorKind::Human => ActorKind::ALL.contains(&kind), + } +} + +#[test] +fn every_actor_kind_is_listed_once() { + assert!(listed(ActorKind::Service)); + assert!(listed(ActorKind::Human)); + assert_eq!(ActorKind::ALL.len(), 2); +} diff --git a/crates/registry-documents/Cargo.toml b/crates/registry-documents/Cargo.toml index 8d3e3c5f94..40fbdc314a 100644 --- a/crates/registry-documents/Cargo.toml +++ b/crates/registry-documents/Cargo.toml @@ -52,6 +52,16 @@ name = "restore_drill" path = "tests/restore_drill.rs" required-features = ["postgres-test"] +[[test]] +name = "refusal_golden" +path = "tests/refusal_golden.rs" +required-features = ["postgres-test"] + +[[test]] +name = "refusal_key_source" +path = "tests/refusal_key_source.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = [] @@ -79,7 +89,7 @@ jsonwebtoken.workspace = true registry-documents-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true @@ -110,7 +120,8 @@ aws-lc-rs.workspace = true base64.workspace = true jsonschema.workspace = true registry-documents-client.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins"] } +registry-platform-crypto.workspace = true +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-documents/migrations/0101_activation_posture.sql b/crates/registry-documents/migrations/0101_activation_posture.sql new file mode 100644 index 0000000000..7307045007 --- /dev/null +++ b/crates/registry-documents/migrations/0101_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE documents_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE documents_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-documents/src/activation.rs b/crates/registry-documents/src/activation.rs index 3bbfdb1bc6..52798881de 100644 --- a/crates/registry-documents/src/activation.rs +++ b/crates/registry-documents/src/activation.rs @@ -580,15 +580,15 @@ async fn apply_begun( let activation = platform::append_activation( &*tx, &layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, package_digest, database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; @@ -649,18 +649,24 @@ pub async fn check_runtime( return Err(ActivationError::LedgerUnreadable); } crate::store::check_activation_schema(&**client).await?; - let active = platform::check_active_package(&**client, &layout(), database_id, package_digest) - .await - .map_err(|error| match error { - platform::ActivePackageError::NotActivated => ActivationError::NotActivated, - platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, - platform::ActivePackageError::PackageNotActive { .. } => { - ActivationError::PackageNotActive - } - platform::ActivePackageError::Activation(error) => { - ActivationError::Store(platform_error(error)) - } - })?; + let active = platform::check_active_package_without_posture( + &**client, + &layout(), + database_id, + package_digest, + ) + .await + .map_err(|error| match error { + platform::ActivePackageError::NotActivated => ActivationError::NotActivated, + platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, + platform::ActivePackageError::PackageNotActive { .. } => ActivationError::PackageNotActive, + // Until this product declares a posture it checks as production, + // so a ledger recorded in development is not its active package. + platform::ActivePackageError::PostureMismatch { .. } => ActivationError::PackageNotActive, + platform::ActivePackageError::Activation(error) => { + ActivationError::Store(platform_error(error)) + } + })?; crate::store::schema_ready(&client).await?; let role = observe(&**client, None) .await? diff --git a/crates/registry-documents/src/audit.rs b/crates/registry-documents/src/audit.rs index 89399089de..613f2c0e89 100644 --- a/crates/registry-documents/src/audit.rs +++ b/crates/registry-documents/src/audit.rs @@ -164,7 +164,7 @@ mod tests { AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new(vec![7u8; 32])) .unwrap(); DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), profile.key_hasher(), ) } diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index 7626a62460..f758102552 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -18,10 +18,9 @@ use std::sync::Arc; use registry_documents_core::{ - AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, MissingScope, - VerifiedTokenFacts, + AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -30,11 +29,10 @@ use thiserror::Error; pub struct DocumentsAuthenticator { verifier: TokenVerifier, - /// The configured claim the verifier reads scopes from, named in the - /// refusal log of a token that lacks a scope its profile requires. - scope_claim: String, claim_names: ClaimNames, profiles: AccessProfiles, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, } @@ -61,12 +59,26 @@ impl DocumentsAuthenticator { } /// Verify one credential and resolve it to exactly one access profile. + /// A refusal names the check it failed, for the operator's counter and + /// log line. The answer to the caller does not carry it. pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| AuthenticationError::Refused)?; - let verified = self.verifier.verify(token).await.map_err(|error| { - tracing::debug!(error = %error, "the Document Store bearer credential did not verify"); - verifier_failure(&error) - })?; + self.authenticate_declaring(token) + .await + .map_err(|refusal| refusal.error) + } + + /// As [`Self::authenticate`], and a scope refusal also carries what the + /// deployment declared about it: the scope claim name, the scope the + /// profile requires, and the profile's id. None of it comes from the + /// token. + pub async fn authenticate_declaring(&self, token: &str) -> Result { + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, // so an empty map would trust every authority the issuer federates. @@ -77,11 +89,11 @@ impl DocumentsAuthenticator { tracing::debug!( "an exchanged credential arrived at a deployment that declared no assertion authority" ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer).into()); } let client_id = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))?; let facts = VerifiedTokenFacts { issuer: verified.claims.iss.as_deref(), subject: verified.claims.sub.as_deref(), @@ -94,38 +106,65 @@ impl DocumentsAuthenticator { .resolve(&facts) .map_err(|refusal| match refusal { AccessRefusal::Profile => { - // A scope miss is the refusal an operator can fix. Log - // the configured claim and scope, never the token's own. - if let Some(missing) = self.profiles.missing_scope(&facts) { - tracing::info!( - "{}", - ScopeRefusal { - claim: &self.scope_claim, - missing, - } - ); + let check = self.profile_check(&facts); + let declared = (check == FailedCheck::Scope) + .then(|| self.declared_scope(&facts)) + .flatten(); + DeclaredRefusal { + error: AuthenticationError::Profile(check), + declared, } - AuthenticationError::Profile } - AccessRefusal::Claims => AuthenticationError::Claims, + AccessRefusal::Claims => AuthenticationError::Claims(claims_check(&facts)).into(), }) } -} -/// The value-free sentence logged when a token lacks a scope its access -/// profile requires. -struct ScopeRefusal<'a> { - claim: &'a str, - missing: MissingScope<'a>, + /// The scope claim, the scope and the access profile a scope refusal is + /// about, all from configuration. + fn declared_scope(&self, facts: &VerifiedTokenFacts<'_>) -> Option { + let missing = self.profiles.missing_scope(facts)?; + Some( + DeclaredScope::new(&self.scope_claim) + .with_required_scope(missing.scope) + .with_access_profile(missing.profile), + ) + } + + /// Which check a profile refusal failed. The access profiles answer only + /// that no profile admits the token. A missing scope is the one the + /// profiles name themselves. Resolving the same facts under each kind a + /// profile can admit separates a client no profile lists from a profile + /// that wants another actor kind: when no kind reaches past the profile + /// lookup, the client has no profile. + fn profile_check(&self, facts: &VerifiedTokenFacts<'_>) -> FailedCheck { + if facts.client_id.is_none() { + return FailedCheck::TokenClient; + } + if self.profiles.missing_scope(facts).is_some() { + return FailedCheck::Scope; + } + let profile_exists = ActorKind::ALL.into_iter().any(|kind| { + let probe = VerifiedTokenFacts { + actor_kind: ActorKindClaim::Present(kind), + ..*facts + }; + !matches!(self.profiles.resolve(&probe), Err(AccessRefusal::Profile)) + }); + if profile_exists { + FailedCheck::ActorKind + } else { + FailedCheck::AccessProfile + } + } } -impl std::fmt::Display for ScopeRefusal<'_> { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "a Document Store request was refused because the token's `{}` claim does not carry the `{}` scope access profile `{}` requires; issue that scope to the client, or set authentication.oidc.scopeClaim to the claim the issuer emits", - self.claim, self.missing.scope, self.missing.profile - ) +/// Which check an identity-claims refusal failed: a malformed actor-kind +/// claim, or a principal or issuer the profile cannot use. +fn claims_check(facts: &VerifiedTokenFacts<'_>) -> FailedCheck { + if facts.actor_kind == ActorKindClaim::Malformed { + FailedCheck::ActorKind + } else { + FailedCheck::TokenClaims } } @@ -139,25 +178,59 @@ impl std::fmt::Debug for DocumentsAuthenticator { } } +/// A refusal of authentication with the values the deployment declared about +/// it, when it is a scope refusal. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DeclaredRefusal { + pub error: AuthenticationError, + pub declared: Option, +} + +impl From for DeclaredRefusal { + fn from(error: AuthenticationError) -> Self { + Self { + error, + declared: None, + } + } +} + +/// Why authentication did not admit a caller. Each refusal carries the check +/// it failed, which is operator-side only and never written to a response. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's access profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, } +impl AuthenticationError { + /// The check this refusal failed. A new variant does not compile until it + /// names its check. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) | Self::Claims(check) | Self::Profile(check) => *check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + /// Separate a verifier outage from a bad credential. /// /// A 401 tells a caller its credential is the problem, so it is reserved /// for credentials. When the issuer's discovery document or key set cannot /// be fetched, read, parsed, or used, nothing has been learned about the /// credential. +/// +/// A refusal of the credential names the check the verifier says it failed. fn verifier_failure(error: &OidcError) -> AuthenticationError { match error { OidcError::Transport(_) @@ -174,7 +247,7 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // an unknown `kid`: a key the issuer never published is a forgery // signal. A variant the platform adds later reads as a refusal until // it is classified here, so a new outcome can never widen the door. - _ => AuthenticationError::Refused, + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -216,7 +289,7 @@ pub(crate) mod tests { .value } - fn keys() -> Arc { + pub(crate) fn keys() -> Arc { Arc::new(JwksFetcher::new_static( serde_json::from_value(json!({"keys": [{ "kty": "oct", @@ -289,53 +362,154 @@ pub(crate) mod tests { assert_eq!(caller.kind, ActorKind::Human); } + /// The check `authenticate` reports for `claims`, signed as a real token. + async fn refused_check(claims: serde_json::Value) -> FailedCheck { + authenticator() + .authenticate(&token(claims)) + .await + .expect_err("the token is refused") + .failed_check() + } + #[tokio::test] async fn a_malformed_or_foreign_credential_is_refused() { let authenticator = authenticator(); assert_eq!( authenticator.authenticate("not-a-token").await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused( + FailedCheck::CredentialMalformed + )) ); let mut foreign = citizen_claims(); foreign["iss"] = json!("https://other.example.test"); assert_eq!( authenticator.authenticate(&token(foreign)).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenIssuer)) ); let mut expired = citizen_claims(); expired["exp"] = json!(chrono::Utc::now().timestamp() - 3_600); assert_eq!( authenticator.authenticate(&token(expired)).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenTime)) + ); + let mut elsewhere = citizen_claims(); + elsewhere["aud"] = json!("urn:example:elsewhere"); + assert_eq!( + authenticator.authenticate(&token(elsewhere)).await, + Err(AuthenticationError::Refused(FailedCheck::TokenAudience)) ); } + #[tokio::test] + async fn a_scope_refusal_declares_the_configured_values_and_none_of_the_tokens() { + let mut unscoped = citizen_claims(); + unscoped["scope"] = json!("canary-scope-from-the-token"); + let refusal = authenticator() + .authenticate_declaring(&token(unscoped)) + .await + .unwrap_err(); + assert_eq!( + refusal.error, + AuthenticationError::Profile(FailedCheck::Scope) + ); + let declared = refusal.declared.expect("a scope refusal declares values"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("documents:own")); + assert_eq!(declared.access_profile(), Some("citizen")); + assert!(!format!("{declared:?}").contains("canary-scope-from-the-token")); + // Another refusal declares nothing. + let mut unprofiled = citizen_claims(); + unprofiled["azp"] = json!("unprofiled-client"); + let other = authenticator() + .authenticate_declaring(&token(unprofiled)) + .await + .unwrap_err(); + assert_eq!(other.declared, None); + } + #[tokio::test] async fn a_token_outside_every_profile_is_a_profile_refusal() { - let authenticator = authenticator(); let mut unscoped = citizen_claims(); unscoped["scope"] = json!("documents:read"); assert_eq!( - authenticator.authenticate(&token(unscoped)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(unscoped)).await, + Err(AuthenticationError::Profile(FailedCheck::Scope)) ); + // The verifier admits this client and no access profile lists it. let mut unprofiled = citizen_claims(); unprofiled["azp"] = json!("unprofiled-client"); assert_eq!( - authenticator.authenticate(&token(unprofiled)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(unprofiled)).await, + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let mut agent = citizen_claims(); agent["registry_actor_kind"] = json!("agent"); assert_eq!( - authenticator.authenticate(&token(agent)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(agent)).await, + Err(AuthenticationError::Profile(FailedCheck::ActorKind)) ); let mut service = citizen_claims(); service["registry_actor_kind"] = json!("service"); assert_eq!( - authenticator.authenticate(&token(service)).await, - Err(AuthenticationError::Profile) + authenticator().authenticate(&token(service)).await, + Err(AuthenticationError::Profile(FailedCheck::ActorKind)) + ); + let mut absent = citizen_claims(); + absent + .as_object_mut() + .unwrap() + .remove("registry_actor_kind"); + assert_eq!(refused_check(absent).await, FailedCheck::ActorKind); + } + + #[test] + fn a_token_with_no_client_id_is_a_token_client_refusal() { + let claims = serde_json::Map::new(); + let facts = VerifiedTokenFacts { + issuer: Some(ISSUER), + subject: Some("citizen-1"), + client_id: None, + scopes: &[], + actor_kind: ActorKindClaim::Absent, + claims: &claims, + }; + assert_eq!( + authenticator().profile_check(&facts), + FailedCheck::TokenClient + ); + } + + #[tokio::test] + async fn a_client_no_profile_lists_is_not_a_missing_actor_kind() { + // With no actor kind either, the profile lookup still fails first. + let mut unprofiled = citizen_claims(); + unprofiled["azp"] = json!("unprofiled-client"); + unprofiled + .as_object_mut() + .unwrap() + .remove("registry_actor_kind"); + assert_eq!(refused_check(unprofiled).await, FailedCheck::AccessProfile); + } + + #[tokio::test] + async fn identity_claims_a_profile_cannot_use_are_claims_refusals() { + let mut malformed = citizen_claims(); + malformed["registry_actor_kind"] = json!(7); + assert_eq!( + authenticator().authenticate(&token(malformed)).await, + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) + ); + let mut principal = citizen_claims(); + principal["sub"] = json!("a principal\u{7}with a control"); + assert_eq!( + authenticator().authenticate(&token(principal)).await, + Err(AuthenticationError::Claims(FailedCheck::TokenClaims)) + ); + let mut unlisted = citizen_claims(); + unlisted["azp"] = json!("unlisted-client"); + assert_eq!( + authenticator().authenticate(&token(unlisted)).await, + Err(AuthenticationError::Refused(FailedCheck::TokenClient)) ); } @@ -345,7 +519,9 @@ pub(crate) mod tests { exchanged[ASSERTION_ISSUER_CLAIM] = json!("https://partner.example.test"); assert_eq!( authenticator().authenticate(&token(exchanged)).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer + )) ); } @@ -359,5 +535,54 @@ pub(crate) mod tests { verifier_failure(&OidcError::Parse), AuthenticationError::Unavailable ); + assert_eq!( + AuthenticationError::Unavailable.failed_check(), + FailedCheck::KeySourceUnavailable + ); + } + + /// A key endpoint the verifier refuses to contact, or a static key set it + /// cannot use, is counted under `key-source-unavailable` and answers the + /// refusal a credential gets (401), not the 503 of a key set that could + /// not be fetched or read. The operator pages say so. + #[test] + fn a_key_source_the_verifier_refuses_is_counted_unavailable_and_answers_a_refusal() { + use registry_platform_oidc::{OidcEndpoint, StaticJwksError}; + for error in [ + OidcError::EndpointRefused { + endpoint: OidcEndpoint::DiscoveredCrossOriginJwks, + remedy: "declare the endpoint", + }, + OidcError::InsecureHttpRequiresOptIn, + OidcError::StaticKeySet(StaticJwksError::Empty), + ] { + assert_eq!( + verifier_failure(&error), + AuthenticationError::Refused(FailedCheck::KeySourceUnavailable), + "{error:?}" + ); + } + } + + #[test] + fn a_refused_credential_carries_the_check_the_verifier_names() { + assert_eq!( + verifier_failure(&OidcError::SignatureInvalid), + AuthenticationError::Refused(FailedCheck::TokenSignature) + ); + assert_eq!( + verifier_failure(&OidcError::UnknownKid), + AuthenticationError::Refused(FailedCheck::TokenKey) + ); + } + + #[test] + fn no_refusal_prints_a_value_the_caller_sent() { + let canary = "canary-issuer.example.test"; + let error = verifier_failure(&OidcError::IssuerMismatch { + expected: "expected".to_owned(), + actual: canary.to_owned(), + }); + assert!(!format!("{error} {error:?}").contains(canary)); } } diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index fe1ee81189..4b269dcb8e 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -21,10 +21,10 @@ use registry_platform_audit::{ }; use registry_platform_config::JwksSource; pub use registry_platform_config::{ - AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, - PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, - UrlHookDestinationConfig, + AdmittedClients, AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, + MetricsListenerConfig, ObjectStorageConfig, OidcIssuerConfig, OidcPackageClientsConfig, + PackageClients, PackageClientsError, PackageConfig, PrivateListenerConfig as ListenerConfig, + SecretProvidersConfig, TlsTermination, UrlHookDestinationConfig, }; use registry_platform_config::{ ConfigBlockError, RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretResolver, @@ -33,7 +33,8 @@ use registry_platform_config::{ use registry_platform_objectstore::{s3::S3Settings, verifier::HttpVerifierSettings}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{BoundedU32, BoundedU64, Diagnostic, ExternalId, LocalId, Report}; use serde::Deserialize; @@ -82,6 +83,11 @@ pub const MAXIMUM_HOOK_PAYLOAD_RETENTION_DAYS: u32 = 30; /// The largest `audit.rotateBytes`. pub const MAXIMUM_AUDIT_ROTATE_BYTES: u64 = u32::MAX as u64; +const ALLOWED_CLIENTS_REQUIRED_CODE: &str = "documents.runtime.allowed-clients-required"; +const PROFILE_CLIENT_NOT_ALLOWED_CODE: &str = "documents.runtime.profile-client-not-allowed"; +const ASSERTION_ISSUER_CLIENT_NOT_ALLOWED_CODE: &str = + "documents.runtime.assertion-issuer-client-not-allowed"; + /// The code of the refusal a runtime document earns when `destinations.hooks` /// leaves unbound a destination the project's hooks name. `documentsctl /// check` reports it at `/destinations/hooks`, and the runtime's startup @@ -155,11 +161,13 @@ pub struct OidcConfig { #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] #[cfg_attr(feature = "schema", schemars(flatten))] pub provider: OidcIssuerConfig, - /// The OAuth clients this runtime admits. Every access profile resolves - /// its caller from the matched client, so the list is never empty. - #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-clients"))] + /// The OAuth clients this runtime admits: `from-package` for the + /// requester clients of the project's access profiles, or a list that + /// covers every client a profile names. Every access profile resolves its + /// caller from the matched client, so the admitted set is never empty. + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-package-clients"))] #[cfg_attr(feature = "schema", schemars(flatten))] - pub clients: OidcClientsConfig, + pub clients: OidcPackageClientsConfig, #[serde(default = "default_scope_claim")] pub scope_claim: ExternalId, } @@ -510,6 +518,18 @@ pub enum RuntimeConfigError { OidcJwksSecret(String), } +/// The static key set the operator pinned. A document that breaks a key set +/// rule is the operator's to fix, so the refusal says which rule: it never +/// holds a key value. +fn parse_static_key_set(document: &[u8]) -> Result { + parse_static_jwks(document).map_err(|error| match error { + OidcError::StaticKeySet(refusal) => RuntimeConfigError::OidcJwksSecret(format!( + "the document at authentication.oidc.jwksSource.documentRef was refused: {refusal}" + )), + _ => RuntimeConfigError::Oidc, + }) +} + fn refused(findings: &[Finding]) -> String { match findings { [] => "the runtime configuration was refused".to_owned(), @@ -525,7 +545,7 @@ fn refused(findings: &[Finding]) -> String { impl RuntimeConfig { #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(DOCUMENTS_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(DOCUMENTS_RUNTIME_ENVELOPE) .removed_keys(DOCUMENTS_REMOVED_KEYS) .require_trusted_ownership() } @@ -588,7 +608,7 @@ impl RuntimeConfig { JwksFetcherConfig::defaults(), network.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", @@ -596,8 +616,7 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_key_set(document.expose_secret())?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -608,7 +627,7 @@ impl RuntimeConfig { /// describe: RFC 9068 access tokens only, from the configured issuer, /// for the configured audience, from an admitted client. #[must_use] - pub fn verifier_profile(&self) -> TokenVerifierConfig { + pub fn verifier_profile(&self, admitted: &AdmittedClients) -> TokenVerifierConfig { let oidc = &self.authentication.oidc; TokenVerifierConfig::access_token_profile( oidc.provider.issuer.to_string(), @@ -620,7 +639,7 @@ impl RuntimeConfig { access_token_typ_set(DOCUMENTS_ACCESS_TOKEN_TYPE), ) .with_scope_claim(oidc.scope_claim.as_str().to_owned()) - .with_allowed_clients(oidc.clients.allowed_clients.clone()) + .with_allowed_clients(admitted.as_slice().to_vec()) .with_assertion_issuers(oidc.clients.assertion_issuers.clone()) } @@ -738,6 +757,12 @@ impl RuntimeConfig { format!("destinations.hooks.{id}.hmacSha256KeyRef"), destination.hmac_sha256_key_ref.as_str(), )); + if let Some(reference) = &destination.previous_hmac_sha256_key_ref { + references.push(( + format!("destinations.hooks.{id}.previousHmacSha256KeyRef"), + reference.as_str(), + )); + } } for (field, reference) in references { if let Err(error) = self.secret_providers.check_reference(&field, reference) { @@ -763,19 +788,17 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; let development = self.listener.tls_termination == TlsTermination::DevelopmentLoopback; - if let Err(error) = oidc.provider.check("authentication.oidc", development) { + if let Err(error) = oidc + .provider + .check_without_posture("authentication.oidc", development) + { findings.push(Finding::block("/authentication/oidc", &error)); } if let Err(error) = oidc.clients.check("authentication.oidc") { findings.push(Finding::block("/authentication/oidc", &error)); } - if oidc.clients.allowed_clients.is_empty() { - findings.push(Finding::new( - "documents.runtime.allowed-clients-required", - "/authentication/oidc/allowedClients", - "authentication.oidc.allowedClients must list the clients this runtime admits; `unrestricted` is refused", - "List every OAuth client an access profile names under allowedClients.", - )); + if oidc.clients.allowed_clients == PackageClients::Unrestricted { + findings.push(allowed_clients_required()); } } @@ -868,6 +891,79 @@ impl RuntimeConfig { /// `destinations.hooks`. #[must_use] pub fn project_findings(&self, project: &DocumentsProject) -> Vec { + let mut findings = self.client_findings(project); + findings.extend(self.hook_findings(project)); + findings + } + + /// The clients the token verifier admits, given the project this runtime + /// serves. `from-package` is the sorted union of the access profiles' + /// requester clients, and a list must cover every one of them, or the + /// profile naming the missing client could never be reached. The verifier + /// is never handed an empty list, which it reads as "every client". + pub fn admitted_clients(&self, project: &DocumentsProject) -> Result { + self.authentication + .oidc + .clients + .allowed_clients + .resolve(&requester_clients(project)) + .map_err(|error| match error { + PackageClientsError::Unrestricted | PackageClientsError::Empty => { + allowed_clients_required() + } + PackageClientsError::Missing(client) => { + let profile = project + .access_profiles + .iter() + .find(|(_, profile)| { + profile + .requester_clients + .as_slice() + .iter() + .any(|listed| listed.as_str() == client) + }) + .map_or("", |(id, _)| id.as_str()); + Finding::new( + PROFILE_CLIENT_NOT_ALLOWED_CODE, + "/authentication/oidc/allowedClients", + format!( + "authentication.oidc.allowedClients does not list {client}, a requester client of access profile {profile}" + ), + "Add the client to allowedClients, or write allowedClients: from-package to admit every requester client the project names.", + ) + } + }) + } + + /// What the admitted clients leave wrong against the project. An + /// `unrestricted` value is reported by [`Self::findings`] alone. + fn client_findings(&self, project: &DocumentsProject) -> Vec { + let oidc = &self.authentication.oidc; + if oidc.clients.allowed_clients == PackageClients::Unrestricted { + return Vec::new(); + } + let admitted = match self.admitted_clients(project) { + Ok(admitted) => admitted, + Err(finding) => return vec![finding], + }; + oidc.clients + .assertion_issuers + .keys() + .filter(|client| !admitted.as_slice().contains(client)) + .map(|client| { + Finding::new( + ASSERTION_ISSUER_CLIENT_NOT_ALLOWED_CODE, + &format!("/authentication/oidc/assertionIssuers/{}", escape(client)), + format!( + "authentication.oidc.assertionIssuers names {client}, which no access profile of the project lists as a requester client" + ), + "Name a requester client of an access profile, or remove the entry.", + ) + }) + .collect() + } + + fn hook_findings(&self, project: &DocumentsProject) -> Vec { let unbound = project.hooks.iter().any(|hook| { let HookHandler::Url { destination_id } = &hook.handler; !self @@ -900,6 +996,29 @@ fn dotted_pointer(field: &str) -> String { .collect() } +/// The requester clients of every access profile of `project`, sorted and +/// distinct. +fn requester_clients(project: &DocumentsProject) -> Vec { + let mut clients: Vec = project + .access_profiles + .values() + .flat_map(|profile| profile.requester_clients.as_slice()) + .map(|client| client.as_str().to_owned()) + .collect(); + clients.sort(); + clients.dedup(); + clients +} + +fn allowed_clients_required() -> Finding { + Finding::new( + ALLOWED_CLIENTS_REQUIRED_CODE, + "/authentication/oidc/allowedClients", + "authentication.oidc.allowedClients must be `from-package` or list the clients this runtime admits; `unrestricted` is refused", + "Write allowedClients: from-package, or list every OAuth client an access profile names.", + ) +} + /// What an offline check of one runtime document found (CFG-CHECK-1). #[derive(Debug)] pub struct RuntimeCheck { @@ -1155,6 +1274,52 @@ pub(crate) mod tests { ); } + const PUBLIC_KEY: &str = r#"{"kty":"EC","crv":"P-256","kid":"k1","alg":"ES256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}"#; + + fn key_set(extra: &str) -> String { + let key = if extra.is_empty() { + PUBLIC_KEY.to_owned() + } else { + PUBLIC_KEY.replacen('}', &format!(",{extra}}}"), 1) + }; + format!(r#"{{"keys":[{key}]}}"#) + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + let document = key_set(r#""ext":true,"x5t":"abc","x5c":["AAAA"]"#); + let jwks = parse_static_key_set(document.as_bytes()).expect("unknown public members load"); + assert_eq!(jwks.keys.len(), 1); + } + + #[test] + fn a_static_key_set_that_holds_a_private_member_is_refused_by_rule_and_not_by_value() { + let secret = "private-canary-value"; + let document = key_set(&format!(r#""d":"{secret}""#)); + let RuntimeConfigError::OidcJwksSecret(message) = + parse_static_key_set(document.as_bytes()).expect_err("a private member is refused") + else { + panic!("a refused key set is not an issuer outage"); + }; + assert!( + message.contains(r#"private-key member "d""#), + "the refusal names the private-key member rule" + ); + assert!(message.contains("authentication.oidc.jwksSource.documentRef")); + assert!( + !message.contains(secret), + "the refusal holds the private member's value" + ); + } + + #[test] + fn a_static_key_set_that_is_not_json_is_not_an_issuer_outage() { + assert!(matches!( + parse_static_key_set(b"not json"), + Err(RuntimeConfigError::OidcJwksSecret(_)) + )); + } + #[test] fn the_starter_runtime_document_is_accepted() { let config = parse(STARTER_RUNTIME).expect("the starter runtime document"); @@ -1243,6 +1408,203 @@ pub(crate) mod tests { ); } + const STARTER_CLIENTS: &str = + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]"; + + fn from_package_runtime() -> String { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, "allowedClients: from-package"); + assert_ne!(text, STARTER_RUNTIME); + text + } + + fn starter_project() -> DocumentsProject { + DocumentsProject::decode( + "documents.yaml", + include_bytes!("../../../products/documents/examples/starter/documents.yaml"), + ) + .expect("the starter project decodes") + .value + } + + fn project_finding_codes(config: &RuntimeConfig, project: &DocumentsProject) -> Vec { + config + .project_findings(project) + .iter() + .map(|finding| format!("{} {}", finding.code, finding.pointer)) + .collect() + } + + #[test] + fn from_package_is_accepted_and_names_no_second_list() { + let config = parse(&from_package_runtime()).expect("from-package loads"); + assert_eq!( + config.authentication.oidc.clients.allowed_clients, + PackageClients::FromPackage + ); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn an_omitted_allowed_clients_member_is_refused() { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, ""); + assert_ne!(text, STARTER_RUNTIME); + let found = codes(parse(&text).unwrap_err()); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].starts_with("config."), "{found:?}"); + } + + #[test] + fn an_empty_list_and_an_unknown_keyword_are_refused() { + for written in ["allowedClients: []", "allowedClients: any"] { + let text = STARTER_RUNTIME.replace(STARTER_CLIENTS, written); + assert!(parse(&text).is_err(), "{written}"); + } + } + + #[test] + fn explicit_list_missing_a_package_client_is_refused() { + let text = STARTER_RUNTIME.replace( + STARTER_CLIENTS, + "allowedClients: [civil-registry-app, citizen-portal, case-portal]", + ); + let config = parse(&text).expect("a list is a valid file on its own"); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.profile-client-not-allowed /authentication/oidc/allowedClients"] + ); + } + + #[test] + fn an_explicit_list_with_a_client_the_package_does_not_name_is_accepted() { + let text = STARTER_RUNTIME.replace( + STARTER_CLIENTS, + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal, extra-app]", + ); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn assertion_issuer_client_outside_the_package_is_refused_under_from_package() { + let with_issuers = |client: &str| { + from_package_runtime().replace( + "allowedClients: from-package\n", + &format!( + "allowedClients: from-package\n assertionIssuers:\n {client}: [https://assertions.example.test]\n" + ), + ) + }; + let config = parse(&with_issuers("unknown-client")).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/unknown-client"] + ); + let config = parse(&with_issuers("citizen-portal")).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + [] as [String; 0] + ); + } + + #[test] + fn an_assertion_issuer_client_with_dots_is_reported_at_its_own_pointer() { + let text = from_package_runtime().replace( + "allowedClients: from-package\n", + "allowedClients: from-package\n assertionIssuers:\n com.example.portal: [https://assertions.example.test]\n", + ); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/com.example.portal"] + ); + } + + #[test] + fn assertion_issuer_client_outside_an_explicit_list_is_refused() { + let text = STARTER_RUNTIME.replace( + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n", + "allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n assertionIssuers:\n unknown-client: [https://assertions.example.test]\n", + ); + assert_ne!(text, STARTER_RUNTIME); + let config = parse(&text).unwrap(); + assert_eq!( + project_finding_codes(&config, &starter_project()), + ["documents.runtime.assertion-issuer-client-not-allowed /authentication/oidc/assertionIssuers/unknown-client"] + ); + } + + #[tokio::test] + async fn from_package_admits_exactly_the_package_clients() { + use crate::auth::tests::{keys, token}; + use registry_platform_oidc::TokenVerifier; + + let project = DocumentsProject::decode( + "documents.yaml", + include_str!("../../../products/documents/examples/starter/documents.yaml") + .replacen( + "requesterClients: [civil-registry-app]", + "requesterClients: [civil-registry-app, second-app]", + 1, + ) + .as_bytes(), + ) + .expect("the project decodes") + .value; + let config = parse(&from_package_runtime()).unwrap(); + let admitted = config.admitted_clients(&project).unwrap(); + assert_eq!( + admitted.as_slice(), + [ + "case-portal", + "citizen-portal", + "civil-registry-app", + "partner-portal", + "second-app" + ] + ); + let mut profile = config.verifier_profile(&admitted); + profile.allowed_algorithms = vec![jsonwebtoken::Algorithm::HS256]; + let verifier = TokenVerifier::new(profile, keys()); + let signed = |client: &str| { + token(serde_json::json!({ + "iss": "https://identity.example.test/realms/registry", + "aud": "urn:example:documents", + "sub": "principal", + "azp": client, + "scope": "documents:read", + })) + }; + for client in admitted.as_slice() { + verifier + .verify(&signed(client)) + .await + .unwrap_or_else(|error| panic!("{client} is admitted: {error}")); + } + let refused = verifier.verify(&signed("stranger-app")).await; + assert!( + matches!( + refused, + Err(registry_platform_oidc::OidcError::ClientNotAllowed) + ), + "{refused:?}" + ); + } + + #[test] + fn from_package_never_reaches_the_verifier_as_an_empty_list() { + let config = parse(&from_package_runtime()).unwrap(); + let mut project = starter_project(); + project.access_profiles.clear(); + let finding = config.admitted_clients(&project).unwrap_err(); + assert_eq!(finding.code, "documents.runtime.allowed-clients-required"); + } + #[test] fn disabled_content_verification_requires_development_loopback() { let disabled = STARTER_RUNTIME.replace(HTTP_VERIFIER, " type: disabled\n"); @@ -1277,6 +1639,163 @@ pub(crate) mod tests { assert!(!findings[0].message.contains("OWNING_SYSTEM_EVENTS_HMAC")); } + #[cfg(unix)] + fn activate_test_hook_keys( + text: &str, + keys: &[(&str, &[u8])], + ) -> Result { + use std::os::unix::fs::PermissionsExt as _; + + let directory = tempfile::tempdir().unwrap(); + for (name, bytes) in keys { + let path = directory.path().join(name); + std::fs::write(&path, bytes).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let configuration = parse(&text.replace( + "/run/secrets/registry-documents", + directory.path().to_str().unwrap(), + )) + .expect("the runtime document parses"); + crate::hooks::ActivatedHooks::activate( + &[], + &configuration.destinations.hooks, + &configuration.secret_resolver().unwrap(), + crate::hooks::HookRuntimeIdentity { + project_id: "civil-registry-documents".to_owned(), + package_digest: format!("sha256:{}", "0".repeat(64)), + database_id: "documents-test".to_owned(), + }, + "public".to_owned(), + std::time::Duration::from_secs(86400), + ) + } + + const CURRENT_HOOK_KEY_REF: &str = "hmacSha256KeyRef: secret:file/owning-system-events-hmac"; + #[cfg(unix)] + const CURRENT_HOOK_KEY: &[u8] = b"synthetic-current-hook-key-123456"; + + fn rotating_hook_runtime() -> String { + STARTER_RUNTIME.replace( + CURRENT_HOOK_KEY_REF, + &format!( + "{CURRENT_HOOK_KEY_REF}\n previousHmacSha256KeyRef: secret:file/previous" + ), + ) + } + + #[test] + fn hook_signing_keys_refuse_a_previous_reference_to_a_disabled_provider() { + let text = + rotating_hook_runtime().replace("secret:file/previous", "secret:env/PREVIOUS_HOOK_KEY"); + let error = parse(&text).expect_err("a disabled secret provider is refused"); + let RuntimeConfigError::Refused(findings) = error else { + panic!("a refused document"); + }; + assert_eq!(findings.len(), 1); + assert_eq!( + findings[0].pointer, + "/destinations/hooks/owning-system-events/previousHmacSha256KeyRef" + ); + assert!(!findings[0].message.contains("PREVIOUS_HOOK_KEY")); + } + + #[cfg(unix)] + #[test] + fn hook_signing_keys_accept_a_distinct_previous_key() { + activate_test_hook_keys( + &rotating_hook_runtime(), + &[ + ("owning-system-events-hmac", CURRENT_HOOK_KEY), + ("previous", &[b'p'; 32]), + ], + ) + .expect("distinct current and previous keys activate"); + } + + #[cfg(unix)] + #[test] + fn hook_signing_keys_refuse_a_previous_key_equal_to_the_current_key() { + let error = activate_test_hook_keys( + &rotating_hook_runtime(), + &[ + ("owning-system-events-hmac", CURRENT_HOOK_KEY), + ("previous", CURRENT_HOOK_KEY), + ], + ) + .unwrap_err() + .to_string(); + assert_eq!( + error, + "destinations.hooks.owning-system-events.previousHmacSha256KeyRef holds the same bytes as destinations.hooks.owning-system-events.hmacSha256KeyRef. To rotate, write 32 new random bytes to the secret destinations.hooks.owning-system-events.hmacSha256KeyRef references and keep the old bytes behind destinations.hooks.owning-system-events.previousHmacSha256KeyRef." + ); + assert!(!error.contains(std::str::from_utf8(CURRENT_HOOK_KEY).unwrap())); + } + + #[cfg(unix)] + #[test] + fn hook_signing_keys_report_length_and_trailing_newline() { + let mut key = [b'x'; 65]; + key[64] = b'\n'; + let error = + activate_test_hook_keys(STARTER_RUNTIME, &[("owning-system-events-hmac", &key)]) + .unwrap_err() + .to_string(); + for detail in [ + "destinations.hooks.owning-system-events.hmacSha256KeyRef", + "65 bytes", + "trailing newline: true", + "Supply 32 to 64 exact key bytes.", + ] { + assert!(error.contains(detail), "{error}"); + } + assert!(!error.contains("xxxxxxxx")); + } + + #[cfg(unix)] + #[test] + fn hook_signing_keys_refuse_previous_key_secret_text() { + let text = b"whsec_synthetic-secret-encoding"; + let error = activate_test_hook_keys( + &rotating_hook_runtime(), + &[ + ("owning-system-events-hmac", CURRENT_HOOK_KEY), + ("previous", text), + ], + ) + .unwrap_err() + .to_string(); + assert!( + error.starts_with("destinations.hooks.owning-system-events.previousHmacSha256KeyRef:") + ); + assert!(error.contains("starts with whsec_")); + assert!(error.ends_with("Supply the exact key bytes without the whsec_ encoding.")); + assert!(!error.contains(std::str::from_utf8(text).unwrap())); + } + + #[cfg(unix)] + #[test] + fn hook_signing_keys_report_both_destinations_when_their_keys_match() { + let text = STARTER_RUNTIME.replace( + " owning-system-events:\n", + " audit-mirror:\n url: https://mirror.example.test/documents\n hmacSha256KeyRef: secret:file/mirror\n owning-system-events:\n", + ); + let error = activate_test_hook_keys( + &text, + &[ + ("owning-system-events-hmac", CURRENT_HOOK_KEY), + ("mirror", CURRENT_HOOK_KEY), + ], + ) + .unwrap_err() + .to_string(); + assert_eq!( + error, + "destinations.hooks.audit-mirror.hmacSha256KeyRef and destinations.hooks.owning-system-events.hmacSha256KeyRef resolve to the same key bytes. Give destinations.hooks.owning-system-events.hmacSha256KeyRef its own key by writing 32 new random bytes to another secret and referencing it there." + ); + assert!(!error.contains(std::str::from_utf8(CURRENT_HOOK_KEY).unwrap())); + } + #[test] fn a_plaintext_hook_destination_is_refused_outside_development() { let text = STARTER_RUNTIME.replace( diff --git a/crates/registry-documents/src/hooks.rs b/crates/registry-documents/src/hooks.rs index 37b8f7987a..cdae741462 100644 --- a/crates/registry-documents/src/hooks.rs +++ b/crates/registry-documents/src/hooks.rs @@ -58,7 +58,6 @@ use crate::store::PostgresStore; const DESTINATION_BINDING_SCHEMA: &str = "registry.documents-hook-destinations/v1"; const COMPILED_HOOK_SCHEMA: &str = "registry.documents-hooks/v1"; -const IDEMPOTENCY_DOMAIN: &[u8] = b"documents-hook-idempotency-v1"; /// The refusal code retained with a delivery whose destination answered with /// a proposal. Each dotted segment is lowercase kebab-case. const PROPOSAL_UNSUPPORTED_CODE: &str = "documents.hook.proposal-unsupported"; @@ -74,7 +73,7 @@ const MAXIMUM_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60); const _: () = assert!(MAXIMUM_PAYLOAD_BYTES <= MAX_DESTINATION_REQUEST_BODY_BYTES); /// Value-free refusal from hook compilation or deployment activation. -#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +#[derive(Debug, Eq, PartialEq, thiserror::Error)] pub enum HookActivationError { #[error("the Document Store hook declaration is invalid")] InvalidDeclaration, @@ -101,8 +100,8 @@ pub enum HookActivationError { InvalidDestination, #[error("a Document Store hook destination widens the fixed delivery budget")] DeliveryBudgetWidening, - #[error("a Document Store hook signing secret is unavailable or invalid")] - InvalidSigningMaterial, + #[error("{}", signing_material_refusal(.0))] + InvalidSigningMaterial(#[source] UrlHookActivationError), #[error("the Document Store hook runtime identity is invalid")] InvalidIdentity, } @@ -691,7 +690,6 @@ impl ActivatedHooks { seams, DeliveryConfig { schema: self.schema.clone(), - idempotency_domain: IDEMPOTENCY_DOMAIN.to_vec(), delivery_source: self.delivery_source.clone(), }, ), @@ -725,12 +723,62 @@ fn activation_error(error: UrlHookActivationError) -> HookActivationError { HookActivationError::DeliveryBudgetWidening } UrlHookActivationError::InvalidDestination => HookActivationError::InvalidDestination, - UrlHookActivationError::InvalidSigningMaterial => { - HookActivationError::InvalidSigningMaterial + UrlHookActivationError::SigningKeyUnavailable { .. } + | UrlHookActivationError::InvalidSigningKey { .. } + | UrlHookActivationError::RepeatedSigningKey { .. } => { + HookActivationError::InvalidSigningMaterial(error) } } } +fn signing_material_refusal(error: &UrlHookActivationError) -> String { + match error { + UrlHookActivationError::SigningKeyUnavailable { + destination, + member, + reason, + } => format!( + "destinations.hooks.{destination}.{member}: {reason}. {}", + reason.suggested_action() + ), + UrlHookActivationError::InvalidSigningKey { + destination, + member, + length, + trailing_newline, + reason, + } => match reason.code() { + "previous-key-equals-current" => { + let current = format!("destinations.hooks.{destination}.hmacSha256KeyRef"); + let previous = format!("destinations.hooks.{destination}.{member}"); + format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}." + ) + } + "key-is-secret-text" => format!( + "destinations.hooks.{destination}.{member}: the delivery key starts with whsec_. Supply the exact key bytes without the whsec_ encoding." + ), + _ => format!( + "destinations.hooks.{destination}.{member} has {length} bytes (trailing newline: {trailing_newline}). Supply 32 to 64 exact key bytes." + ), + }, + UrlHookActivationError::RepeatedSigningKey { first, second } => { + shared_signing_key_refusal(first, second) + } + UrlHookActivationError::DeliveryBudgetWidening | UrlHookActivationError::InvalidDestination => { + error.to_string() + } + } +} + +fn shared_signing_key_refusal(first: &str, second: &str) -> String { + let first = format!("destinations.hooks.{first}"); + let second = format!("destinations.hooks.{second}"); + format!( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there." + ) +} + /// The delays between attempts: from 30 seconds, doubling, capped at one /// hour, one delay between each pair of the attempt ceiling's attempts. fn retry_delays_ms() -> Vec { @@ -887,6 +935,18 @@ impl HookDeliveryService { self.inner.deliver_once().await } + #[cfg(feature = "postgres-test")] + pub(crate) async fn replay_for_test( + &self, + event_id: Uuid, + compiled_delivery_id: &str, + generation: i64, + ) -> Result { + self.inner + .replay(event_id, compiled_delivery_id, generation) + .await + } + pub async fn verify_retained_bindings(&self) -> Result<(), DeliveryError> { self.inner .verify_retained_bindings() diff --git a/crates/registry-documents/src/hooks_tests.rs b/crates/registry-documents/src/hooks_tests.rs index f6490ef993..72d5a9e9cf 100644 --- a/crates/registry-documents/src/hooks_tests.rs +++ b/crates/registry-documents/src/hooks_tests.rs @@ -447,7 +447,13 @@ fn identity() -> HookRuntimeIdentity { /// pinned: a change to the digest shape is a breaking change. #[test] fn hook_destination_binding_digests_are_pinned() { - let (_directory, secrets) = file_secrets(); + use std::os::unix::fs::PermissionsExt as _; + + let (directory, secrets) = file_secrets(); + let mirror_key = directory.path().join("mirror-key"); + std::fs::write(&mirror_key, [0x6b; 32]).expect("write the mirror key"); + std::fs::set_permissions(&mirror_key, std::fs::Permissions::from_mode(0o600)) + .expect("restrict the mirror key"); let configured = configured(json!({ "owning-system-events": { "url": "https://events.example.test/documents", @@ -455,7 +461,7 @@ fn hook_destination_binding_digests_are_pinned() { }, "audit-mirror": { "url": "http://127.0.0.1:8080/hooks", - "hmacSha256KeyRef": "secret:file/hook-key", + "hmacSha256KeyRef": "secret:file/mirror-key", "attemptTimeoutMilliseconds": 250, "maximumAttempts": 3, }, @@ -466,16 +472,16 @@ fn hook_destination_binding_digests_are_pinned() { .expect("the pinned hook destinations activate"); assert_eq!( - activated.binding_digest, - "sha256:dc81f68b54c313d5cc310258dbefd0743b5e35e7e53f65ad2a0b89dc93f5b40f" - ); - assert_eq!( - activated.bindings["owning-system-events"].binding_digest(), - "sha256:cd4da816b206e19dfa0a04a81c09b9fee12cac3edd1efaaffdecfa55c8e76a58" - ); - assert_eq!( - activated.bindings["audit-mirror"].binding_digest(), - "sha256:545d6c1a305c7a38085da5520df5e1ba8db18c0eb5a2b234a919eeae8055550e" + [ + activated.binding_digest.as_str(), + activated.bindings["owning-system-events"].binding_digest(), + activated.bindings["audit-mirror"].binding_digest(), + ], + [ + "sha256:4ede0d0a045d99392472f146bf4f4f78d0cf15f1abd1a5f37625c99e5200d12b", + "sha256:cd4da816b206e19dfa0a04a81c09b9fee12cac3edd1efaaffdecfa55c8e76a58", + "sha256:13cbbd8ac10dba6e6f99b245e9e485b9f6c924ac18408d7bb6d929197d0d7229", + ] ); } @@ -527,7 +533,20 @@ fn activation_refuses_a_signing_secret_it_cannot_resolve() { Duration::from_secs(7 * 24 * 60 * 60), ) .expect_err("an unresolvable signing secret is refused"); - assert_eq!(error, HookActivationError::InvalidSigningMaterial); + assert!(matches!( + error, + HookActivationError::InvalidSigningMaterial( + UrlHookActivationError::SigningKeyUnavailable { .. } + ) + )); + let message = error.to_string(); + assert!( + message.starts_with("destinations.hooks.owning-system-events.hmacSha256KeyRef"), + "{message}" + ); + assert!(message + .ends_with("Enable the reference's provider under secretProviders in the runtime file.")); + assert!(!message.contains("secret:file/hook-key")); } #[test] diff --git a/crates/registry-documents/src/http.rs b/crates/registry-documents/src/http.rs index a53d002877..e4bd1bcb21 100644 --- a/crates/registry-documents/src/http.rs +++ b/crates/registry-documents/src/http.rs @@ -26,10 +26,12 @@ use registry_documents_core::{ type_uri, Caller, IssueGrantRequest, ProblemCode, ReserveDocumentRequest, HEALTH_PATH, READY_PATH, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, +}; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use serde::de::DeserializeOwned; @@ -39,7 +41,7 @@ use uuid::Uuid; use crate::audit::DocumentsAudit; use crate::auth::{AuthenticationError, DocumentsAuthenticator}; use crate::metrics::{serve_metrics, MetricsState, METRICS_PATH}; -use crate::service::{DocumentService, PageRequest}; +use crate::service::{DocumentService, PageRequest, ServiceError}; use crate::store::PostgresStore; tokio::task_local! { @@ -64,7 +66,7 @@ fn finish(limited: Router, unlimited: Router) -> Router { .fallback(route_not_found) .method_not_allowed_fallback(method_not_allowed) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } /// The operator-private router the metrics listener serves: the series, with @@ -251,31 +253,50 @@ impl DocumentRoutes { /// The verified caller, before anything else of the request is read. /// A missing or refused credential is `authentication.refused`; a token /// that resolves to no access profile is `profile.not-authorized`. - async fn caller(&self, headers: &HeaderMap) -> Result { - let token = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .and_then(|value| parse_bearer_token(value).ok()) - .ok_or(ProblemCode::AuthenticationRefused)?; + async fn caller(&self, headers: &HeaderMap) -> Result { + let token = bearer_token(headers)?; let caller = self .authenticator - .authenticate(token) + .authenticate_declaring(token) .await - .map_err(|error| match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - ProblemCode::AuthenticationRefused - } - AuthenticationError::Profile => ProblemCode::ProfileNotAuthorized, - AuthenticationError::Unavailable => { - tracing::warn!("the token verifier could not answer; the request was refused"); - ProblemCode::ServiceUnavailable - } + .map_err(|refusal| Refusal { + error: authentication_refusal(refusal.error), + declared: refusal.declared, })?; self.service.admit().await?; Ok(caller) } } +/// The bearer token of the request, or the refusal that names what is wrong +/// with its credential: none, another scheme, or a header that is not a +/// well-formed bearer credential. +fn bearer_token(headers: &HeaderMap) -> Result<&str, ServiceError> { + let credential = |check| ServiceError::unauthenticated(check); + let value = headers + .get(AUTHORIZATION) + .ok_or_else(|| credential(FailedCheck::CredentialMissing))? + .to_str() + .map_err(|_| credential(FailedCheck::CredentialMalformed))?; + parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => credential(FailedCheck::CredentialMissing), + _ => credential(FailedCheck::CredentialMalformed), + }) +} + +/// How authentication's refusal answers: a credential or claims refusal is +/// `authentication.refused`, a profile refusal is `profile.not-authorized`, +/// and a verifier that cannot answer is `service.unavailable`. +fn authentication_refusal(error: AuthenticationError) -> ServiceError { + match error { + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + ServiceError::unauthenticated(check) + } + AuthenticationError::Profile(check) => ServiceError::not_authorized(check), + AuthenticationError::Unavailable => ServiceError::KeySourceUnavailable, + } +} + /// The served surface: `/health`, `/ready`, and the document routes. pub fn router(routes: DocumentRoutes) -> Router { let probes = Router::new() @@ -298,12 +319,61 @@ pub fn router(routes: DocumentRoutes) -> Router { finish(limited, unlimited) } -fn identifier(text: &str) -> Result { - Uuid::parse_str(text).map_err(|_| ProblemCode::ResourceNotFound) +/// An id in a path. One that is not an id names nothing, and the answer +/// does not say whether anything exists. +fn identifier(text: &str) -> Result { + Uuid::parse_str(text).map_err(|_| ServiceError::concealed(FailedCheck::Visibility)) +} + +/// A failed operation, and the values the deployment declared about it when +/// it is a scope refusal. The values go to the operator's log line only. +pub(crate) struct Refusal { + error: ServiceError, + declared: Option, } -fn answer(result: Result) -> Response { - result.unwrap_or_else(problem_response) +impl From for Refusal { + fn from(error: ServiceError) -> Self { + Self { + error, + declared: None, + } + } +} + +impl From for Refusal { + fn from(problem: ProblemCode) -> Self { + ServiceError::from(problem).into() + } +} + +fn answer(result: Result) -> Response { + result.unwrap_or_else(|refusal| { + let mut response = refusal_response(refusal.error); + if let Some(declared) = refusal.declared { + response.extensions_mut().insert(declared); + } + response + }) +} + +/// The remedy the log line of a scope refusal carries. +const SCOPE_REMEDY: &str = "issue the access profile's required scope to the client, or set authentication.oidc.scopeClaim to the claim the issuer emits"; + +/// Render the answer to a failed operation. A refusal of authority puts its +/// check in the response's extensions, which are never serialized, for the +/// layer that records it; the bytes of the answer are those of its problem. +pub(crate) fn refusal_response(error: ServiceError) -> Response { + let mut response = problem_response(error.problem()); + if let Some(check) = error.failed_check() { + let note = RefusalNote::new(check); + let note = match check { + FailedCheck::Scope => note.with_remedy(SCOPE_REMEDY), + _ => note, + }; + response.extensions_mut().insert(note); + } + response } /// The idempotency key a creating request carries: present, bounded, and @@ -755,6 +825,86 @@ mod tests { assert!(response.headers().get(WWW_AUTHENTICATE).is_none()); } + fn authorization(value: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, value.parse().unwrap()); + headers + } + + #[test] + fn a_credential_refusal_names_what_is_wrong_with_the_credential() { + let check = |headers: &HeaderMap| bearer_token(headers).unwrap_err().failed_check(); + assert_eq!( + check(&HeaderMap::new()), + Some(FailedCheck::CredentialMissing) + ); + assert_eq!( + check(&authorization("Basic dXNlcjpwYXNz")), + Some(FailedCheck::CredentialMissing) + ); + for malformed in ["Bearer", "Bearer token", "Bearer a b"] { + assert_eq!( + check(&authorization(malformed)), + Some(FailedCheck::CredentialMalformed), + "{malformed}" + ); + } + let mut unreadable = HeaderMap::new(); + unreadable.insert(AUTHORIZATION, b"Bearer \xff".as_slice().try_into().unwrap()); + assert_eq!(check(&unreadable), Some(FailedCheck::CredentialMalformed)); + assert_eq!(bearer_token(&authorization("bearer abc")), Ok("abc")); + } + + #[test] + fn a_refusal_answers_the_bytes_of_its_problem_and_carries_its_note_apart() { + for (error, problem) in [ + ( + ServiceError::concealed(FailedCheck::Visibility), + ProblemCode::ResourceNotFound, + ), + ( + ServiceError::not_authorized(FailedCheck::Scope), + ProblemCode::ProfileNotAuthorized, + ), + ( + ServiceError::unauthenticated(FailedCheck::TokenSignature), + ProblemCode::AuthenticationRefused, + ), + ( + ServiceError::KeySourceUnavailable, + ProblemCode::ServiceUnavailable, + ), + ] { + let response = refusal_response(error); + let plain = problem_response(problem); + assert_eq!(response.status(), plain.status()); + // Each answer is under its own server-created trace. + for (name, value) in plain.headers() { + if name != "traceparent" && name != "tracestate" { + assert_eq!(response.headers().get(name), Some(value), "{name}"); + } + } + let note = response.extensions().get::().unwrap(); + assert_eq!(Some(note.check), error.failed_check()); + assert_eq!( + note.remedy.is_some(), + note.check == FailedCheck::Scope, + "only a scope refusal carries a remedy" + ); + } + let plain = refusal_response(ServiceError::from(ProblemCode::RequestInvalid)); + assert!(plain.extensions().get::().is_none()); + } + + #[test] + fn a_path_id_that_is_not_an_id_names_nothing() { + assert_eq!( + identifier("not-a-uuid"), + Err(ServiceError::concealed(FailedCheck::Visibility)) + ); + assert!(identifier(&Uuid::nil().to_string()).is_ok()); + } + #[test] fn the_idempotency_key_is_present_bounded_and_graphical() { let with = |value: &str| { diff --git a/crates/registry-documents/src/metrics.rs b/crates/registry-documents/src/metrics.rs index 1fee8e7dfe..63a7f92c94 100644 --- a/crates/registry-documents/src/metrics.rs +++ b/crates/registry-documents/src/metrics.rs @@ -39,6 +39,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::{record_refusal, DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ sample_error_class, CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -154,6 +155,9 @@ pub struct QueueDepth { pub struct Metrics { requests: CounterVec, sample_failures: CounterVec, + /// Counts and logs each refusal by the check it failed; its counter is + /// `documents_request_refusals_total`. + refusals: RefusalRecorder, started: Instant, /// Seconds after `started` at which each worker last completed a pass. last_success: [AtomicU64; 1], @@ -183,6 +187,7 @@ impl Default for Metrics { LabelSpace::closed_zero_filled(&["sample"], &samples).expect(DECLARATION), ) .expect(DECLARATION), + refusals: RefusalRecorder::new("documents").expect(DECLARATION), started: Instant::now(), last_success: [AtomicU64::new(0)], } @@ -206,6 +211,18 @@ impl Metrics { ); } + /// Count one refusal under the check it failed and write the log line + /// the recorder admits. + pub fn record_refusal(&self, note: RefusalNote) { + record_refusal!(self.refusals, note); + } + + /// As [`Self::record_refusal`], and a scope refusal's line also names the + /// values the deployment declared for it. + pub fn record_refusal_declaring(&self, note: RefusalNote, declared: Option<&DeclaredScope>) { + record_refusal!(self.refusals, note, declared = declared); + } + /// Record that `worker` just completed a pass. pub fn record_worker_success(&self, worker: Worker) { self.record_worker_success_at(worker, self.started.elapsed().as_secs()); @@ -231,6 +248,7 @@ impl Metrics { let mut out = Exposition::new(); self.requests.write(&mut out).expect(DECLARATION); self.sample_failures.write(&mut out).expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); write_queue( &mut out, "documents_verification_jobs", @@ -347,7 +365,9 @@ fn status_class(status: StatusCode) -> &'static str { } /// Count every answered request on the serving listener under the route -/// template it matched. +/// template it matched, and every refusal under the check it failed. The +/// refusal rides the response's extensions, which are never serialized, so +/// recording it cannot change a byte of the answer. pub async fn count_requests( State(metrics): State>, request: Request, @@ -361,6 +381,9 @@ pub async fn count_requests( let method = request.method().clone(); let response = next.run(request).await; metrics.record_request(&route, &method, response.status()); + if let Some(note) = response.extensions().get::() { + metrics.record_refusal_declaring(*note, response.extensions().get::()); + } response } @@ -516,6 +539,7 @@ pub async fn serve_metrics(State(state): State) -> Response { #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; fn depth(by_state: &[(&str, i64)], oldest: i64) -> QueueDepth { QueueDepth { @@ -549,6 +573,29 @@ mod tests { )); } + #[test] + fn the_refusal_counter_lists_every_check_from_zero_and_counts_by_check() { + let metrics = Metrics::default(); + let text = metrics.render(&Sampled::default()); + for check in FailedCheck::ALL { + assert!( + text.contains(&format!( + "documents_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + )), + "{}", + check.as_str() + ); + } + metrics.record_refusal(RefusalNote::new(FailedCheck::Scope)); + metrics.record_refusal(RefusalNote::new(FailedCheck::Scope)); + metrics.record_refusal(RefusalNote::new(FailedCheck::Visibility)); + let text = metrics.render(&Sampled::default()); + assert!(text.contains("documents_request_refusals_total{check=\"scope\"} 2")); + assert!(text.contains("documents_request_refusals_total{check=\"visibility\"} 1")); + assert!(text.contains("documents_request_refusals_total{check=\"ownership\"} 0")); + } + #[test] fn every_status_has_its_own_bounded_class() { let class = |code: u16| status_class(StatusCode::from_u16(code).unwrap()); diff --git a/crates/registry-documents/src/runtime.rs b/crates/registry-documents/src/runtime.rs index 456cde783c..f0a08189f8 100644 --- a/crates/registry-documents/src/runtime.rs +++ b/crates/registry-documents/src/runtime.rs @@ -397,6 +397,9 @@ async fn prepare_with( )), None => None, }; + let admitted = config + .admitted_clients(&project) + .map_err(|finding| RuntimeConfigError::Refused(vec![finding]))?; // The sweep changes what the instances already serving release, so it // runs only once every step that could refuse this start has succeeded. let suspended = sweep_bindings(&store, verifier.binding_digest()) @@ -412,7 +415,7 @@ async fn prepare_with( ); } let authenticator = Arc::new(DocumentsAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), keys, AccessProfiles::new(&project), config.binds_assertion_issuers(), @@ -751,7 +754,7 @@ async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; Ok(DocumentsAudit::new(writer, profile.key_hasher())) @@ -881,6 +884,19 @@ impl Prepared { self.hook_delivery.deliver_once().await } + /// Exercise the shared operator replay against a replay-enabled test delivery. + #[cfg(feature = "postgres-test")] + pub async fn replay_hook_for_test( + &self, + event_id: uuid::Uuid, + compiled_delivery_id: &str, + generation: i64, + ) -> Result { + self.hook_delivery + .replay_for_test(event_id, compiled_delivery_id, generation) + .await + } + /// One drain of the content verification worker per call, stopping /// early once `stopped` turns true. fn drain( diff --git a/crates/registry-documents/src/schema.rs b/crates/registry-documents/src/schema.rs index c8703c1fe1..425c6a0782 100644 --- a/crates/registry-documents/src/schema.rs +++ b/crates/registry-documents/src/schema.rs @@ -803,21 +803,32 @@ fn install_runtime_constraints(schema: &mut Value) { set_definition_property(schema, definition, property, "pattern", json!("^/")); } // Every access profile resolves its caller from the matched client, so - // a Document Store deployment always lists the clients it admits. The + // a Document Store deployment always states the clients it admits. The // shared block also admits the keyword `unrestricted`, which this - // runtime refuses in every mode, so the member is restated as the list - // alone and the shared definition is dropped. + // runtime refuses in every mode, so the member is restated as + // `from-package` or the list and the shared definition is dropped. if let Some(clients) = schema.pointer_mut("/$defs/OidcConfig/properties/allowedClients") { *clients = json!({ - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "type": "array", - "items": {"type": "string", "minLength": 1}, - "minItems": 1, - "uniqueItems": true, + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + {"type": "string", "const": "from-package"}, + { + "type": "array", + "items": {"type": "string", "minLength": 1}, + "minItems": 1, + "uniqueItems": true, + }, + ], }); } + if let Some(issuers) = + schema.pointer_mut("/$defs/OidcConfig/properties/assertionIssuers/description") + { + *issuers = json!("Assertion authorities each client may exchange a subject token from,\nkeyed by client identifier. Omitted, no assertion-issuer rule applies;\nwritten, it lists at least one client, each with at least one\nauthority. Once a client is listed, a token it exchanged is accepted\nonly for one of that client's declared authorities, and a client that\nis not listed may exchange from no authority."); + } if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { definitions.remove("OidcAllowedClients"); + definitions.remove("OidcPackageAllowedClients"); } if let Some(providers) = schema .pointer_mut("/$defs/SecretProvidersConfig") @@ -923,9 +934,16 @@ mod tests { ); } let clients = &document["$defs"]["OidcConfig"]["properties"]["allowedClients"]; - assert_eq!(clients["type"], "array"); - assert_eq!(clients["minItems"], 1); + let forms = clients["oneOf"].as_array().expect("two written forms"); + assert_eq!(forms.len(), 2, "{clients}"); + assert_eq!(forms[0], json!({"type": "string", "const": "from-package"})); + assert_eq!(forms[1]["type"], "array"); + assert_eq!(forms[1]["minItems"], 1); + assert_eq!(forms[1]["uniqueItems"], true); + assert_eq!(forms[1]["items"]["minLength"], 1); + assert!(clients.get("$ref").is_none(), "{clients}"); assert!(document["$defs"].get("OidcAllowedClients").is_none()); + assert!(document["$defs"].get("OidcPackageAllowedClients").is_none()); } #[test] diff --git a/crates/registry-documents/src/service.rs b/crates/registry-documents/src/service.rs index 921abefd85..d737abe19b 100644 --- a/crates/registry-documents/src/service.rs +++ b/crates/registry-documents/src/service.rs @@ -29,6 +29,7 @@ use registry_documents_core::{ ReservationView, ReserveDocumentRequest, Reserver, Standing, UploadState, VerificationState, MAXIMUM_PAGE_SIZE, UPLOAD_CONTENT_PATH, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_canonical_json::canonicalize_json; use registry_platform_dispatch::postgres::{enqueue, JobKey, JobTable}; use registry_platform_objectstore::ObjectStoreError; @@ -218,10 +219,197 @@ fn checked(parsed: Option) -> String { parsed.map_or_else(|| UNPARSED.to_owned(), |value| value.to_string()) } +/// The problem codes that refuse a caller's authority, or conceal a target +/// the caller may not see. A refusal is built with the check it failed +/// ([`ServiceError::Refused`]), never from the bare code, so the operator's +/// counter and log line can name the check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefusalCode { + AuthenticationRefused, + CustodyNotPermitted, + ProfileNotAuthorized, + ResourceNotFound, +} + +impl RefusalCode { + /// The problem this refusal answers with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + match self { + Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, + Self::CustodyNotPermitted => ProblemCode::CustodyNotPermitted, + Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, + Self::ResourceNotFound => ProblemCode::ResourceNotFound, + } + } + + /// Sort a problem into a refusal or a plain answer. The match names every + /// code, so a code added to the vocabulary does not compile until it + /// declares which side it is on. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn of(problem: ProblemCode) -> Option { + match problem { + ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), + ProblemCode::CustodyNotPermitted => Some(Self::CustodyNotPermitted), + ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), + ProblemCode::ResourceNotFound => Some(Self::ResourceNotFound), + ProblemCode::CustodyQuotaExceeded + | ProblemCode::DocumentGrantExpiryOutOfRange + | ProblemCode::DocumentPolicyUnknown + | ProblemCode::DocumentVersionNotReleasable + | ProblemCode::DocumentContentTypeNotAllowed + | ProblemCode::DocumentTooLarge + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ServiceUnavailable + | ProblemCode::UploadContentTypeMismatch + | ProblemCode::UploadDigestMismatch + | ProblemCode::UploadExpired + | ProblemCode::UploadFinalized + | ProblemCode::UploadLengthMismatch => None, + } + } +} + +/// A problem code that is not a refusal of authority. The only way to build +/// one is [`PlainProblem::new`], which refuses a code [`RefusalCode::of`] +/// maps, so a refusal cannot be answered without the check it failed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct PlainProblem(ProblemCode); + +impl PlainProblem { + /// `problem` as a plain problem, or `None` when it is a refusal code. + #[must_use] + pub fn new(problem: ProblemCode) -> Option { + match RefusalCode::of(problem) { + None => Some(Self(problem)), + Some(_) => None, + } + } + + /// The problem the caller is answered with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + self.0 + } +} + +/// Why an operation answered a problem. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ServiceError { + /// A problem that is not a refusal of authority: validation, a conflict, + /// an idempotency answer, or an outage. A refusal code is built as + /// `Refused`. + Problem(PlainProblem), + /// A refusal of authority, with the check it failed. + Refused { + code: RefusalCode, + check: FailedCheck, + }, + /// The verifier could not reach or use its key source. The caller is + /// answered `service.unavailable`, and the operator's record names the + /// check. + KeySourceUnavailable, +} + +impl ServiceError { + /// A refusal that conceals a target the caller may not see: the row is + /// absent or foreign, and the answer does not say which. + #[must_use] + pub const fn concealed(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::ResourceNotFound, + check, + } + } + + /// A refusal of a caller that sees the target but may not act on it. + #[must_use] + pub const fn not_authorized(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::ProfileNotAuthorized, + check, + } + } + + /// A refusal to place a document in custody. + #[must_use] + pub const fn custody(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::CustodyNotPermitted, + check, + } + } + + /// A refusal of a credential or of the identity claims it carries. + #[must_use] + pub const fn unauthenticated(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::AuthenticationRefused, + check, + } + } + + /// The problem the caller is answered with. + #[must_use] + pub const fn problem(&self) -> ProblemCode { + match self { + Self::Problem(problem) => problem.problem(), + Self::Refused { code, .. } => code.problem(), + Self::KeySourceUnavailable => ProblemCode::ServiceUnavailable, + } + } + + /// The check this answer failed, when it is a refusal. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> Option { + match self { + Self::Problem(_) => None, + Self::Refused { check, .. } => Some(*check), + Self::KeySourceUnavailable => Some(FailedCheck::KeySourceUnavailable), + } + } +} + +impl From for ServiceError { + /// A problem that is not a refusal. A refusal code reaching this + /// conversion has no check to record, which is a defect in the caller: + /// it is logged and answered `service.unavailable`, never as a refusal + /// the operator cannot account for. + fn from(problem: ProblemCode) -> Self { + if let Some(plain) = PlainProblem::new(problem) { + return Self::Problem(plain); + } + tracing::error!( + code = problem.code(), + "a refusal was built without the check it failed" + ); + Self::Problem(PlainProblem(ProblemCode::ServiceUnavailable)) + } +} + +/// The answer to a custody placement the policy refused. Every refusal of +/// [`place_custody`] is one of the caller's profile or request naming custody +/// it may not place, so the check is the operation. +fn custody_refusal(problem: ProblemCode) -> ServiceError { + match RefusalCode::of(problem) { + Some(RefusalCode::CustodyNotPermitted) => ServiceError::custody(FailedCheck::Operation), + Some(_) | None => problem.into(), + } +} + /// Log a failure the caller is answered `service.unavailable` for. -fn unavailable(stage: &'static str, error: &dyn std::fmt::Display) -> ProblemCode { +fn unavailable(stage: &'static str, error: &dyn std::fmt::Display) -> ServiceError { tracing::error!(stage, error = %error, "a document operation failed"); - ProblemCode::ServiceUnavailable + ServiceError::Problem(PlainProblem(ProblemCode::ServiceUnavailable)) } fn timestamp(value: DateTime) -> String { @@ -455,7 +643,7 @@ fn key_digest(caller: &Caller, operation: &str, key: &str) -> String { } /// The digest of a request body in canonical JSON. -fn request_digest(body: &impl serde::Serialize) -> Result { +fn request_digest(body: &impl serde::Serialize) -> Result { let value = serde_json::to_value(body).map_err(|error| unavailable("request digest", &error))?; let canonical = @@ -479,7 +667,7 @@ async fn replay( transaction: &tokio_postgres::Transaction<'_>, key: &str, request: &str, -) -> Result { +) -> Result { transaction .execute( "SELECT pg_advisory_xact_lock(hashtextextended($1, 1))", @@ -503,10 +691,10 @@ async fn replay( let resource: Uuid = row.try_get(1).map_err(read)?; let expired: bool = row.try_get(2).map_err(read)?; if expired { - return Err(ProblemCode::IdempotencyExpired); + return Err(ProblemCode::IdempotencyExpired.into()); } if recorded != request { - return Err(ProblemCode::IdempotencyKeyReused); + return Err(ProblemCode::IdempotencyKeyReused.into()); } Ok(Replay::Repeat(resource)) } @@ -520,7 +708,7 @@ async fn record_key( request: &str, resource: Uuid, days: i32, -) -> Result<(), ProblemCode> { +) -> Result<(), ServiceError> { transaction .execute( "INSERT INTO documents_idempotency @@ -600,7 +788,7 @@ impl DocumentService { &self.settings.budget } - fn actor_reference(&self, caller: &Caller) -> Result { + fn actor_reference(&self, caller: &Caller) -> Result { self.audit .actor_reference(&caller.issuer, &caller.subject, caller.kind) .map_err(|error| unavailable("audit actor reference", &error)) @@ -610,7 +798,7 @@ impl DocumentService { &self, event: &'static str, record: Value, - ) -> Result { + ) -> Result { self.audit .begin(event, record) .await @@ -620,15 +808,15 @@ impl DocumentService { async fn finish( audit: registry_platform_audit::AuditRequest, event: &'static str, - result: &Result, + result: &Result, success: Value, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let record = match result { Ok(_) => success, Err(problem) => json!({ "event": event, "outcome": "refused", - "code": problem.code(), + "code": problem.problem().code(), }), }; audit @@ -655,7 +843,7 @@ impl DocumentService { policy } - async fn client(&self) -> Result { + async fn client(&self) -> Result { self.store .client() .await @@ -664,7 +852,7 @@ impl DocumentService { /// A protected request is admitted only while this runtime's package /// remains active. Mutations additionally fence their own transaction. - pub(crate) async fn admit(&self) -> Result<(), ProblemCode> { + pub(crate) async fn admit(&self) -> Result<(), ServiceError> { self.store .admit() .await @@ -674,7 +862,7 @@ impl DocumentService { async fn record_in( client: &C, document_id: Uuid, - ) -> Result, ProblemCode> { + ) -> Result, ServiceError> { client .query_opt( &format!( @@ -690,14 +878,14 @@ impl DocumentService { .transpose() } - async fn record(&self, document_id: Uuid) -> Result, ProblemCode> { + async fn record(&self, document_id: Uuid) -> Result, ServiceError> { let client = self.client().await?; Self::record_in(&**client, document_id).await } /// Whether `caller`, by issuer, subject, and actor kind, holds an /// active grant on `version_id`. - async fn holds_grant(&self, caller: &Caller, version_id: Uuid) -> Result { + async fn holds_grant(&self, caller: &Caller, version_id: Uuid) -> Result { let client = self.client().await?; let row = client .query_one( @@ -719,7 +907,7 @@ impl DocumentService { } /// Decide what `caller` is to `record`. - async fn access(&self, caller: &Caller, record: &Record) -> Result { + async fn access(&self, caller: &Caller, record: &Record) -> Result { let Some(policy) = self.policy(&record.policy_id) else { return Ok(Access::default()); }; @@ -739,7 +927,7 @@ impl DocumentService { /// The view `access` shows of `record`. A version approved under /// another verifier binding, or whose approval names other content, is /// shown `suspended`: it is not releasable now. - fn present(&self, record: &Record, access: Access) -> Result { + fn present(&self, record: &Record, access: Access) -> Result { let mut status = record.status; if status.is_releasable() && record @@ -792,7 +980,7 @@ impl DocumentService { caller: &Caller, key: &str, request: &ReserveDocumentRequest, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -826,7 +1014,7 @@ impl DocumentService { caller: &Caller, key: &str, request: &ReserveDocumentRequest, - ) -> Result { + ) -> Result { let admitted = admit_reservation( &self.project, ReservationAsk { @@ -842,7 +1030,8 @@ impl DocumentService { subject: request.custodian.subject.as_str(), issuing_institution: request.issuing_institution.as_ref().map(ExternalId::as_str), }, - )?; + ) + .map_err(custody_refusal)?; let binding = admitted .policy .binding(admitted.policy_id) @@ -991,7 +1180,7 @@ impl DocumentService { &self, caller: &Caller, record: &Record, - ) -> Result { + ) -> Result { let access = self.access(caller, record).await?; Ok(ReservationView { document: self.present(record, access)?, @@ -1014,7 +1203,7 @@ impl DocumentService { content_type: Option<&str>, content_length: Option, body: S, - ) -> Result + ) -> Result where S: Stream> + Unpin, { @@ -1062,7 +1251,7 @@ impl DocumentService { &self, caller: &Caller, upload_id: Uuid, - ) -> Result { + ) -> Result { let client = self.client().await?; let row = client .query_opt( @@ -1071,14 +1260,14 @@ impl DocumentService { ) .await .map_err(|error| unavailable("reservation read", &error))? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let record = Record::from_row(&row).map_err(|error| unavailable("reservation decode", &error))?; if record.reserver_issuer != caller.issuer || record.reserver_subject != caller.subject || record.reserver_kind != caller.kind { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } Ok(Reservation { record }) } @@ -1090,7 +1279,7 @@ impl DocumentService { content_type: Option<&str>, content_length: Option, body: S, - ) -> Result + ) -> Result where S: Stream> + Unpin, { @@ -1103,31 +1292,33 @@ impl DocumentService { || record.upload_lapsed || record.status.is_erasing()) { - return Err(ProblemCode::UploadExpired); + return Err(ProblemCode::UploadExpired.into()); } if content_type != Some(record.media_type.as_str()) { return Err(if finalized { ProblemCode::UploadFinalized } else { ProblemCode::UploadContentTypeMismatch - }); + } + .into()); } match content_length { Some(length) if length > self.settings.ceiling => { - return Err(ProblemCode::RequestBodyTooLarge) + return Err(ProblemCode::RequestBodyTooLarge.into()) } Some(length) if length != record.length => { return Err(if finalized { ProblemCode::UploadFinalized } else { ProblemCode::UploadLengthMismatch - }) + } + .into()) } _ => {} } let Some(_permit) = self.settings.budget.try_reserve(record.length) else { tracing::warn!("the transfer budget is spent; the upload was refused"); - return Err(ProblemCode::ServiceUnavailable); + return Err(ProblemCode::ServiceUnavailable.into()); }; let deadline = self.settings.deadline.for_length(record.length); let body = match tokio::time::timeout(deadline, read_hashing(body, record.length)).await { @@ -1137,12 +1328,13 @@ impl DocumentService { ProblemCode::UploadFinalized } else { ProblemCode::UploadLengthMismatch - }) + } + .into()) } - Ok(Err(BodyRefusal::Unreadable)) => return Err(ProblemCode::RequestInvalid), + Ok(Err(BodyRefusal::Unreadable)) => return Err(ProblemCode::RequestInvalid.into()), Err(_) => { tracing::warn!("an upload body did not arrive within its transfer deadline"); - return Err(ProblemCode::ServiceUnavailable); + return Err(ProblemCode::ServiceUnavailable.into()); } }; let digest = body.digest(); @@ -1152,11 +1344,11 @@ impl DocumentService { self.current_view(caller, record.document_id).await?, )) } else { - Err(ProblemCode::UploadFinalized) + Err(ProblemCode::UploadFinalized.into()) }; } if digest != record.expected_digest { - return Err(ProblemCode::UploadDigestMismatch); + return Err(ProblemCode::UploadDigestMismatch.into()); } let sha256 = body.sha256_hex; let stored = match self.storage.as_ref() { @@ -1178,7 +1370,7 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? @@ -1196,7 +1388,7 @@ impl DocumentService { record: &Record, sha256: &str, bytes: Vec, - ) -> Result { + ) -> Result { let object_id = Uuid::new_v4(); let store = self .storage @@ -1275,7 +1467,7 @@ impl DocumentService { record: &Record, digest: &str, stored: Stored, - ) -> Result { + ) -> Result { let version_id = record.version_id; let mut client = self.client().await?; let transaction = client @@ -1302,9 +1494,9 @@ impl DocumentService { let erasing: bool = row.try_get(3).map_err(read)?; match state.as_str() { "finalized" if computed.as_deref() == Some(digest) => return Ok(false), - "finalized" => return Err(ProblemCode::UploadFinalized), - "expired" => return Err(ProblemCode::UploadExpired), - _ if lapsed || erasing => return Err(ProblemCode::UploadExpired), + "finalized" => return Err(ProblemCode::UploadFinalized.into()), + "expired" => return Err(ProblemCode::UploadExpired.into()), + _ if lapsed || erasing => return Err(ProblemCode::UploadExpired.into()), _ => {} } if !pin_storage(&*transaction, &self.storage) @@ -1386,14 +1578,14 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } self.present(&record, access) } @@ -1403,7 +1595,7 @@ impl DocumentService { &self, caller: &Caller, page: &PageRequest, - ) -> Result { + ) -> Result { let (after, after_id) = Cursor::bounds(page.cursor); let rows = { let client = self.client().await?; @@ -1464,7 +1656,7 @@ impl DocumentService { caller: &Caller, document_id: Uuid, version_id: Uuid, - ) -> Result { + ) -> Result { let started = Instant::now(); let reference = self.actor_reference(caller)?; let audit = self @@ -1502,7 +1694,7 @@ impl DocumentService { json!({ "event": CONTENT_DOWNLOAD_EVENT, "outcome": "refused", - "code": problem.code(), + "code": problem.problem().code(), }), Err(problem), ), @@ -1512,7 +1704,7 @@ impl DocumentService { "outcome": "storage-integrity", "byteCount": 0, }), - Err(ProblemCode::ServiceUnavailable), + Err(ProblemCode::ServiceUnavailable.into()), ), Err(Release::Unavailable) => ( json!({ @@ -1520,7 +1712,7 @@ impl DocumentService { "outcome": "storage-unavailable", "byteCount": 0, }), - Err(ProblemCode::ServiceUnavailable), + Err(ProblemCode::ServiceUnavailable.into()), ), }; audit @@ -1545,7 +1737,7 @@ impl DocumentService { .record(document_id) .await? .filter(|record| record.version_id == version_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; let digest = self.releasable(&record, access)?; let Some(permit) = self.settings.budget.try_reserve(record.length) else { @@ -1570,13 +1762,17 @@ impl DocumentService { /// The digest `access` may be released of `record`, or the answer to a /// caller that may not have its content. - fn releasable<'a>(&self, record: &'a Record, access: Access) -> Result<&'a str, ProblemCode> { + fn releasable<'a>(&self, record: &'a Record, access: Access) -> Result<&'a str, ServiceError> { match record.releasable_digest(&self.settings.verifier_binding) { Some(digest) if access.standing.custodian || access.released_by_grant => Ok(digest), - None if access.standing.custodian => Err(ProblemCode::DocumentVersionNotReleasable), + None if access.standing.custodian => { + Err(ProblemCode::DocumentVersionNotReleasable.into()) + } // The owning system sees the document but is never released it. - _ if access.standing.sees() => Err(ProblemCode::ProfileNotAuthorized), - _ => Err(ProblemCode::ResourceNotFound), + _ if access.standing.sees() => { + Err(ServiceError::not_authorized(FailedCheck::Ownership)) + } + _ => Err(ServiceError::concealed(FailedCheck::Visibility)), } } @@ -1633,16 +1829,22 @@ fn integrity(version: Uuid, error: &StorageError) -> Release { /// Why a release did not happen. enum Release { - Refused(ProblemCode), + Refused(ServiceError), /// The stored content failed its integrity check. Integrity, /// The content storage could not be read. Unavailable, } +impl From for Release { + fn from(error: ServiceError) -> Self { + Self::Refused(error) + } +} + impl From for Release { fn from(problem: ProblemCode) -> Self { - Self::Refused(problem) + Self::Refused(problem.into()) } } @@ -1650,6 +1852,95 @@ impl From for Release { mod tests { use super::*; + #[test] + fn every_problem_is_sorted_into_a_refusal_or_a_plain_answer() { + let refusals: Vec = ProblemCode::ALL + .iter() + .copied() + .filter(|problem| RefusalCode::of(*problem).is_some()) + .collect(); + assert_eq!( + refusals, + [ + ProblemCode::AuthenticationRefused, + ProblemCode::CustodyNotPermitted, + ProblemCode::ProfileNotAuthorized, + ProblemCode::ResourceNotFound, + ] + ); + for problem in ProblemCode::ALL { + if let Some(code) = RefusalCode::of(*problem) { + assert_eq!(code.problem(), *problem); + } + } + } + + #[test] + fn a_plain_problem_converts_and_a_bare_refusal_code_does_not_become_a_refusal() { + for problem in ProblemCode::ALL { + let error = ServiceError::from(*problem); + match RefusalCode::of(*problem) { + None => assert_eq!( + error, + ServiceError::Problem(PlainProblem::new(*problem).unwrap()) + ), + Some(_) => assert_eq!( + error, + ServiceError::from(ProblemCode::ServiceUnavailable), + "{problem:?}" + ), + } + assert_eq!(error.failed_check(), None); + } + } + + #[test] + fn a_refusal_answers_its_code_and_names_its_check() { + let cases = [ + ( + ServiceError::unauthenticated(FailedCheck::TokenClaims), + ProblemCode::AuthenticationRefused, + FailedCheck::TokenClaims, + ), + ( + ServiceError::not_authorized(FailedCheck::Ownership), + ProblemCode::ProfileNotAuthorized, + FailedCheck::Ownership, + ), + ( + ServiceError::custody(FailedCheck::Operation), + ProblemCode::CustodyNotPermitted, + FailedCheck::Operation, + ), + ( + ServiceError::concealed(FailedCheck::Visibility), + ProblemCode::ResourceNotFound, + FailedCheck::Visibility, + ), + ( + ServiceError::KeySourceUnavailable, + ProblemCode::ServiceUnavailable, + FailedCheck::KeySourceUnavailable, + ), + ]; + for (error, problem, check) in cases { + assert_eq!(error.problem(), problem); + assert_eq!(error.failed_check(), Some(check)); + } + } + + #[test] + fn a_custody_refusal_names_the_operation() { + assert_eq!( + custody_refusal(ProblemCode::CustodyNotPermitted), + ServiceError::custody(FailedCheck::Operation) + ); + assert_eq!( + custody_refusal(ProblemCode::DocumentPolicyUnknown), + ServiceError::from(ProblemCode::DocumentPolicyUnknown) + ); + } + #[test] fn the_upload_path_names_the_upload() { let id = Uuid::nil(); diff --git a/crates/registry-documents/src/service/erasure.rs b/crates/registry-documents/src/service/erasure.rs index aff8421e6e..2daedf5935 100644 --- a/crates/registry-documents/src/service/erasure.rs +++ b/crates/registry-documents/src/service/erasure.rs @@ -12,11 +12,12 @@ //! the version is due. No grant expiry or revocation ever starts this clock. use registry_documents_core::{may_request_erasure, Caller, DocumentView, ProblemCode}; +use registry_platform_authcommon::FailedCheck; use serde_json::{json, Value}; use tokio_postgres::Transaction; use uuid::Uuid; -use super::{timestamp, unavailable, DocumentService}; +use super::{timestamp, unavailable, DocumentService, ServiceError}; use crate::audit::ERASURE_REQUEST_EVENT; use crate::hooks::GrantChange; @@ -38,7 +39,7 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -71,22 +72,22 @@ impl DocumentService { &self, caller: &Caller, document_id: Uuid, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } if !may_request_erasure(access.standing) { - return Err(ProblemCode::ProfileNotAuthorized); + return Err(ServiceError::not_authorized(FailedCheck::Ownership)); } // A custodian sees the document only under a declared policy. let policy = self .policy(&record.policy_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let grace = i32::try_from(policy.mandatory_restrictions.cleanup_grace_hours.get()) .map_err(|error| unavailable("erasure grace", &error))?; let version_id = record.version_id; @@ -193,7 +194,7 @@ impl DocumentService { pub(super) async fn refuse_erasing( transaction: &Transaction<'_>, version_id: Uuid, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let erasing: bool = transaction .query_one( "SELECT erasure_state <> 'none' FROM documents_versions @@ -204,7 +205,7 @@ impl DocumentService { .and_then(|row| row.try_get(0)) .map_err(|error| unavailable("grant erasure check", &error))?; if erasing { - return Err(ProblemCode::DocumentVersionNotReleasable); + return Err(ProblemCode::DocumentVersionNotReleasable.into()); } Ok(()) } diff --git a/crates/registry-documents/src/service/grants.rs b/crates/registry-documents/src/service/grants.rs index 5bd8d55609..f55bb9c6f6 100644 --- a/crates/registry-documents/src/service/grants.rs +++ b/crates/registry-documents/src/service/grants.rs @@ -17,6 +17,7 @@ use registry_documents_core::{ grant_expiry_hours, ActorKind, Caller, DocumentGrantPage, DocumentGrantView, GrantState, GranteeRef, IssueGrantRequest, ProblemCode, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_yaml::ExternalId; use serde_json::{json, Value}; use tokio_postgres::Row; @@ -24,7 +25,7 @@ use uuid::Uuid; use super::{ checked, key_digest, next_cursor, record_key, replay, request_digest, timestamp, unavailable, - Cursor, DocumentService, PageRequest, Record, Replay, + Cursor, DocumentService, PageRequest, Record, Replay, ServiceError, }; use crate::audit::{GRANT_ISSUE_EVENT, GRANT_REVOKE_EVENT}; use crate::hooks::{DocumentEvent, GrantChange}; @@ -101,14 +102,14 @@ impl Grant { } } -fn decode_grants(rows: &[Row]) -> Result, ProblemCode> { +fn decode_grants(rows: &[Row]) -> Result, ServiceError> { rows.iter() .map(Grant::from_row) .collect::, _>>() .map_err(|error| unavailable("grant decode", &error)) } -fn grant_views(grants: &[Grant], limit: u32) -> Result, ProblemCode> { +fn grant_views(grants: &[Grant], limit: u32) -> Result, ServiceError> { grants .iter() .take(limit as usize) @@ -132,14 +133,14 @@ impl DocumentService { caller: &Caller, document_id: Uuid, managing: bool, - ) -> Result { + ) -> Result { let record = self .record(document_id) .await? - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let access = self.access(caller, &record).await?; if !access.sees() { - return Err(ProblemCode::ResourceNotFound); + return Err(ServiceError::concealed(FailedCheck::Visibility)); } let allowed = if managing { access.standing.may_grant @@ -147,7 +148,15 @@ impl DocumentService { access.standing.may_list_grants() }; if !allowed { - return Err(ProblemCode::ProfileNotAuthorized); + // A caller that sees the document and does not hold custody of it + // is refused because the document belongs to another caller. A + // custodian is refused because its profile has no grant authority. + let check = if access.standing.custodian { + FailedCheck::Operation + } else { + FailedCheck::Ownership + }; + return Err(ServiceError::not_authorized(check)); } Ok(record) } @@ -162,7 +171,7 @@ impl DocumentService { key: &str, document_id: Uuid, request: &IssueGrantRequest, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let version_id = Uuid::parse_str(&request.version_id).ok(); let audit = self @@ -200,20 +209,20 @@ impl DocumentService { document_id: Uuid, version_id: Option, request: &IssueGrantRequest, - ) -> Result { + ) -> Result { let record = self.grantable(caller, document_id, true).await?; let version_id = version_id .filter(|id| *id == record.version_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; if record .releasable_digest(&self.settings.verifier_binding) .is_none() { - return Err(ProblemCode::DocumentVersionNotReleasable); + return Err(ProblemCode::DocumentVersionNotReleasable.into()); } let policy = self .policy(&record.policy_id) - .ok_or(ProblemCode::ResourceNotFound)?; + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))?; let hours = i32::try_from(grant_expiry_hours(policy, request.expiry_hours)?) .map_err(|_| ProblemCode::RequestUnprocessable)?; let days = i32::try_from(self.settings.idempotency_days) @@ -289,7 +298,7 @@ impl DocumentService { &self, caller: &Caller, grant_id: Uuid, - ) -> Result { + ) -> Result { let reference = self.actor_reference(caller)?; let audit = self .begin( @@ -319,7 +328,7 @@ impl DocumentService { &self, caller: &Caller, grant_id: Uuid, - ) -> Result { + ) -> Result { let document_id: Uuid = { let client = self.client().await?; client @@ -329,7 +338,7 @@ impl DocumentService { ) .await .map_err(|error| unavailable("grant read", &error))? - .ok_or(ProblemCode::ResourceNotFound)? + .ok_or_else(|| ServiceError::concealed(FailedCheck::Visibility))? .try_get(0) .map_err(|error| unavailable("grant decode", &error))? }; @@ -390,7 +399,7 @@ impl DocumentService { caller: &Caller, grant_id: Uuid, change: GrantChange, - ) -> Result<(), ProblemCode> { + ) -> Result<(), ServiceError> { let event = DocumentEvent::grant(transaction, grant_id, change, caller.kind) .await .map_err(|error| unavailable("grant event read", &error))?; @@ -407,7 +416,7 @@ impl DocumentService { caller: &Caller, document_id: Uuid, page: &PageRequest, - ) -> Result { + ) -> Result { self.grantable(caller, document_id, false).await?; let (after, after_id) = Cursor::bounds(page.cursor); let client = self.client().await?; @@ -440,7 +449,7 @@ impl DocumentService { &self, caller: &Caller, page: &PageRequest, - ) -> Result { + ) -> Result { let (after, after_id) = Cursor::bounds(page.cursor); let policies: Vec<&str> = self .project diff --git a/crates/registry-documents/src/store.rs b/crates/registry-documents/src/store.rs index c67a28bc25..96d846c77c 100644 --- a/crates/registry-documents/src/store.rs +++ b/crates/registry-documents/src/store.rs @@ -18,11 +18,16 @@ use tokio_postgres::Config as PgConfig; use crate::config::{describe_secret_failure, DatabaseConfig}; const DOCUMENTS_MIGRATION: &str = include_str!("../migrations/0100_documents.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0101_activation_posture.sql"); /// Every schema version, in the order it is applied. Readiness requires the /// applied set to be exactly this list. The 1.0 baseline is version /// [`BASELINE_SCHEMA_VERSION`]; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 1] = [(100, DOCUMENTS_MIGRATION)]; +pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ + (100, DOCUMENTS_MIGRATION), + (101, ACTIVATION_POSTURE_MIGRATION), +]; /// The 1.0 baseline schema version, shared with the other products. const BASELINE_SCHEMA_VERSION: i64 = 100; const _: () = assert!( diff --git a/crates/registry-documents/tests/golden/refusals.json b/crates/registry-documents/tests/golden/refusals.json new file mode 100644 index 0000000000..8afc5cadaf --- /dev/null +++ b/crates/registry-documents/tests/golden/refusals.json @@ -0,0 +1,489 @@ +{ + "agent-actor-kind": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "another-actor-kind": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "another-scheme": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "client-no-profile-lists": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "download-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "download-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "empty-bearer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "erasure-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "erasure-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "exchanged-token": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "expired": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "foreign-audience": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "foreign-issuer": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "forged-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "grant-issued-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grant-issued-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "grant-on-another-version": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grants-listed-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "grants-listed-by-the-reserving-system": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "malformed-actor-kind": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "missing-scope": { + "body": { + "code": "profile.not-authorized", + "detail": "The caller's access profile does not permit this operation.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-documents/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "no-authorization-header": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "not-a-compact-token": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "principal-outside-its-grammar": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "read-by-a-stranger": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "read-of-a-malformed-id": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "read-of-an-absent-document": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "reservation-by-a-recipient-profile": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "reservation-for-another-custodian-by-a-person": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "reservation-outside-the-custody-profiles": { + "body": { + "code": "custody.not-permitted", + "detail": "The caller's access profile may not place a document in this custody, or the request names an issuing institution other than the profile's.", + "status": 403, + "title": "Custody not permitted", + "type": "https://id.registrystack.org/problems/registry-documents/custody/not-permitted" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "revoke-of-an-absent-grant": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "unadmitted-client": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-documents/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "upload-by-another-caller": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + }, + "upload-to-an-absent-reservation": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource does not exist or is not available to the caller.", + "status": 404, + "title": "Not found", + "type": "https://id.registrystack.org/problems/registry-documents/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 404 + } +} diff --git a/crates/registry-documents/tests/migration_pins.rs b/crates/registry-documents/tests/migration_pins.rs index 5a5d9ee276..b59de6db40 100644 --- a/crates/registry-documents/tests/migration_pins.rs +++ b/crates/registry-documents/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0100_documents.sql", - "d21dae145068a46052af7ec69076ad2bdf883a0e550325db66c811380fe91575", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0100_documents.sql", + "d21dae145068a46052af7ec69076ad2bdf883a0e550325db66c811380fe91575", + ), + ( + "0101_activation_posture.sql", + "b984c63d7402d024752955aed60dd3b9b5dd821a0210ca64a0e1bbc1a6ec1df9", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-documents/tests/postgres_documents.rs b/crates/registry-documents/tests/postgres_documents.rs index 2a698aadf2..7067397615 100644 --- a/crates/registry-documents/tests/postgres_documents.rs +++ b/crates/registry-documents/tests/postgres_documents.rs @@ -1180,7 +1180,7 @@ async fn a_verification_audit_failure_refuses_the_claim_and_records_no_verdict() .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FailingSink)), + AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -2537,7 +2537,7 @@ async fn a_request_audit_failure_refuses_the_upload_and_the_download() { fn failing_audit() -> DocumentsAudit { DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FailingSink)), + AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -2752,7 +2752,9 @@ async fn a_response_audit_failure_after_commit_answers_unavailable_and_the_retry .await .expect("the runtime prepares") .with_audit(DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(FirstLineSink { kept: kept.clone() })), + AuditWriter::from_line_sink_without_posture(Box::new(FirstLineSink { + kept: kept.clone(), + })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -3889,9 +3891,9 @@ async fn the_runtime_is_ready_only_while_the_ledger_names_its_package_active() { .execute(&format!( "INSERT INTO documents_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, 'sha256:{}', package_digest, \ - database_id, 'successor', now(), role_mode \ + database_id, 'successor', now(), role_mode, posture \ FROM documents_activations ORDER BY apply_order DESC LIMIT 1", "0".repeat(64) )) diff --git a/crates/registry-documents/tests/postgres_hooks.rs b/crates/registry-documents/tests/postgres_hooks.rs index 8bae9056db..2457e3f04e 100644 --- a/crates/registry-documents/tests/postgres_hooks.rs +++ b/crates/registry-documents/tests/postgres_hooks.rs @@ -11,17 +11,21 @@ mod support; use std::sync::Arc; +use std::time::SystemTime; -use registry_documents::runtime::{prepare_with_verifier, Prepared, RuntimeError}; +use registry_documents::runtime::{prepare, prepare_with_verifier, Prepared, RuntimeError}; use registry_documents_core::{ DOCUMENT_GRANT_CHANGED_EVENT_SCHEMA_ID, DOCUMENT_VERSION_READY_EVENT_SCHEMA_ID, DOCUMENT_VERSION_REJECTED_EVENT_SCHEMA_ID, }; +use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, +}; use registry_platform_hooks::delivery::DeliveryOutcome; use serde_json::{json, Value}; use support::{ pdf, reservation, Api, Deployment, FakeVerifier, APP, APPROVE, CITIZEN, DATABASE_STORAGE, - DISABLED_VERIFIER, READER, REJECT, STARTER_PROJECT, UNREACHABLE_HOOKS_URL, + DISABLED_VERIFIER, HOOK_KEY, READER, REJECT, STARTER_PROJECT, UNREACHABLE_HOOKS_URL, }; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -29,6 +33,56 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; const PDF: &str = "application/pdf"; const SOURCE: &str = "urn:registrystack:documents:civil-registry-documents"; +fn assert_signed_delivery(request: &wiremock::Request, stored: &[u8], key_bytes: &[&[u8]]) { + assert_eq!(request.body, stored, "the stored canonical bytes are sent"); + let envelope: Value = serde_json::from_slice(stored).unwrap(); + let header = |name: &str| { + request.headers[name] + .to_str() + .unwrap_or_else(|_| panic!("invalid {name} header")) + }; + let mut headers = request + .headers + .keys() + .map(|name| name.as_str()) + .filter(|name| !matches!(*name, "host" | "content-length" | "connection")) + .collect::>(); + headers.sort_unstable(); + assert_eq!( + headers, + [ + "accept", + "content-type", + "webhook-id", + "webhook-signature", + "webhook-timestamp", + ] + ); + assert_eq!(header("accept"), "application/json"); + assert_eq!(header("content-type"), "application/json"); + assert_eq!(header("webhook-id"), envelope["id"].as_str().unwrap()); + + let signature = header("webhook-signature"); + let entries = signature.split(' ').collect::>(); + assert_eq!(entries.len(), key_bytes.len()); + for (entry, bytes) in entries.into_iter().zip(key_bytes) { + assert!(entry.starts_with("v1,"), "invalid signature entry version"); + let keys = DeliveryKeys::new(DeliveryKey::new(bytes).unwrap(), None).unwrap(); + verify( + &keys, + SignedContent { + id: header("webhook-id"), + timestamp: header("webhook-timestamp"), + signature: entry, + body: &request.body, + }, + SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .expect("the signature authenticates the exact received bytes"); + } +} + /// A second observer on `document-version.ready`, so one verdict must /// capture one delivery for each. const READY_MIRROR: &str = " @@ -679,8 +733,16 @@ async fn delivery_sends_the_signed_envelope_and_refuses_a_returned_proposal() { .expect(1) .mount(&receiver) .await; + const PREVIOUS_KEY: &str = "documents-test-previous-key-not-a-secret\n"; let mut deployment = deployment(STARTER_PROJECT).await; deployment.bind_hooks(&format!("{}/document-events", receiver.uri())); + deployment.secret("previous-hook-key", PREVIOUS_KEY); + let runtime = std::fs::read_to_string(&deployment.runtime).unwrap(); + let runtime = runtime.replace( + "hmacSha256KeyRef: secret:file/hook-key", + "hmacSha256KeyRef: secret:file/hook-key\n previousHmacSha256KeyRef: secret:file/previous-hook-key", + ); + std::fs::write(&deployment.runtime, runtime).unwrap(); let verifier = FakeVerifier::new("binding-a", APPROVE); let (prepared, api) = start(&deployment, &verifier).await; let (document, _) = upload(&api, 7).await; @@ -701,24 +763,11 @@ async fn delivery_sends_the_signed_envelope_and_refuses_a_returned_proposal() { let requests = receiver.received_requests().await.unwrap(); assert_eq!(requests.len(), 1); - let request = &requests[0]; - assert_eq!(request.body, stored, "the stored canonical bytes are sent"); - let header = |name: &str| { - request - .headers - .get(name) - .and_then(|value| value.to_str().ok()) - .unwrap_or_else(|| panic!("missing valid {name} header")) - .to_owned() - }; - assert_eq!(header("ce-type"), "document-version-ready"); - assert_eq!(header("ce-source"), SOURCE); - assert_eq!( - header("ce-dataschema"), - DOCUMENT_VERSION_READY_EVENT_SCHEMA_ID + assert_signed_delivery( + &requests[0], + &stored, + &[HOOK_KEY.as_bytes(), PREVIOUS_KEY.as_bytes()], ); - assert!(header("x-registry-signature").starts_with("v1=")); - assert!(header("idempotency-key").starts_with("sha256:")); let state = deployment .admin @@ -761,7 +810,7 @@ async fn a_failing_destination_is_retried_then_dead_lettered_without_touching_th Mock::given(method("POST")) .and(path("/document-events")) .respond_with(ResponseTemplate::new(503)) - .expect(2) + .expect(3) .mount(&receiver) .await; let mut deployment = deployment(STARTER_PROJECT).await; @@ -770,6 +819,13 @@ async fn a_failing_destination_is_retried_then_dead_lettered_without_touching_th let (prepared, api) = start(&deployment, &verifier).await; let (document, _) = upload(&api, 8).await; assert_eq!(prepared.verify_due().await, 1); + let stored: Vec = deployment + .scalar("SELECT payload FROM registry_outbox") + .await; + // Opt the fixture into shared operator replay so the dead letter retains its payload. + deployment + .execute("UPDATE registry_webhook_deliveries SET operator_replay = true") + .await; assert_eq!( prepared.deliver_hooks_once().await.unwrap(), @@ -809,6 +865,37 @@ async fn a_failing_destination_is_retried_then_dead_lettered_without_touching_th .await; assert_eq!(state, "dead-lettered"); + let row = deployment + .admin + .query_one( + &format!( + "SELECT event_id, compiled_delivery_id, generation + FROM {}.registry_webhook_delivery_state", + deployment.schema + ), + &[], + ) + .await + .unwrap(); + let compiled_delivery_id: String = row.get(1); + let generation: i64 = row.get(2); + assert_eq!( + prepared + .replay_hook_for_test(row.get(0), &compiled_delivery_id, generation) + .await + .expect("the shared operator replay reopens the dead letter"), + generation + 1 + ); + assert_eq!( + prepared.deliver_hooks_once().await.unwrap(), + DeliveryOutcome::RetryScheduled + ); + let requests = receiver.received_requests().await.unwrap(); + assert_eq!(requests.len(), 3); + for request in &requests { + assert_signed_delivery(request, &stored, &[HOOK_KEY.as_bytes()]); + } + // The version the event reports stays ready throughout. let read = api.read(CITIZEN, &document).await; assert_eq!(read.json()["version"]["status"], "ready"); @@ -833,6 +920,50 @@ async fn an_unreachable_destination_never_blocks_a_transition() { assert_eq!(delivery_count(&deployment).await, 2); } +#[tokio::test] +async fn startup_reports_invalid_hook_key_bytes_after_the_offline_reference_check() { + let mut deployment = deployment(STARTER_PROJECT).await; + let key = format!("{}\n", "x".repeat(64)); + deployment.secret("hook-key", &key); + + let offline = registry_documents::config::check_runtime_file(&deployment.runtime, false, None); + assert!( + offline.report.is_empty(), + "the offline check accepts the reference" + ); + + let message = hook_key_startup_refusal(&deployment).await; + for detail in [ + "destinations.hooks.owning-system-events.hmacSha256KeyRef", + "65 bytes", + "trailing newline: true", + "Supply 32 to 64 exact key bytes.", + ] { + assert!(message.contains(detail), "{message}"); + } + assert!(!message.contains(&key[..64])); +} + +#[tokio::test] +async fn startup_reports_an_empty_hook_key_file() { + let mut deployment = deployment(STARTER_PROJECT).await; + deployment.secret("hook-key", ""); + + let message = hook_key_startup_refusal(&deployment).await; + assert_eq!( + message, + "destinations.hooks.owning-system-events.hmacSha256KeyRef: the referenced secret value is invalid. Store a non-empty value of at most 64 KiB, without NUL bytes unless the secret is a binary key." + ); +} + +async fn hook_key_startup_refusal(deployment: &Deployment) -> String { + match prepare(&deployment.runtime).await { + Err(RuntimeError::HookActivation(error)) => error.to_string(), + Err(error) => panic!("expected a hook signing key refusal, got {error}"), + Ok(_) => panic!("startup accepted invalid hook key bytes"), + } +} + #[tokio::test] async fn startup_refuses_a_project_hook_whose_destination_is_not_bound() { let project = STARTER_PROJECT.replace( diff --git a/crates/registry-documents/tests/postgres_operator.rs b/crates/registry-documents/tests/postgres_operator.rs index 29121cb3c5..c96ba8cb64 100644 --- a/crates/registry-documents/tests/postgres_operator.rs +++ b/crates/registry-documents/tests/postgres_operator.rs @@ -105,7 +105,7 @@ async fn a_fresh_database_is_refused_by_serve_until_the_package_is_applied() { .await .expect("the package applies"); assert!(applied.recorded); - assert_eq!(applied.schema_versions_applied, vec![100]); + assert_eq!(applied.schema_versions_applied, vec![100, 101]); assert_eq!(applied.activation.plan_kind, PlanKind::Initial); assert_eq!(applied.activation.role_mode, RoleMode::Single); prepare(&deployment.runtime) @@ -123,7 +123,7 @@ async fn plan_reports_the_change_and_writes_nothing() { assert_eq!(plan.change, ActivationChange::Activate); assert_eq!(plan.plan_kind, PlanKind::Initial); assert_eq!(plan.active_digest, None); - assert_eq!(plan.pending_schema_versions, vec![100]); + assert_eq!(plan.pending_schema_versions, vec![100, 101]); assert_eq!(plan.database_id, DatabaseIdCheck::NotRecorded); assert!(plan.refusals.is_empty(), "{:?}", plan.refusals); assert!(plan.package_digest.starts_with("sha256:")); @@ -256,7 +256,7 @@ async fn status_reports_the_active_package_and_its_history() { assert_eq!(active.activation_id, second.activation.activation_id); assert_eq!(active.package_digest, second.activation.package_digest); assert_eq!(active.database_id, "registry-documents-test"); - assert_eq!(status.schema_version, Some(100)); + assert_eq!(status.schema_version, Some(101)); assert_eq!( status .history @@ -1463,7 +1463,7 @@ async fn replay_audited( .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(LimitedSink { lines })), + AuditWriter::from_line_sink_without_posture(Box::new(LimitedSink { lines })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) @@ -1836,7 +1836,7 @@ async fn erasure_replay_audited( .await .unwrap(); let audit = DocumentsAudit::new( - AuditWriter::from_line_sink(Box::new(LimitedSink { lines })), + AuditWriter::from_line_sink_without_posture(Box::new(LimitedSink { lines })), AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new( b"documents-test-audit-key-not-a-secret".to_vec(), )) diff --git a/crates/registry-documents/tests/postgres_startup.rs b/crates/registry-documents/tests/postgres_startup.rs index 6f2f668407..cf01fc052b 100644 --- a/crates/registry-documents/tests/postgres_startup.rs +++ b/crates/registry-documents/tests/postgres_startup.rs @@ -17,7 +17,7 @@ use registry_documents::runtime::{prepare, RuntimeError}; use registry_documents_client::{DocumentsClient, DocumentsClientConfig, ProblemCode}; use support::{ database_url, pdf, reservation_body, sha256, token, Deployment, APP, CITIZEN, DATABASE_STORAGE, - DISABLED_VERIFIER, + DISABLED_VERIFIER, PARTNER_SERVICE, READER, STAFF, }; use url::Url; @@ -129,6 +129,46 @@ async fn a_prepared_runtime_serves_documents_only_to_a_verified_caller() { server.await.unwrap().unwrap(); } +/// The runtime file says `allowedClients: from-package` and lists no client. +/// Each requester client of the package reaches its profile, and a client the +/// package does not name is refused. +#[tokio::test] +async fn a_runtime_that_admits_the_package_clients_serves_a_call_from_each() { + let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + deployment.admit_package_clients(); + let text = std::fs::read_to_string(&deployment.runtime).unwrap(); + assert!(text.contains("allowedClients: from-package"), "{text}"); + deployment.migrate().await; + let prepared = prepare(&deployment.runtime) + .await + .expect("the runtime prepares"); + let address = prepared.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(prepared.serve_until(async { + stopped.await.ok(); + })); + let http = reqwest::Client::new(); + let policies = format!("http://{address}/v1/document-policies"); + for principal in [APP, CITIZEN, READER, STAFF] { + let response = http + .get(&policies) + .bearer_auth(token(principal)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK, "{principal:?}"); + } + let response = http + .get(&policies) + .bearer_auth(token(PARTNER_SERVICE)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED); + stop.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn a_runtime_whose_database_refuses_the_credential_does_not_start() { let mut refused = Url::parse(&database_url()).unwrap(); @@ -168,13 +208,13 @@ async fn applying_the_schema_twice_applies_nothing_twice() { .admin .query( &format!( - "SELECT version FROM {}.documents_schema_migrations", + "SELECT version FROM {}.documents_schema_migrations ORDER BY version", deployment.schema ), &[], ) .await .unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get::<_, i64>(0), 100); + let versions: Vec = rows.iter().map(|row| row.get(0)).collect(); + assert_eq!(versions, [100, 101]); } diff --git a/crates/registry-documents/tests/refusal_golden.rs b/crates/registry-documents/tests/refusal_golden.rs new file mode 100644 index 0000000000..74bbc76f63 --- /dev/null +++ b/crates/registry-documents/tests/refusal_golden.rs @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The refusals of the Document Store, driven over the served router with +//! real tokens, in two checks. +//! +//! The first freezes what a caller is answered: the status, the headers that +//! matter to a client, and the body without its trace, for every refusal of +//! authentication or authority, against `tests/golden/refusals.json`. The +//! file records the answers the runtime gave before refusals were counted by +//! the check they failed. It must not change when the recording changes. +//! +//! The second proves the operator's side of the same refusals: each one adds +//! one to `documents_request_refusals_total` under the fixed check it failed, +//! writes one `request refused` line carrying that check and nothing a caller +//! sent, and answers the same bytes as the first. +//! +//! `DOCUMENTS_UPDATE_GOLDEN=1` rewrites the golden file from the current +//! answers. The database is named by `DOCUMENTS_TEST_DATABASE_URL`. + +mod support; + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use axum::body::Body; +use axum::http::{Method, Request}; +use registry_documents::runtime::{prepare_with_verifier, Prepared}; +use registry_platform_authcommon::FailedCheck; +use serde_json::{json, Value}; +use support::{ + pdf, request, reservation, token, token_with, Answer, Api, Deployment, FakeVerifier, Principal, + APP, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, OTHER_APP, PARTNER_SERVICE, READER, + STRANGER, TEST_AUDIENCE, TEST_ISSUER, +}; +use tower::ServiceExt as _; +use tracing::instrument::WithSubscriber as _; +use uuid::Uuid; + +/// The headers a client reads on a refusal. +const HEADERS: [&str; 4] = [ + "content-type", + "www-authenticate", + "retry-after", + "cache-control", +]; + +/// How a fixture presents its credential. +enum Credential { + Absent, + Header(&'static str), + Token(String), +} + +/// One refusal: its name in the golden file, the check it must be recorded +/// under, and the request that trips it. +struct Fixture { + name: &'static str, + check: FailedCheck, + method: Method, + path: String, + credential: Credential, + body: Option, +} + +impl Fixture { + fn new( + name: &'static str, + check: FailedCheck, + method: Method, + path: &str, + credential: Credential, + ) -> Self { + Self { + name, + check, + method, + path: path.to_owned(), + credential, + body: None, + } + } + + fn get(name: &'static str, check: FailedCheck, path: &str, credential: Credential) -> Self { + Self::new(name, check, Method::GET, path, credential) + } + + fn as_principal( + name: &'static str, + check: FailedCheck, + method: Method, + path: &str, + principal: Principal, + ) -> Self { + Self::new( + name, + check, + method, + path, + Credential::Token(token(principal)), + ) + } + + fn with_body(mut self, body: Value) -> Self { + self.body = Some(body); + self + } + + fn request(&self) -> Request { + let mut builder = Request::builder() + .method(self.method.clone()) + .uri(&self.path); + match &self.credential { + Credential::Absent => {} + Credential::Header(value) => builder = builder.header("authorization", *value), + Credential::Token(token) => { + builder = builder.header("authorization", format!("Bearer {token}")); + } + } + match &self.body { + Some(body) => builder + .header("content-type", "application/json") + .header("idempotency-key", Uuid::new_v4().to_string()) + .body(Body::from(body.to_string())) + .unwrap(), + None => builder.body(Body::empty()).unwrap(), + } + } +} + +/// The deployment, one document held for the citizen, and its ids. +struct World { + deployment: Deployment, + prepared: Prepared, + api: Api, + document: String, + version: String, + upload_path: String, + missing: String, +} + +async fn world() -> World { + world_with_project(support::STARTER_PROJECT).await +} + +async fn world_with_project(project: &str) -> World { + let mut deployment = + Deployment::with_project(DATABASE_STORAGE, DISABLED_VERIFIER, project).await; + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + deployment.configure(&format!("metricsListener:\n bind: 127.0.0.1:{port}\n")); + deployment.migrate().await; + let prepared = prepare_with_verifier( + &deployment.runtime, + FakeVerifier::new("refusal-golden", APPROVE), + ) + .await + .expect("the runtime prepares"); + let api = Api::new(&prepared); + let content = pdf(256, 7); + let reserved = api + .reserve( + APP, + "citizen-delivery", + CITIZEN.subject, + &content, + "application/pdf", + ) + .await; + let (document, version, upload_path) = reservation(&reserved); + World { + deployment, + prepared, + api, + document, + version, + upload_path, + missing: Uuid::new_v4().to_string(), + } +} + +fn claims(name: &str, value: Value) -> Value { + json!({ name: value }) +} + +fn fixtures(world: &World) -> Vec { + let document = &world.document; + let version = &world.version; + let missing = world.missing.clone(); + let reserve = |policy: &str, custodian: &str| { + support::reservation_body( + policy, + custodian, + &support::sha256(&pdf(256, 7)), + 256, + "application/pdf", + ) + }; + let signed = |claims: Value| Credential::Token(token_with(CITIZEN, claims)); + let mut forged = token(CITIZEN); + let signature_at = forged.rfind('.').unwrap() + 1; + forged.replace_range(signature_at.., &"A".repeat(86)); + vec![ + // The credential. + Fixture::get( + "no-authorization-header", + FailedCheck::CredentialMissing, + "/v1/documents", + Credential::Absent, + ), + Fixture::get( + "another-scheme", + FailedCheck::CredentialMissing, + "/v1/documents", + Credential::Header("Basic dXNlcjpwYXNz"), + ), + Fixture::get( + "empty-bearer", + FailedCheck::CredentialMalformed, + "/v1/documents", + Credential::Header("Bearer"), + ), + Fixture::get( + "not-a-compact-token", + FailedCheck::CredentialMalformed, + "/v1/documents", + Credential::Token("not-a-token".to_owned()), + ), + // The token. + Fixture::get( + "forged-signature", + FailedCheck::TokenSignature, + "/v1/documents", + Credential::Token(forged), + ), + Fixture::get( + "foreign-issuer", + FailedCheck::TokenIssuer, + "/v1/documents", + signed(claims("iss", json!("https://other.example.test"))), + ), + Fixture::get( + "foreign-audience", + FailedCheck::TokenAudience, + "/v1/documents", + signed(claims("aud", json!("urn:example:elsewhere"))), + ), + Fixture::get( + "expired", + FailedCheck::TokenTime, + "/v1/documents", + signed(claims("exp", json!(1_600_000_000))), + ), + Fixture::get( + "unadmitted-client", + FailedCheck::TokenClient, + "/v1/documents", + signed(json!({"azp": "unlisted-client", "client_id": "unlisted-client"})), + ), + Fixture::get( + "exchanged-token", + FailedCheck::TokenAssertionIssuer, + "/v1/documents", + signed(claims( + registry_platform_oidc::ASSERTION_ISSUER_CLAIM, + json!("https://partner.example.test"), + )), + ), + // The profile the token resolves to. + Fixture::get( + "missing-scope", + FailedCheck::Scope, + "/v1/documents", + signed(claims("scope", json!("documents:read"))), + ), + // The verifier admits this client and no access profile of the + // starter project lists it. + Fixture::as_principal( + "client-no-profile-lists", + FailedCheck::AccessProfile, + Method::GET, + "/v1/documents", + PARTNER_SERVICE, + ), + Fixture::get( + "another-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!("service"))), + ), + Fixture::get( + "agent-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!("agent"))), + ), + Fixture::get( + "malformed-actor-kind", + FailedCheck::ActorKind, + "/v1/documents", + signed(claims("registry_actor_kind", json!(7))), + ), + Fixture::get( + "principal-outside-its-grammar", + FailedCheck::TokenClaims, + "/v1/documents", + signed(claims("sub", json!("a principal\u{7}with a control"))), + ), + // A document the caller may not see, or not act on. + Fixture::as_principal( + "read-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}"), + STRANGER, + ), + Fixture::as_principal( + "read-of-an-absent-document", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{missing}"), + CITIZEN, + ), + Fixture::as_principal( + "read-of-a-malformed-id", + FailedCheck::Visibility, + Method::GET, + "/v1/documents/not-a-uuid", + CITIZEN, + ), + Fixture::as_principal( + "download-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}/versions/{version}/content"), + STRANGER, + ), + Fixture::as_principal( + "download-by-the-reserving-system", + FailedCheck::Ownership, + Method::GET, + &format!("/v1/documents/{document}/versions/{version}/content"), + APP, + ), + Fixture::as_principal( + "grants-listed-by-a-stranger", + FailedCheck::Visibility, + Method::GET, + &format!("/v1/documents/{document}/grants"), + STRANGER, + ), + Fixture::as_principal( + "grants-listed-by-the-reserving-system", + FailedCheck::Ownership, + Method::GET, + &format!("/v1/documents/{document}/grants"), + APP, + ), + Fixture::as_principal( + "grant-issued-by-a-stranger", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/grants"), + STRANGER, + ) + .with_body( + json!({"versionId": version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "grant-issued-by-the-reserving-system", + FailedCheck::Ownership, + Method::POST, + &format!("/v1/documents/{document}/grants"), + APP, + ) + .with_body( + json!({"versionId": version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "grant-on-another-version", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/grants"), + CITIZEN, + ) + .with_body( + json!({"versionId": missing, "grantee": {"subject": "reader-1", "kind": "human"}}), + ), + Fixture::as_principal( + "revoke-of-an-absent-grant", + FailedCheck::Visibility, + Method::DELETE, + &format!("/v1/document-grants/{missing}"), + CITIZEN, + ), + Fixture::as_principal( + "erasure-by-a-stranger", + FailedCheck::Visibility, + Method::POST, + &format!("/v1/documents/{document}/erasure"), + STRANGER, + ), + Fixture::as_principal( + "erasure-by-the-reserving-system", + FailedCheck::Ownership, + Method::POST, + &format!("/v1/documents/{document}/erasure"), + APP, + ), + // An upload the caller did not reserve. + Fixture::as_principal( + "upload-to-an-absent-reservation", + FailedCheck::Visibility, + Method::PUT, + &format!("/v1/uploads/{missing}/content"), + APP, + ), + Fixture::as_principal( + "upload-by-another-caller", + FailedCheck::Visibility, + Method::PUT, + &world.upload_path, + OTHER_APP, + ), + // Custody the caller's profile may not place. + Fixture::as_principal( + "reservation-by-a-recipient-profile", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + READER, + ) + .with_body(reserve("citizen-delivery", "citizen-1")), + Fixture::as_principal( + "reservation-outside-the-custody-profiles", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + CITIZEN, + ) + .with_body(reserve("citizen-delivery", "citizen-1")), + Fixture::as_principal( + "reservation-for-another-custodian-by-a-person", + FailedCheck::Operation, + Method::POST, + "/v1/documents", + CITIZEN, + ) + .with_body(reserve("named-share", "citizen-2")), + ] +} + +/// The answer to `fixture` and what a client can read of it: the status, the +/// headers in [`HEADERS`], and the problem body without its trace. +async fn observe(api: &Api, fixture: &Fixture) -> (Answer, Value) { + let answer = api.call(fixture.request()).await; + let mut body: Value = serde_json::from_slice(&answer.body).unwrap_or_else(|_| { + panic!( + "{}: a problem body, got {}", + fixture.name, + String::from_utf8_lossy(&answer.body) + ) + }); + assert!( + body.as_object_mut().unwrap().remove("traceId").is_some(), + "{}: the answer carries a trace", + fixture.name + ); + let headers: BTreeMap<&str, &str> = HEADERS + .iter() + .filter_map(|name| { + answer + .headers + .get(*name) + .map(|value| (*name, value.to_str().unwrap())) + }) + .collect(); + let observed = json!({ + "status": answer.status, + "headers": headers, + "body": body, + }); + (answer, observed) +} + +fn golden_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json") +} + +#[tokio::test] +async fn every_refusal_answers_the_bytes_the_golden_file_holds() { + let world = world().await; + let mut observed = BTreeMap::new(); + for fixture in fixtures(&world) { + let (_, answer) = observe(&world.api, &fixture).await; + assert!( + matches!(answer["status"].as_u64(), Some(401 | 403 | 404)), + "{}: {answer}", + fixture.name + ); + observed.insert(fixture.name, answer); + } + let observed = serde_json::to_value(&observed).unwrap(); + if std::env::var_os("DOCUMENTS_UPDATE_GOLDEN").is_some() { + let text = serde_json::to_string_pretty(&observed).unwrap() + "\n"; + std::fs::create_dir_all(golden_path().parent().unwrap()).unwrap(); + std::fs::write(golden_path(), text).unwrap(); + return; + } + let golden: Value = serde_json::from_slice( + &std::fs::read(golden_path()).expect("tests/golden/refusals.json exists"), + ) + .unwrap(); + assert_eq!( + observed, + golden, + "a refusal answers differently than the golden file holds:\n{}", + serde_json::to_string_pretty(&observed).unwrap() + ); +} + +/// The count `documents_request_refusals_total` holds for `check`. +async fn counted(prepared: &Prepared, check: FailedCheck) -> u64 { + let response = prepared + .metrics_app() + .expect("a metrics listener is configured") + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = String::from_utf8( + axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(), + ) + .unwrap(); + let prefix = format!( + "documents_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + text.lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("no series for {}\n{text}", check.as_str())) + .parse() + .unwrap() +} + +#[tokio::test] +async fn every_refusal_is_counted_and_logged_under_the_check_it_failed() { + let world = world().await; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let mut logged: BTreeMap<&str, usize> = BTreeMap::new(); + let mut seen: BTreeMap<&str, u64> = BTreeMap::new(); + for fixture in fixtures(&world) { + let before = counted(&world.prepared, fixture.check).await; + let lines_before = logs.text().lines().count(); + let (_, _) = observe(&world.api, &fixture) + .with_subscriber(logs.subscriber()) + .await; + let after = counted(&world.prepared, fixture.check).await; + assert_eq!(after, before + 1, "{}: counted once", fixture.name); + let occurrences = seen.entry(fixture.check.as_str()).or_default(); + *occurrences += 1; + let text = logs.text(); + let written: Vec<&str> = text + .lines() + .skip(lines_before) + .filter(|line| line.contains("request refused")) + .collect(); + // The limiter admits the first lines of each check in a window. + if *occurrences <= 5 { + assert_eq!(written.len(), 1, "{}: one line\n{text}", fixture.name); + let line: Value = serde_json::from_str(written[0]).unwrap(); + let fields = &line["fields"]; + assert_eq!(fields["decision"], "refused", "{}", fixture.name); + assert_eq!( + fields["failed_check"], + fixture.check.as_str(), + "{}", + fixture.name + ); + *logged.entry(fixture.check.as_str()).or_default() += 1; + } + } + let text = logs.text(); + // Nothing a caller sent reaches the log. + for canary in [ + "unlisted-client", + "a principal", + "other.example.test", + "urn:example:elsewhere", + "partner.example.test", + TEST_ISSUER, + TEST_AUDIENCE, + "citizen-portal", + "reader-1", + "someone-else", + "not-a-token", + "partner-service", + CITIZEN.subject, + &world.document, + &world.version, + &world.missing, + ] { + assert!(!text.contains(canary), "{canary} reached the log\n{text}"); + } + assert!(!logged.is_empty()); +} + +/// The sum of every series of `documents_request_refusals_total`. +async fn counted_in_total(prepared: &Prepared) -> u64 { + let mut total = 0; + for check in FailedCheck::ALL { + total += counted(prepared, check).await; + } + total +} + +#[tokio::test] +async fn a_request_that_is_not_refused_is_not_counted() { + let world = world().await; + let before = counted_in_total(&world.prepared).await; + let read = world.api.read(CITIZEN, &world.document).await; + assert_eq!(read.status, 200); + let listed = world.api.get(CITIZEN, "/v1/documents").await; + assert_eq!(listed.status, 200); + let missing_route = world.api.get(CITIZEN, "/v1/nothing-here").await; + assert_eq!(missing_route.status, 404); + let unsupported = world + .api + .call( + request(CITIZEN, Method::POST, "/v1/documents") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert!(unsupported.status >= 400); + assert_eq!(counted_in_total(&world.prepared).await, before); + drop(world.deployment); +} + +/// A custodian whose profile has no grant authority is refused under +/// `operation`, not `ownership`, with the answer the reserving system gets. +/// Under `citizen-delivery` with represented-principal grants refused, the +/// citizen holds the document and may not issue a grant on it. +#[tokio::test] +async fn a_custodian_without_grant_authority_is_counted_under_operation() { + let project = support::STARTER_PROJECT.replacen( + "representedPrincipalGrants: permitted", + "representedPrincipalGrants: refused", + 1, + ); + assert_ne!( + project, + support::STARTER_PROJECT, + "the starter changed shape" + ); + let world = world_with_project(&project).await; + let fixture = Fixture::as_principal( + "grant-issued-by-a-custodian-without-grant-authority", + FailedCheck::Operation, + Method::POST, + &format!("/v1/documents/{}/grants", world.document), + CITIZEN, + ) + .with_body( + json!({"versionId": world.version, "grantee": {"subject": "reader-1", "kind": "human"}}), + ); + let operation_before = counted(&world.prepared, FailedCheck::Operation).await; + let ownership_before = counted(&world.prepared, FailedCheck::Ownership).await; + let (_, answer) = observe(&world.api, &fixture).await; + assert_eq!( + counted(&world.prepared, FailedCheck::Operation).await, + operation_before + 1 + ); + assert_eq!( + counted(&world.prepared, FailedCheck::Ownership).await, + ownership_before + ); + let golden: Value = serde_json::from_slice(&std::fs::read(golden_path()).unwrap()).unwrap(); + assert_eq!(answer, golden["grant-issued-by-the-reserving-system"]); + drop(world.deployment); +} + +/// A scope refusal's line names what the deployment declared, the scope +/// claim, the scope the profile requires and the profile, and nothing the +/// token carried in its own scope. +#[tokio::test] +async fn a_scope_refusal_line_names_the_declared_values_and_none_of_the_tokens() { + let world = world().await; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let canary = "canary-scope-from-the-token"; + let fixture = Fixture::get( + "listing-with-another-scope", + FailedCheck::Scope, + "/v1/documents", + Credential::Token(token_with(CITIZEN, claims("scope", json!(canary)))), + ); + let (answer, _) = observe(&world.api, &fixture) + .with_subscriber(logs.subscriber()) + .await; + assert_eq!(answer.status, 403); + let text = logs.text(); + assert!( + !text.contains(canary), + "the token's scope reached the log\n{text}" + ); + let line: Value = text + .lines() + .filter(|line| line.contains("request refused")) + .map(|line| serde_json::from_str(line).unwrap()) + .next() + .unwrap_or_else(|| panic!("no refusal line\n{text}")); + let fields = &line["fields"]; + assert_eq!(fields["failed_check"], "scope"); + assert_eq!(fields["scope_claim"], "scope"); + assert_eq!(fields["required_scope"], "documents:own"); + assert_eq!(fields["access_profile"], "citizen"); + assert!(fields["remedy"].as_str().unwrap().contains("scopeClaim")); + drop(world.deployment); +} diff --git a/crates/registry-documents/tests/refusal_key_source.rs b/crates/registry-documents/tests/refusal_key_source.rs new file mode 100644 index 0000000000..327a057b74 --- /dev/null +++ b/crates/registry-documents/tests/refusal_key_source.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A key source that does not answer. The caller is answered +//! `service.unavailable` with `Retry-After`, never a 401, and the operator's +//! counter records `key-source-unavailable`. The database is named by +//! `DOCUMENTS_TEST_DATABASE_URL`. + +mod support; + +use axum::body::Body; +use axum::http::Request; +use registry_documents::runtime::{prepare_with_verifier, Prepared}; +use registry_platform_authcommon::FailedCheck; +use support::{ + Api, Deployment, FakeVerifier, APPROVE, CITIZEN, DATABASE_STORAGE, DISABLED_VERIFIER, +}; +use tower::ServiceExt as _; + +/// The count `documents_request_refusals_total` holds for `check`. +async fn counted(prepared: &Prepared, check: FailedCheck) -> u64 { + let response = prepared + .metrics_app() + .expect("a metrics listener is configured") + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = String::from_utf8( + axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(), + ) + .unwrap(); + let prefix = format!( + "documents_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + text.lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("no series for {}\n{text}", check.as_str())) + .parse() + .unwrap() +} + +#[tokio::test] +async fn an_unreachable_key_source_answers_unavailable_and_counts_the_check() { + let mut deployment = Deployment::new(DATABASE_STORAGE, DISABLED_VERIFIER).await; + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + deployment.configure(&format!("metricsListener:\n bind: 127.0.0.1:{port}\n")); + // Nothing listens on the discard port, so every key fetch fails. + deployment.fetch_keys_from("http://127.0.0.1:9/jwks"); + deployment.migrate().await; + let prepared = prepare_with_verifier( + &deployment.runtime, + FakeVerifier::new("refusal-key-source", APPROVE), + ) + .await + .expect("the runtime prepares without reaching the key source"); + let api = Api::new(&prepared); + let before = counted(&prepared, FailedCheck::KeySourceUnavailable).await; + let answer = api.get(CITIZEN, "/v1/documents").await; + assert_eq!( + answer.status, + 503, + "{}", + String::from_utf8_lossy(&answer.body) + ); + assert_eq!(answer.headers["retry-after"], "5"); + assert_eq!(answer.headers["content-type"], "application/problem+json"); + assert_eq!(answer.json()["code"], "service.unavailable"); + assert!(answer.headers.get("www-authenticate").is_none()); + assert_eq!( + counted(&prepared, FailedCheck::KeySourceUnavailable).await, + before + 1 + ); + drop(deployment); +} diff --git a/crates/registry-documents/tests/support/mod.rs b/crates/registry-documents/tests/support/mod.rs index b06e474577..3f7a88e12a 100644 --- a/crates/registry-documents/tests/support/mod.rs +++ b/crates/registry-documents/tests/support/mod.rs @@ -42,7 +42,9 @@ pub fn database_url() -> String { /// An independent in-memory audit sink for direct worker boundary tests. pub fn worker_audit() -> registry_documents::audit::DocumentsAudit { registry_documents::audit::DocumentsAudit::new( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(Vec::::new())), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + Vec::::new(), + )), registry_platform_audit::AuditProfile::production_from_secret_bytes( zeroize::Zeroizing::new(b"documents-canary-audit-key-not-a-secret".to_vec()), ) @@ -66,6 +68,8 @@ pub struct Deployment { erasure: &'static str, extra: String, hooks_url: String, + allowed_clients: String, + jwks_source: String, } impl Deployment { @@ -122,6 +126,10 @@ impl Deployment { erasure: "active", extra: String::new(), hooks_url: UNREACHABLE_HOOKS_URL.to_owned(), + allowed_clients: + "[civil-registry-app, citizen-portal, case-portal, partner-portal, partner-service]" + .to_owned(), + jwks_source: "type: static\n documentRef: secret:file/jwks.json".to_owned(), }; deployment.secret("runtime-database-url", runtime_url.unwrap_or(&scoped_url)); deployment.secret("migration-database-url", &scoped_url); @@ -180,6 +188,20 @@ impl Deployment { self.write_runtime(); } + /// Write `allowedClients: from-package`, so the runtime admits exactly the + /// requester clients the package names and the file lists none. + pub fn admit_package_clients(&mut self) { + self.allowed_clients = "from-package".to_owned(); + self.write_runtime(); + } + + /// Name the issuer's key set by `uri` in place of the static key set, so a + /// refusal to verify can be driven by a key source that does not answer. + pub fn fetch_keys_from(&mut self, uri: &str) { + self.jwks_source = format!("type: uri\n uri: {uri}"); + self.write_runtime(); + } + /// Append `block`, top-level runtime keys, to the runtime document. pub fn configure(&mut self, block: &str) { self.extra = block.to_owned(); @@ -211,10 +233,9 @@ authentication: issuer: https://identity.example.test/realms/registry audience: urn:example:documents scopeClaim: scope - allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal, partner-service] + allowedClients: {allowed_clients} jwksSource: - type: static - documentRef: secret:file/jwks.json + {jwks_source} audit: destination: file path: {audit} @@ -237,6 +258,8 @@ destinations: erasure = self.erasure, extra = self.extra, hooks_url = self.hooks_url, + allowed_clients = self.allowed_clients, + jwks_source = self.jwks_source, ); std::fs::write(&self.runtime, document).unwrap(); } diff --git a/crates/registry-documents/tests/token_characterisation.rs b/crates/registry-documents/tests/token_characterisation.rs new file mode 100644 index 0000000000..baaec3727c --- /dev/null +++ b/crates/registry-documents/tests/token_characterisation.rs @@ -0,0 +1,298 @@ +#![allow( + clippy::disallowed_methods, + reason = "tests read back the YAML the code under test wrote, or a published contract or fixture, to assert on it; they read no operator configuration" +)] +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of the Document Store's bearer authentication against the +//! token fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `documents` cell is run through the +//! authenticator the server builds: the verifier profile comes from a +//! `RuntimeConfig` loaded from a runtime file, the keys from that file's static +//! key source, the access profiles from a project package, and the credential +//! goes through `DocumentsAuthenticator::authenticate`. No database is involved. +//! +//! The project package is the published starter with its `staff` access profile +//! rewritten for the row: the fixture's client, the first scope the fixture +//! carries, and the actor kind the fixture declares (`human` when it declares +//! none, or when the row selects the human-only profile). +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::collections::BTreeMap; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; + +use registry_documents::auth::{AuthenticationError, DocumentsAuthenticator}; +use registry_documents::config::RuntimeConfig; +use registry_documents::package::{package_limits, PACKAGE_COMMAND, PROJECT_FILE}; +use registry_documents_core::{AccessProfiles, DocumentsProject}; +use registry_platform_config::write_package; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:documents"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; +/// The clients the starter's other access profiles name. The allowed list +/// keeps them so every profile of the package resolves a client. +const STARTER_CLIENTS: [&str; 4] = [ + "civil-registry-app", + "citizen-portal", + "partner-portal", + "partner-service", +]; +const STARTER_PROJECT: &str = + include_str!("../../../products/documents/examples/starter/documents.yaml"); + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +/// The actor kind the profile admits: the one the fixture declares when it is +/// a kind the Document Store has, and `human` otherwise or when the row +/// selects the human-only profile. +fn profile_actor_kind(case: &FixtureCase) -> &'static str { + if case.against == Against::HumanOnlyProfile { + return "human"; + } + match literal_string(case, "registry_actor_kind").as_deref() { + Some("service") => "service", + _ => "human", + } +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +/// The starter project with its `staff` profile rewritten for the row. +fn project_text(client: &str, scope: &str, kind: &str) -> String { + let mut project: Value = serde_norway::from_str(STARTER_PROJECT).expect("the starter parses"); + let staff = project + .pointer_mut("/accessProfiles/staff") + .expect("the starter has a staff access profile"); + staff["requesterClients"] = json!([client]); + staff["requiredScopes"] = json!([scope]); + staff["actorKind"] = json!(kind); + serde_norway::to_string(&project).expect("the project serialises") +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("jwks.json"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + // The database is never contacted: only the key source and the verifier + // profile are built from this runtime file. + write_private( + &secrets.join("database-url"), + b"postgresql://corpus@127.0.0.1:1/corpus", + ); + write_private( + &secrets.join("audit-key"), + b"documents-corpus-audit-key-0123456789", + ); + write_private( + &secrets.join("hook-key"), + b"documents-corpus-hook-key-0123456789", + ); + + let claim = scope_claim(&case); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); + let client = fixture_client(&case); + let project = project_text(&client, &scope, profile_actor_kind(&case)); + let package = root.path().join("package"); + write_package( + &package, + &BTreeMap::from([(PROJECT_FILE.to_owned(), project.clone().into_bytes())]), + None, + &package_limits(), + PACKAGE_COMMAND, + ) + .expect("the package for the row"); + + let mut allowed = vec![client]; + allowed.extend(STARTER_CLIENTS.map(str::to_owned)); + let runtime_path = root.path().join("runtime.yaml"); + fs::write( + &runtime_path, + format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: token-characterisation +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/database-url + migrationUrlRef: secret:file/database-url +authentication: + oidc: + issuer: {issuer} + audience: {audience} + scopeClaim: {claim} + allowedClients: {allowed} + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key + attemptTimeoutMilliseconds: 1000 + maximumAttempts: 2 +", + package = package.display(), + secrets = secrets.display(), + issuer = case.issuer, + audience = case.audience, + allowed = serde_json::to_string(&allowed).expect("a client list"), + audit = root.path().join("audit.ndjson").display(), + ), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = config.secret_resolver().expect("the secret resolver"); + let keys = config + .jwks_fetcher(&resolver) + .await + .expect("the static key source"); + let decoded = DocumentsProject::decode(PROJECT_FILE, project.as_bytes()) + .expect("the rewritten project decodes") + .value; + + let admitted = config + .admitted_clients(&decoded) + .expect("the listed clients cover the project"); + let authenticator = DocumentsAuthenticator::new( + config.verifier_profile(&admitted), + keys.clone(), + AccessProfiles::new(&decoded), + config.binds_assertion_issuers(), + ); + let token = case.token.expose(); + match authenticator.authenticate(token).await { + Ok(caller) => Outcome::Admitted(Some(caller.kind.as_str().to_owned())), + Err(AuthenticationError::Claims(_)) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { + let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); + match reference.verify(token).await { + Err(failure) => Outcome::refused_by(&failure), + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => refusal("header"), + } + } + } +} + +#[tokio::test] +async fn documents_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("documents", &signer, ISSUER, AUDIENCE, observe) + .await + .expect("every documents row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no documents row ran"); + eprintln!( + "documents: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/crates/registry-documentsctl/Cargo.toml b/crates/registry-documentsctl/Cargo.toml index edec888d13..2132c99b7e 100644 --- a/crates/registry-documentsctl/Cargo.toml +++ b/crates/registry-documentsctl/Cargo.toml @@ -17,6 +17,11 @@ name = "postgres_cli" path = "tests/postgres_cli.rs" required-features = ["postgres-test"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = ["registry-documents/postgres-test"] @@ -30,13 +35,16 @@ registry-documents.workspace = true registry-documents-core.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true serde.workspace = true serde_json.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid.workspace = true +zeroize.workspace = true [dev-dependencies] +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } tokio-postgres.workspace = true diff --git a/crates/registry-documentsctl/src/lib.rs b/crates/registry-documentsctl/src/lib.rs index d105d01101..9bc2798d65 100644 --- a/crates/registry-documentsctl/src/lib.rs +++ b/crates/registry-documentsctl/src/lib.rs @@ -49,6 +49,7 @@ use serde_json::{json, Value}; use uuid::Uuid; mod operate; +mod provision; mod report; mod starter; @@ -90,6 +91,8 @@ enum Command { Package(PackageArgs), /// Report what apply would change in the database, writing nothing. Plan(ActivationArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Apply the schema and record the configured package as active. Apply(ApplyArgs), /// Report the active package and the activation history. @@ -512,6 +515,7 @@ where }; let command = command_path(&cli.command); let outcome = match &cli.command { + Command::Provision(args) => return provision(args, cli.format), Command::Init(args) => init(&args.directory), Command::Check(args) => check(args), Command::Package(args) => package(args), @@ -556,6 +560,7 @@ fn command_path(command: &Command) -> &'static str { Command::Check(_) => "check", Command::Package(_) => "package", Command::Plan(_) => "plan", + Command::Provision(_) => "provision", Command::Apply(_) => "apply", Command::Status(_) => "status", Command::Verification(VerificationCommand::List(_)) => "verification list", @@ -566,6 +571,23 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "documentsctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn init(directory: &Path) -> Outcome { match starter::write(directory) { Ok(created) => { diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs new file mode 100644 index 0000000000..ceca495cb2 --- /dev/null +++ b/crates/registry-documentsctl/src/provision.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision`: the shared command over the Document Store's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_documents::config::{startup_report, RuntimeConfig}; +use registry_documents_core::DOCUMENTS_RUNTIME_KIND; +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// The Document Store keeps its tables in `public`. `provision` gives the +/// migration role USAGE and CREATE on it and the runtime role USAGE, directly. +/// It needs no extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "documents", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(DOCUMENTS_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-documentsctl/tests/postgres_cli.rs b/crates/registry-documentsctl/tests/postgres_cli.rs index f50a7829c8..7a00a1dfd9 100644 --- a/crates/registry-documentsctl/tests/postgres_cli.rs +++ b/crates/registry-documentsctl/tests/postgres_cli.rs @@ -386,11 +386,12 @@ async fn apply_refuses_a_package_that_is_not_the_pinned_one() { } /// A database provisioned as the Document Store operate page provisions -/// one: split migration and runtime login roles, `PUBLIC` stripped of every -/// privilege on the database and on the `public` schema, and the schema -/// handed to the migration role. The runtime role holds only `CONNECT`, so -/// before the first apply it has no usage on any schema and its -/// `current_schema()` is null. Roles are cluster-wide, so each is named +/// one, as `documentsctl provision` leaves it: split migration and runtime +/// login roles, `PUBLIC` stripped of every privilege on the database and of +/// `CREATE` on the `public` schema, the migration role holding `USAGE` and +/// `CREATE` on `public`, and the runtime role holding `CONNECT` on the +/// database and `USAGE` on `public`. Before the first apply the runtime +/// role has no table privilege. Roles are cluster-wide, so each is named /// after the suite's own database, which makes a leftover from a failed run /// attributable, and [`ProvisionedDatabase::drop`] removes them with the /// database. @@ -404,6 +405,14 @@ impl ProvisionedDatabase { const PASSWORD: &'static str = "documents-test"; async fn new(admin: &tokio_postgres::Client) -> Self { + Self::with_runtime_usage(admin, true).await + } + + /// The database as an operator who provisioned by hand to a layout that + /// gives the runtime role no `USAGE` on `public` leaves it, when + /// `runtime_usage` is false: no role but the migration role can resolve + /// the `public` schema. + async fn with_runtime_usage(admin: &tokio_postgres::Client, runtime_usage: bool) -> Self { let suite = base_config() .get_dbname() .expect("DOCUMENTS_TEST_DATABASE_URL names a database") @@ -445,11 +454,20 @@ impl ProvisionedDatabase { .batch_execute(&format!( "REVOKE ALL ON DATABASE {name} FROM PUBLIC; GRANT CONNECT ON DATABASE {name} TO {migration_role}, {runtime_role}; - ALTER SCHEMA public OWNER TO {migration_role}; - REVOKE ALL ON SCHEMA public FROM PUBLIC;" + REVOKE CREATE ON SCHEMA public FROM PUBLIC; + GRANT USAGE, CREATE ON SCHEMA public TO {migration_role}; + GRANT USAGE ON SCHEMA public TO {runtime_role};" )) .await .unwrap(); + if !runtime_usage { + database + .batch_execute(&format!( + "REVOKE USAGE ON SCHEMA public FROM PUBLIC, {runtime_role}" + )) + .await + .unwrap(); + } drop(database); connection.await.unwrap().unwrap(); provisioned @@ -506,8 +524,8 @@ fn base_config() -> tokio_postgres::Config { } /// The operate page's journey on a database provisioned as it says: `plan` -/// over the runtime credential, which holds nothing but `CONNECT` before -/// the first apply, reports the initial activation; `apply` over the +/// over the runtime credential, which holds no table privilege before the +/// first apply, reports the initial activation; `apply` over the /// migration credential splits the roles; and `plan` then reports nothing /// to change. #[tokio::test] @@ -537,7 +555,7 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op assert_eq!(plan["change"], "activate"); assert_eq!(plan["planKind"], "initial"); assert_eq!(plan["activeDigest"], Value::Null); - assert_eq!(plan["pendingSchemaVersions"], serde_json::json!([100])); + assert_eq!(plan["pendingSchemaVersions"], serde_json::json!([100, 101])); assert_eq!(plan["runtimeRoleMode"], Value::Null); assert_eq!(plan["refusals"], serde_json::json!([])); let output = Command::new(env!("CARGO_BIN_EXE_documentsctl")) @@ -566,7 +584,9 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op // After apply, a runtime role that lost its schema usage resolves no // schema again. That is a misconfiguration, refused by name rather - // than read as a database nobody applied a package to. + // than read as a database nobody applied a package to. `provision` + // leaves `PUBLIC` its default `USAGE` on `public`, so the revoke names + // `PUBLIC` as well, as an operator who hardened the schema would. let (database, connection) = tokio_postgres::connect(&provisioned.admin_url(), tokio_postgres::NoTls) .await @@ -574,7 +594,7 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op let connection = tokio::spawn(connection); database .batch_execute(&format!( - "REVOKE USAGE ON SCHEMA public FROM {}", + "REVOKE USAGE ON SCHEMA public FROM PUBLIC, {}", provisioned.runtime_role )) .await @@ -590,3 +610,39 @@ async fn plan_reports_the_initial_activation_on_a_database_provisioned_as_the_op provisioned.drop(&deployment.admin).await; } + +/// A database provisioned by hand so that the runtime role has `USAGE` on no +/// schema resolves no schema before the first apply. `plan` over that +/// credential still reports the initial activation: the refusal by name is +/// for a database a package was already applied to. +#[tokio::test] +async fn plan_reports_the_initial_activation_when_the_runtime_role_resolves_no_schema() { + let deployment = Deployment::new().await; + let digest = deployment.deploy(); + let runtime = deployment.runtime(); + let provisioned = ProvisionedDatabase::with_runtime_usage(&deployment.admin, false).await; + deployment.secret( + "runtime-database-url", + &provisioned.url( + &provisioned.runtime_role, + Some(ProvisionedDatabase::PASSWORD), + ), + ); + deployment.secret( + "migration-database-url", + &provisioned.url( + &provisioned.migration_role, + Some(ProvisionedDatabase::PASSWORD), + ), + ); + + let (code, plan) = ctl(&["plan", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{plan:#}"); + assert_eq!(plan["packageDigest"], digest); + assert_eq!(plan["change"], "activate"); + assert_eq!(plan["planKind"], "initial"); + assert_eq!(plan["activeDigest"], Value::Null); + assert_eq!(plan["refusals"], serde_json::json!([])); + + provisioned.drop(&deployment.admin).await; +} diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs new file mode 100644 index 0000000000..0d8a7dd217 --- /dev/null +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file whose secret files name a migration and a runtime login on +/// one server that does not exist, so a connection attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://documents_migration:{MIGRATION_PASSWORD}@db.invalid:5432/documents" + ), + ), + ( + "runtime-database-url", + format!("postgresql://documents_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/documents"), + ), + ( + "documents-audit-key", + "documentsctl-test-audit-key-not-a-secret".to_owned(), + ), + ( + "hook-key", + "documentsctl-test-hook-key-not-a-secret-0123456789".to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: registry-documents-ctl-test +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +authentication: + oidc: + issuer: https://identity.example.test/realms/registry + audience: urn:example:documents + scopeClaim: scope + allowedClients: [civil-registry-app] +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/documents-audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key +", + package = directory.join("package").display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_documentsctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["documents_migration", "documents_runtime"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE DATABASE \"documents\""), "{stdout}"); + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "documents"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "documents"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The command's own flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for arguments in [ + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ], + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ], + vec!["provision", "--runtime-config", &runtime], + ] { + let output = ctl(&arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty(), "{arguments:?}"); + } + // A missing administrator flag is a usage error of the provision verb, + // not clap's answer to an unknown verb. + let stderr = + String::from_utf8(ctl(&["provision", "--runtime-config", &runtime]).stderr).unwrap(); + assert!(stderr.contains("--admin-url"), "{stderr}"); + assert!(!stderr.contains("unrecognized subcommand"), "{stderr}"); + let stderr = String::from_utf8( + ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "DOCUMENTS_ADMIN_URL", + ]) + .stderr, + ) + .unwrap(); + assert!( + stderr.contains("conflicting use of --admin-url-file"), + "{stderr}" + ); +} + +/// The first diagnostic of a refused `provision --print-sql` over `runtime`, +/// after checking the exit status and that no password reached either stream. +fn loader_refusal(runtime: &str) -> serde_json::Value { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(1), "{stdout}{stderr}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret) && !stderr.contains(secret), + "a refusal holds no password" + ); + } + let report: serde_json::Value = + serde_json::from_str(&stdout).unwrap_or_else(|error| panic!("{error}: {stdout}{stderr}")); + report["diagnostics"][0].clone() +} + +#[test] +fn a_missing_database_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["path"], "/database/runtimeUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn a_database_secret_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/migration-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["path"], "/database/migrationUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime) + .unwrap() + .replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca\n", + ); + std::fs::write(&runtime, text).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!(diagnostic["path"], "/database/caBundleRef", "{diagnostic}"); +} + +#[test] +fn a_runtime_file_the_runtime_refuses_is_refused_with_its_diagnostic() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap().replace( + "allowedClients: [civil-registry-app]", + "allowedClients: unrestricted", + ); + std::fs::write(&runtime, text).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!( + diagnostic["code"], "documents.runtime.allowed-clients-required", + "{diagnostic}" + ); +} diff --git a/crates/registry-documentsctl/tests/provision_postgres.rs b/crates/registry-documentsctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..87da3f1be9 --- /dev/null +++ b/crates/registry-documentsctl/tests/provision_postgres.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `documentsctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "documents-audit-key", + "documentsctl-test-audit-key-not-a-secret", + ), + ( + "hook-key", + "documentsctl-test-hook-key-not-a-secret-0123456789", + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + Self { directory, admin } + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write the runtime document over `package`, pinned to `digest`. + fn write_runtime(&self, package: &Path, digest: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/documents/runtime/v1alpha1 +kind: DocumentsRuntimeConfig +identity: + databaseId: registry-documents-ctl-test +package: + root: {package} + expectedDigest: {digest} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback + networkExposure: private-address +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + testOnlyPlaintext: true +authentication: + oidc: + issuer: https://identity.example.test/realms/registry + audience: urn:example:documents + scopeClaim: scope + allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal] +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/documents-audit-key +storage: + type: database +contentVerification: + type: disabled +cleanup: + erasure: active +destinations: + hooks: + owning-system-events: + url: http://127.0.0.1:9/document-events + hmacSha256KeyRef: secret:file/hook-key +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } + + /// `init`, then `package`, then a runtime document pinned to the + /// package digest the report names. + fn deploy(&self) -> String { + let project = self.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project]); + assert_eq!(code, 0, "{report:#}"); + let package = self.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + let digest = report["packageDigest"].as_str().unwrap().to_owned(); + self.write_runtime(&package, &digest); + digest + } + + /// Replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_documentsctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// The public half of a P-256 key, as a key set the runtime trusts. +const PUBLIC_KEY_SET: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","alg":"ES256","use":"sig","kid":"documentsctl-test-1","x":"gEHpg5PeV9TxLeisE9SSOQLb8FibjLxUHbQANAxmS4A","y":"wPnAyYS42uEWe2vyT4ys7yOAPoQwYU5FkogAZYroLbk"}]}"#; + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its health route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + deployment.deploy(); + let runtime = deployment.runtime(); + let (base_url, ca) = provision_test_env(); + let ca_path = deployment.path("secrets").join("postgres-ca.pem"); + std::fs::write(&ca_path, &ca).unwrap(); + std::fs::set_permissions(&ca_path, std::fs::Permissions::from_mode(0o600)).unwrap(); + let document = std::fs::read_to_string(&runtime).unwrap(); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + const ALLOWED_CLIENTS: &str = + " allowedClients: [civil-registry-app, citizen-portal, case-portal, partner-portal]\n"; + assert!(document.contains(" testOnlyPlaintext: true\n")); + assert!(document.contains(ALLOWED_CLIENTS)); + std::fs::write( + &runtime, + document + .replace( + " testOnlyPlaintext: true\n", + " caBundleRef: secret:file/postgres-ca.pem\n", + ) + .replace( + ALLOWED_CLIENTS, + &format!( + "{ALLOWED_CLIENTS} jwksSource:\n type: static\n documentRef: secret:file/jwks.json\n" + ), + ), + ) + .unwrap(); + deployment.secret("jwks.json", PUBLIC_KEY_SET); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("documents_owner_{suffix}"), + format!("documents_mig_{suffix}"), + format!("documents_rt_{suffix}"), + format!("documents_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + assert_eq!(applied["activation"]["roleMode"], "split"); + + let prepared = registry_documents::runtime::prepare(&runtime) + .await + .expect("the runtime prepares over the runtime role"); + let address = prepared.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(prepared.serve_until(async { + stopped.await.ok(); + })); + let response = tokio::task::spawn_blocking(move || { + use std::io::{Read as _, Write as _}; + let mut stream = std::net::TcpStream::connect(address).unwrap(); + stream + .write_all(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + response + }) + .await + .unwrap(); + assert!( + response.starts_with("HTTP/1.1 200"), + "the health route answers: {response}" + ); + stop.send(()).unwrap(); + server.await.unwrap().expect("the server stops cleanly"); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-evidence-client-node/src/convert.rs b/crates/registry-evidence-client-node/src/convert.rs index fa1d412fd3..8bbc417818 100644 --- a/crates/registry-evidence-client-node/src/convert.rs +++ b/crates/registry-evidence-client-node/src/convert.rs @@ -18,7 +18,7 @@ use registry_evidence_client::{ SelectorValue, StaticToken, SubjectBindingReceipt, SubjectExpectations, SubjectRequest, TokenError, TokenProvider, }; -use registry_platform_crypto::PrivateJwk; +use registry_platform_crypto::{PrivateJwk, PRIVATE_JWK_MEMBERS}; use registry_platform_httputil::{exchange_authorization_from_json, ExchangeAuthorization}; use serde_json::{Map, Value}; use url::Url; @@ -595,15 +595,15 @@ fn response_format_from_json(value: &Value) -> Result Result Result { let status = response.status().as_u16(); - if validate_response_headers(response.headers()).is_err() { + if validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(EvidenceClientError::Protocol { status, code: None, @@ -1673,7 +1673,7 @@ fn metadata_cache_seconds( fn metadata_fetch_policy(trust: &TrustProfile) -> FetchUrlPolicy { match trust { - TrustProfile::LocalLoopbackDiscovery => FetchUrlPolicy::dev(), + TrustProfile::LocalLoopbackDiscovery => FetchUrlPolicy::https_or_loopback(), TrustProfile::HttpsDiscovery | TrustProfile::PinnedJwks { .. } => FetchUrlPolicy::strict(), } } @@ -1695,6 +1695,8 @@ fn authorization_server_metadata_is_compatible( } fn validate_metadata_url(url: &Url, trust: &TrustProfile) -> Result<(), EvidenceClientError> { + // Exactly `127.0.0.1`, the address a supervised development service binds, + // so metadata the service publishes cannot name another local listener. let exact_local_loopback = url.scheme() == "http" && url.host_str() == Some("127.0.0.1") && url.port().is_some_and(|port| port != 0); @@ -4260,7 +4262,7 @@ mod tests { validate_metadata_url(&url, &TrustProfile::LocalLoopbackDiscovery).is_ok(), "{target} was rejected" ); - assert!(FetchUrlPolicy::dev() + assert!(FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .is_ok()); } @@ -4440,7 +4442,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("first metadata response"); @@ -4450,7 +4452,7 @@ mod tests { JSON_MEDIA_TYPE, Some((&first.value, first.etag.as_ref(), first.cache_seconds)), 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("conditional metadata response"); @@ -4478,7 +4480,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await; let Err(error) = result else { @@ -4530,7 +4532,7 @@ mod tests { JSON_MEDIA_TYPE, None, 600, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .is_err()); diff --git a/crates/registry-evidence-client/src/profile.rs b/crates/registry-evidence-client/src/profile.rs index 7052506477..fd94fefbad 100644 --- a/crates/registry-evidence-client/src/profile.rs +++ b/crates/registry-evidence-client/src/profile.rs @@ -152,6 +152,8 @@ impl EvidenceClientProfile { return Err(profile_error()); } let origin_only = self.base_url == base_url.origin().ascii_serialization(); + // Exactly `127.0.0.1`, the address a supervised development service + // binds, so a profile names the origin it will reach. let local_loopback = base_url.scheme() == "http" && base_url.host_str() == Some("127.0.0.1") && base_url.port().is_some_and(|port| port != 0); diff --git a/crates/registry-evidence-client/src/profile_file.rs b/crates/registry-evidence-client/src/profile_file.rs index d3f797b14a..0af699ade9 100644 --- a/crates/registry-evidence-client/src/profile_file.rs +++ b/crates/registry-evidence-client/src/profile_file.rs @@ -295,6 +295,8 @@ impl ProfileDocument { } match self.trust { Some(TrustMember::LocalLoopbackDiscovery {}) => { + // Exactly `127.0.0.1`, the address a supervised development + // service binds, so a profile names the origin it will reach. let loopback = parsed.scheme() == "http" && parsed.host_str() == Some("127.0.0.1") && parsed.port().is_some_and(|port| port != 0); diff --git a/crates/registry-evidence-oid4vci/Cargo.toml b/crates/registry-evidence-oid4vci/Cargo.toml index 79687e89cf..2b61abf0f1 100644 --- a/crates/registry-evidence-oid4vci/Cargo.toml +++ b/crates/registry-evidence-oid4vci/Cargo.toml @@ -49,6 +49,7 @@ jsonwebtoken.workspace = true registry-evidence-client.workspace = true registry-evidence-verifier.workspace = true registry-platform-audit.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, features = ["xchacha-seal"] } @@ -76,6 +77,7 @@ axum-test.workspace = true ed25519-dalek.workspace = true jsonschema.workspace = true p256.workspace = true +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } registry-thunderid-tooling = { workspace = true, features = ["session"] } reqwest.workspace = true tempfile.workspace = true diff --git a/crates/registry-evidence-oid4vci/src/audit.rs b/crates/registry-evidence-oid4vci/src/audit.rs index 77dbe66cc2..277c6d0267 100644 --- a/crates/registry-evidence-oid4vci/src/audit.rs +++ b/crates/registry-evidence-oid4vci/src/audit.rs @@ -69,7 +69,7 @@ impl DeliveryAudit { master_secret: Zeroizing>, ) -> Result { let profile = AuditProfile::production_from_secret_bytes(master_secret)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher: profile.key_hasher(), diff --git a/crates/registry-evidence-oid4vci/src/authorizer.rs b/crates/registry-evidence-oid4vci/src/authorizer.rs index ebe4be5532..afbd0e64a1 100644 --- a/crates/registry-evidence-oid4vci/src/authorizer.rs +++ b/crates/registry-evidence-oid4vci/src/authorizer.rs @@ -18,6 +18,7 @@ use std::{collections::HashSet, sync::Arc, time::Duration}; use async_trait::async_trait; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ grant_claims, ClaimNames, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcError, @@ -28,6 +29,9 @@ use crate::config::{OfferAuthorizationConfig, ValidationMode}; /// The access-token types this service accepts, which are the two spellings /// RFC 9068 permits for a JWT access token. +/// The claim the platform verifier reads scopes from unless configured. +const DEFAULT_SCOPE_CLAIM: &str = "scope"; + const ACCESS_TOKEN_TYPES: [&str; 2] = ["at+jwt", "application/at+jwt"]; /// What a verified offer token established. @@ -52,16 +56,36 @@ pub struct AuthorizedOffer { pub enum AuthorizationError { #[error("the request carried no bearer credential")] Missing, + /// The credential was refused, under the check that refused it. #[error("the presented credential was refused")] - Refused, + Refused(FailedCheck), #[error("the offer key set is unavailable")] KeySource, } +impl AuthorizationError { + /// The check the request failed. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Missing => FailedCheck::CredentialMissing, + Self::Refused(check) => *check, + Self::KeySource => FailedCheck::KeySourceUnavailable, + } + } +} + /// The seam the offer endpoint authorizes through. #[async_trait] pub trait OfferAuthorizer: Send + Sync { async fn authorize(&self, credential: &str) -> Result; + + /// What a scope refusal may say about the deployment, when the authorizer + /// has a scope gate. Both values are configured, never read from a token. + fn declared_scope(&self) -> Option { + None + } } /// The configured issuer's access-token verifier. @@ -73,6 +97,8 @@ pub struct MintResourceServer { /// token's scope set after verification, with the same closed refusal a /// refused client gets, before any offer is stored or Evidence contacted. required_scopes: Vec, + /// The claim the verifier reads scopes from. + scope_claim: String, } impl MintResourceServer { @@ -92,9 +118,12 @@ impl MintResourceServer { fetch_url_policy(config, mode), )); let required_scopes = config.required_scopes.items().to_vec(); + let profile = verifier_profile(config); + let scope_claim = profile.scope_claim.clone(); Self { - verifier: Arc::new(TokenVerifier::new(verifier_profile(config), fetcher)), + verifier: Arc::new(TokenVerifier::new(profile, fetcher)), required_scopes, + scope_claim, claims: config.claims.clone(), } } @@ -107,6 +136,7 @@ impl MintResourceServer { Self { verifier, required_scopes: Vec::new(), + scope_claim: DEFAULT_SCOPE_CLAIM.to_owned(), claims: ClaimNames::default(), } } @@ -177,6 +207,13 @@ fn fetch_url_policy(config: &OfferAuthorizationConfig, mode: ValidationMode) -> #[async_trait] impl OfferAuthorizer for MintResourceServer { + fn declared_scope(&self) -> Option { + (!self.required_scopes.is_empty()).then(|| { + DeclaredScope::new(&self.scope_claim) + .with_required_scope(self.required_scopes.join(" ")) + }) + } + async fn authorize(&self, credential: &str) -> Result { if credential.is_empty() { return Err(AuthorizationError::Missing); @@ -185,7 +222,7 @@ impl OfferAuthorizer for MintResourceServer { Ok(verified) => { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map_err(|_| AuthorizationError::Refused)? + .map_err(|_| AuthorizationError::Refused(FailedCheck::TokenTime))? .as_secs(); if !matches!(grant_claims(&verified.claims, &self.claims, now), Ok(None)) || !matches!( @@ -197,7 +234,7 @@ impl OfferAuthorizer for MintResourceServer { // later redemption cannot recheck the task authority. No // complete, partial, malformed, or expired task grant under // either configured or reserved claim names may cross it. - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)); } // The scope gate runs only on the verified token's scope set: // a correctly signed token for this audience whose client @@ -210,7 +247,7 @@ impl OfferAuthorizer for MintResourceServer { .iter() .all(|scope| present.contains(scope.as_str())) { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::Scope)); } } let client = match verified.matched_client_id() { @@ -232,7 +269,7 @@ impl OfferAuthorizer for MintResourceServer { target: "registry_evidence_oid4vci::authorizer", "the token verifier returned a malformed matched client" ); - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenClient)); } }; let subject = verified @@ -241,18 +278,12 @@ impl OfferAuthorizer for MintResourceServer { .clone() .filter(|subject| !subject.is_empty()); if client.is_none() && subject.is_none() { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenClient)); } Ok(AuthorizedOffer { client, subject }) } - Err(error) if is_key_source_failure(&error) => { - tracing::warn!( - target: "registry_evidence_oid4vci::authorizer", - "the offer key set is unavailable" - ); - Err(AuthorizationError::KeySource) - } - Err(_) => Err(AuthorizationError::Refused), + Err(error) if is_key_source_failure(&error) => Err(AuthorizationError::KeySource), + Err(error) => Err(AuthorizationError::Refused(error.failed_check())), } } } @@ -306,6 +337,22 @@ mod tests { assert_eq!(server.authorize("").await, Err(AuthorizationError::Missing)); } + #[test] + fn the_declared_scope_is_the_configured_claim_and_scopes() { + let mut config = valid_config(); + config.offers.required_scopes = + crate::config::Restriction::Listed(vec!["offers:create".to_owned()]); + let server = MintResourceServer::from_config(&config.offers, config.validation_mode); + let declared = server.declared_scope().expect("a scope gate is declared"); + assert_eq!(declared.scope_claim(), "scope"); + assert_eq!(declared.required_scope(), Some("offers:create")); + assert_eq!(declared.access_profile(), None); + + config.offers.required_scopes = crate::config::Restriction::Unrestricted; + let server = MintResourceServer::from_config(&config.offers, config.validation_mode); + assert_eq!(server.declared_scope(), None); + } + #[test] fn the_resource_server_is_built_from_the_offer_document_alone() { // The construction takes the offer boundary and the validation mode. diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 2ec3f988a9..5860b1a52a 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -81,7 +81,7 @@ const REMOVED_KEYS: &[RemovedKey] = &[ /// The shared runtime reader for a delivery runtime file. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: OID4VCI_RUNTIME_API_VERSION, kind: OID4VCI_RUNTIME_KIND, }) @@ -1643,7 +1643,8 @@ fn credential_issuer_findings(issuer: &str, findings: &mut Vec) { } } -/// Accept a plain loopback HTTP endpoint, with an optional path and nothing +/// Accept a plain HTTP endpoint on exactly `127.0.0.1`, the address a +/// supervised development service binds, with an optional path and nothing /// else that could vary between what is configured and what is reached. fn is_supervised_local_endpoint(origin: &Url) -> bool { let url = origin.to_url(); diff --git a/crates/registry-evidence-oid4vci/src/observability.rs b/crates/registry-evidence-oid4vci/src/observability.rs index 409d15c372..76cfa74032 100644 --- a/crates/registry-evidence-oid4vci/src/observability.rs +++ b/crates/registry-evidence-oid4vci/src/observability.rs @@ -23,6 +23,7 @@ use axum::{ Router, }; +use registry_platform_authcommon::{DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_MEDIA_TYPE, }; @@ -139,6 +140,9 @@ pub(crate) struct Metrics { store_entries: AtomicUsize, store_capacity: usize, cleanup_expired: AtomicU64, + refusals: RefusalRecorder, + /// The configured values a scope refusal's log line names. + declared_scope: Option, } impl Metrics { @@ -149,9 +153,33 @@ impl Metrics { store_entries: AtomicUsize::new(0), store_capacity, cleanup_expired: AtomicU64::new(0), + refusals: RefusalRecorder::new("evidence_oid4vci").expect(DECLARATION), + declared_scope: None, } } + /// Name the configured values a scope refusal's log line carries. + pub(crate) fn with_declared_scope(mut self, declared_scope: Option) -> Self { + self.declared_scope = declared_scope; + self + } + + /// Count a refused request under its check and write the admitted log + /// line. + fn record_refusal(&self, note: RefusalNote) { + registry_platform_authcommon::record_refusal!( + self.refusals, + note, + declared = self.declared_scope.as_ref() + ); + } + + /// The recorder that counts each refused request under its check. + #[cfg(test)] + pub(crate) fn refusal_recorder(&self) -> &RefusalRecorder { + &self.refusals + } + pub(crate) fn record_outcome(&self, outcome: Outcome) { let mut outcomes = self .outcomes @@ -295,6 +323,7 @@ impl Metrics { self.cleanup_expired.load(Ordering::Relaxed), ) .expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); out.finish() } } @@ -324,6 +353,9 @@ pub(crate) async fn observe( .map_or(NO_ERROR, |problem| normalized_problem(problem.0)); metrics.record_request(route, method, status, error, started.elapsed()); log_request(route, method, status, error); + if let Some(note) = response.extensions().get::() { + metrics.record_refusal(*note); + } response } diff --git a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt index e487bf305c..67cf00d65c 100644 --- a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt +++ b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt @@ -103,3 +103,50 @@ evidence_oid4vci_store_capacity 256 # HELP evidence_oid4vci_cleanup_expired_total Expired in-memory entries released by cleanup. # TYPE evidence_oid4vci_cleanup_expired_total counter evidence_oid4vci_cleanup_expired_total 3 +# HELP evidence_oid4vci_request_refusals_total Requests refused, by the check that failed. +# TYPE evidence_oid4vci_request_refusals_total counter +evidence_oid4vci_request_refusals_total{check="credential-missing"} 0 +evidence_oid4vci_request_refusals_total{check="credential-malformed"} 0 +evidence_oid4vci_request_refusals_total{check="token-algorithm"} 0 +evidence_oid4vci_request_refusals_total{check="token-type"} 0 +evidence_oid4vci_request_refusals_total{check="token-key"} 0 +evidence_oid4vci_request_refusals_total{check="token-signature"} 0 +evidence_oid4vci_request_refusals_total{check="token-issuer"} 0 +evidence_oid4vci_request_refusals_total{check="token-audience"} 0 +evidence_oid4vci_request_refusals_total{check="token-time"} 0 +evidence_oid4vci_request_refusals_total{check="token-client"} 0 +evidence_oid4vci_request_refusals_total{check="token-assertion-issuer"} 0 +evidence_oid4vci_request_refusals_total{check="token-claims"} 0 +evidence_oid4vci_request_refusals_total{check="actor-kind"} 0 +evidence_oid4vci_request_refusals_total{check="delegation"} 0 +evidence_oid4vci_request_refusals_total{check="sender-constraint"} 0 +evidence_oid4vci_request_refusals_total{check="key-source-unavailable"} 0 +evidence_oid4vci_request_refusals_total{check="shared-secret"} 0 +evidence_oid4vci_request_refusals_total{check="one-time-credential"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-signature"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-freshness"} 0 +evidence_oid4vci_request_refusals_total{check="delivery-binding"} 0 +evidence_oid4vci_request_refusals_total{check="host-origin"} 0 +evidence_oid4vci_request_refusals_total{check="scope"} 0 +evidence_oid4vci_request_refusals_total{check="access-profile"} 0 +evidence_oid4vci_request_refusals_total{check="requester-client"} 0 +evidence_oid4vci_request_refusals_total{check="purpose"} 0 +evidence_oid4vci_request_refusals_total{check="operation"} 0 +evidence_oid4vci_request_refusals_total{check="disclosure"} 0 +evidence_oid4vci_request_refusals_total{check="subject-selector"} 0 +evidence_oid4vci_request_refusals_total{check="revision-pin"} 0 +evidence_oid4vci_request_refusals_total{check="acquisition-channel"} 0 +evidence_oid4vci_request_refusals_total{check="source-authority"} 0 +evidence_oid4vci_request_refusals_total{check="separation-of-duties"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-missing"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-claims"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-expired"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-binding"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-scope"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-lifetime"} 0 +evidence_oid4vci_request_refusals_total{check="task-grant-status"} 0 +evidence_oid4vci_request_refusals_total{check="row-boundary"} 0 +evidence_oid4vci_request_refusals_total{check="ownership"} 0 +evidence_oid4vci_request_refusals_total{check="visibility"} 0 +evidence_oid4vci_request_refusals_total{check="action-guard"} 0 +evidence_oid4vci_request_refusals_total{check="rate-limit"} 0 diff --git a/crates/registry-evidence-oid4vci/src/service.rs b/crates/registry-evidence-oid4vci/src/service.rs index 6ab18f3caa..cce746989e 100644 --- a/crates/registry-evidence-oid4vci/src/service.rs +++ b/crates/registry-evidence-oid4vci/src/service.rs @@ -54,11 +54,12 @@ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use chrono::Utc; use registry_evidence_client::{HolderPublicKey, MAXIMUM_HOLDER_KEYS}; use registry_evidence_verifier::sdjwt_vc::holder_thumbprint; +use registry_platform_authcommon::{FailedCheck, RefusalNote}; use registry_platform_config::describe_secret_failure; use registry_platform_crypto::PublicJwk; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, - FrameworkRejection, + normalize_framework_rejection, request_body_limit, security_headers_without_posture, + CspBuilder, FrameworkRejection, }; use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, @@ -239,9 +240,11 @@ async fn admit(limiter: &TokenBucketLimiter, key: &str) -> Result<(), Response> /// own key or cost is a fault of this service, so it is logged without the key /// and answered as a server error that carries no Retry-After. fn limiter_refusal(error: &TokenBucketError) -> Response { - let wait = match error { - TokenBucketError::Exceeded { retry_after } => retry_after.as_secs() + 1, - TokenBucketError::Capacity => CAPACITY_RETRY_SECONDS, + let (wait, check) = match error { + TokenBucketError::Exceeded { retry_after } => { + (retry_after.as_secs() + 1, Some(FailedCheck::RateLimit)) + } + TokenBucketError::Capacity => (CAPACITY_RETRY_SECONDS, None), TokenBucketError::Configuration | TokenBucketError::CostExceedsBurst => { tracing::error!( fault = %error, @@ -262,7 +265,10 @@ fn limiter_refusal(error: &TokenBucketError) -> Response { response .headers_mut() .insert(RETRY_AFTER, HeaderValue::from(wait)); - response + match check { + Some(check) => refused(response, check), + None => response, + } } /// The limiter key of an authorized offer principal: a digest, so a client id @@ -392,7 +398,10 @@ impl DeliveryService { ) -> Self { let store = Arc::new(OfferStore::new(&config.store)); let nonces = NonceMinter::new(config.store.nonce_lifetime_seconds); - let metrics = Arc::new(Metrics::new(config.store.maximum_offers)); + let metrics = Arc::new( + Metrics::new(config.store.maximum_offers) + .with_declared_scope(authorizer.declared_scope()), + ); let limits = Limits::new(&config.rate_limits); Self { config, @@ -608,7 +617,9 @@ pub fn build_app(service: Arc) -> Router { refuse_a_stalled_request, )) .layer(from_fn(normalize_rejections)) - .layer(security_headers(CspBuilder::deny_by_default())) + .layer(security_headers_without_posture( + CspBuilder::deny_by_default(), + )) .layer(from_fn_with_state(metrics, observability::observe)) .layer(from_fn(add_no_store)) } @@ -1133,8 +1144,9 @@ async fn credential( headers: HeaderMap, body: Bytes, ) -> Response { - let Some(access_token) = bearer_credential(&headers) else { - return unauthorized("a bearer access token is required"); + let access_token = match bearer_credential(&headers) { + Ok(access_token) => access_token, + Err(check) => return unauthorized(check, "a bearer access token is required"), }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); @@ -1146,7 +1158,10 @@ async fn credential( Ok(prepared) => prepared, Err(StoreError::Unknown) => { service.metrics.record_outcome(Outcome::TokenClaimRefused); - return unauthorized("the access token cannot be used"); + return unauthorized( + FailedCheck::OneTimeCredential, + "the access token cannot be used", + ); } Err(error) => return store_response(&service, &error, Outcome::TokenClaimRefused), }; @@ -1506,31 +1521,58 @@ async fn authorize_offer( service: &DeliveryService, headers: &HeaderMap, ) -> Result { - let credential = bearer_credential(headers).unwrap_or_default(); + let credential = bearer_credential(headers) + .map_err(|check| unauthorized(check, "a bearer access token is required"))?; service .authorizer .authorize(credential) .await - .map_err(|error| match error { - AuthorizationError::Missing => unauthorized("a bearer access token is required"), - AuthorizationError::Refused => unauthorized("the presented credential was refused"), - AuthorizationError::KeySource => problem( - StatusCode::SERVICE_UNAVAILABLE, - "temporarily_unavailable", - "offers cannot be authorized at the moment", - ), + .map_err(|error| { + let check = error.failed_check(); + match error { + AuthorizationError::Missing => { + unauthorized(check, "a bearer access token is required") + } + AuthorizationError::Refused(_) => { + unauthorized(check, "the presented credential was refused") + } + AuthorizationError::KeySource => refused( + problem( + StatusCode::SERVICE_UNAVAILABLE, + "temporarily_unavailable", + "offers cannot be authorized at the moment", + ), + check, + ), + } }) } -/// The bearer credential a request presented, if it presented one. -fn bearer_credential(headers: &HeaderMap) -> Option<&str> { - let value = headers.get(AUTHORIZATION)?.to_str().ok()?; - let (scheme, credential) = value.split_once(' ')?; +/// The bearer credential a request presented, or the check its header failed: +/// no header, or one naming another scheme, is a missing credential. An +/// unreadable header, or the Bearer scheme with no token after it, is a +/// malformed credential. +fn bearer_credential(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let value = headers + .get(AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + let Some((scheme, credential)) = value.split_once(' ') else { + return Err(if value.eq_ignore_ascii_case("Bearer") { + FailedCheck::CredentialMalformed + } else { + FailedCheck::CredentialMissing + }); + }; if !scheme.eq_ignore_ascii_case("Bearer") { - return None; + return Err(FailedCheck::CredentialMissing); } let credential = credential.trim(); - (!credential.is_empty()).then_some(credential) + if credential.is_empty() { + return Err(FailedCheck::CredentialMalformed); + } + Ok(credential) } /// The system clock, which is the reading a serving process takes. @@ -1546,19 +1588,21 @@ fn now() -> i64 { fn store_response( service: &Arc, error: &StoreError, - refused: Outcome, + claim_refused: Outcome, ) -> Response { service.metrics.record_outcome(match error { StoreError::Saturated => Outcome::StoreSaturated, StoreError::Poisoned | StoreError::Unavailable => Outcome::StoreFault, - _ => refused, + _ => claim_refused, }); refresh_store_entries_in_background(service); match error { StoreError::Unknown | StoreError::AlreadyRedeemed | StoreError::TransactionCodeRefused - | StoreError::LockedOut => unredeemable_code_response(), + | StoreError::LockedOut => { + refused(unredeemable_code_response(), FailedCheck::OneTimeCredential) + } StoreError::Saturated | StoreError::Poisoned | StoreError::Unavailable => { tracing::warn!( target: "registry_evidence_oid4vci::service", @@ -1618,10 +1662,11 @@ fn warn_on_unusable_issuance(error: &IssuanceError) { fn issuance_response(service: &DeliveryService, error: &IssuanceError) -> Response { record_issuance_outcome(service, error); match error { - IssuanceError::Refused => problem( + IssuanceError::Refused => refusal( StatusCode::FORBIDDEN, "invalid_credential_request", "the credential source refused this request", + FailedCheck::SourceAuthority, ), IssuanceError::NotAvailable => problem( StatusCode::BAD_REQUEST, @@ -1648,7 +1693,12 @@ fn issuance_response(service: &DeliveryService, error: &IssuanceError) -> Respon fn credential_issuance_response(service: &DeliveryService, error: &IssuanceError) -> Response { record_issuance_outcome(service, error); warn_on_unusable_issuance(error); - terminal_credential_response() + match error { + IssuanceError::Refused => { + refused(terminal_credential_response(), FailedCheck::SourceAuthority) + } + _ => terminal_credential_response(), + } } fn terminal_credential_response() -> Response { @@ -1684,17 +1734,61 @@ async fn unknown_route() -> Response { problem(StatusCode::NOT_FOUND, "invalid_request", "no such route") } -fn unauthorized(description: &'static str) -> Response { - let mut response = problem(StatusCode::UNAUTHORIZED, "invalid_token", description); +/// The answer carrying the check that refused the caller in its response +/// extensions, which are never serialized. The request observer reads it. +fn refused(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +fn unauthorized(check: FailedCheck, description: &'static str) -> Response { + let mut response = problem_answer(StatusCode::UNAUTHORIZED, "invalid_token", description); response .headers_mut() .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - response + refused(response, check) +} + +/// Whether a status is an authentication or authorization refusal, which names +/// the check that failed. +fn is_refusal_status(status: StatusCode) -> bool { + matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) +} + +/// An authentication or authorization refusal with the check that failed. +fn refusal( + status: StatusCode, + error: &'static str, + description: impl Into>, + check: FailedCheck, +) -> Response { + refused(problem_answer(status, error, description), check) +} + +/// One error shape for every answer that is not an authentication or +/// authorization refusal. Those are built by [`refusal`] and [`unauthorized`], +/// which take the failed check. +fn problem( + status: StatusCode, + error: &'static str, + description: impl Into>, +) -> Response { + if is_refusal_status(status) { + tracing::error!( + target: "registry_evidence_oid4vci::service", + "a refusal was built without naming its failed check" + ); + debug_assert!( + false, + "a refusal is built with `refusal`, which names its check" + ); + } + problem_answer(status, error, description) } /// One error shape for every refusal: the OAuth members a wallet already reads, /// carrying fixed text chosen here and never any part of the request. -fn problem( +fn problem_answer( status: StatusCode, error: &'static str, description: impl Into>, @@ -1762,6 +1856,78 @@ async fn add_no_store(request: Request, next: Next) -> Response { mod tests { use super::*; + #[test] + fn a_bearer_header_is_classified_by_what_it_lacks() { + let classify = |value: Option<&[u8]>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + AUTHORIZATION, + HeaderValue::from_bytes(value).expect("test header is valid"), + ); + } + bearer_credential(&headers).map(str::to_owned) + }; + assert_eq!(classify(Some(b"Bearer abc")), Ok("abc".to_owned())); + assert_eq!(classify(Some(b"bearer abc")), Ok("abc".to_owned())); + assert_eq!(classify(None), Err(FailedCheck::CredentialMissing)); + assert_eq!( + classify(Some(b"Basic abc")), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + classify(Some(b"Basic")), + Err(FailedCheck::CredentialMissing) + ); + assert_eq!( + classify(Some(b"Bearer ")), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + classify(Some(b"Bearer")), + Err(FailedCheck::CredentialMalformed) + ); + assert_eq!( + classify(Some(&[0xff, 0xfe])), + Err(FailedCheck::CredentialMalformed) + ); + } + + #[test] + fn refusal_answers_carry_their_failed_check() { + for status in [StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN] { + let response = refusal( + status, + "invalid_token", + "refused", + FailedCheck::CredentialMissing, + ); + assert_eq!(response.status(), status); + assert!(response.extensions().get::().is_some()); + } + let response = unauthorized(FailedCheck::CredentialMissing, "refused"); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert!(response.extensions().get::().is_some()); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `refusal`")] + fn an_unauthorized_answer_built_without_a_failed_check_is_caught() { + let _ = problem(StatusCode::UNAUTHORIZED, "invalid_token", "refused"); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `refusal`")] + fn a_forbidden_answer_built_without_a_failed_check_is_caught() { + let _ = problem( + StatusCode::FORBIDDEN, + "invalid_credential_request", + "refused", + ); + } + use std::{ fs, io::Write, @@ -1775,6 +1941,7 @@ mod tests { use axum_test::TestServer; use registry_evidence_client::HolderBoundRequestSpec; use registry_platform_audit::AuditWriter; + use registry_platform_authcommon::FailedCheck; use crate::{ authorizer::AuthorizedOffer, @@ -1798,7 +1965,7 @@ mod tests { fn test_audit_with(sink: Box) -> Arc { Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(sink), + AuditWriter::from_line_sink_without_posture(sink), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -1886,7 +2053,7 @@ mod tests { return Err(AuthorizationError::Missing); } if credential != self.accepted { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), @@ -1895,6 +2062,34 @@ mod tests { } } + /// An authorizer that refuses every credential for its scope and declares + /// the scope gate it enforces. + struct ScopeGateAuthorizer; + + #[async_trait] + impl OfferAuthorizer for ScopeGateAuthorizer { + async fn authorize(&self, _: &str) -> Result { + Err(AuthorizationError::Refused(FailedCheck::Scope)) + } + + fn declared_scope(&self) -> Option { + Some( + registry_platform_authcommon::DeclaredScope::new("scope") + .with_required_scope("offers:create"), + ) + } + } + + /// An authorizer whose issuer key set cannot be reached. + struct UnreachableKeySetAuthorizer; + + #[async_trait] + impl OfferAuthorizer for UnreachableKeySetAuthorizer { + async fn authorize(&self, _: &str) -> Result { + Err(AuthorizationError::KeySource) + } + } + /// Records every request it is asked to issue, and answers with one /// credential per holder key. struct RecordingIssuer { @@ -2738,7 +2933,7 @@ mod tests { impl OfferAuthorizer for PrincipalAuthorizer { async fn authorize(&self, credential: &str) -> Result { if credential != self.token { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: self.client.clone(), @@ -2766,7 +2961,7 @@ mod tests { return Ok(authorized); } } - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenSignature)) } } @@ -3771,6 +3966,49 @@ mod tests { /// The failed check reaches the operator log as well, with the same fixed /// wording and none of the proof's contents. + #[tokio::test] + async fn a_scope_refusal_logs_the_declared_values_and_none_of_the_tokens() { + let buffer = TestLogBuffer::default(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(buffer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + + let directory = canonical_tempdir(); + let service = DeliveryService::with_halves( + load_deployment(directory.path()), + Arc::new(ScopeGateAuthorizer), + Arc::new(RecordingIssuer::new()), + test_audit(), + ); + let server = TestServer::new(build_app(Arc::new(service))); + let refused = server + .post(OFFERS_PATH) + .add_header("authorization", "Bearer scope-canary-held-by-the-token") + .json(&offer_body(false)) + .await; + assert_eq!(refused.status_code(), StatusCode::UNAUTHORIZED); + + let rendered = String::from_utf8(buffer.0.lock().expect("log buffer lock").clone()) + .expect("logs are UTF-8"); + assert!(rendered.contains("request refused"), "logs: {rendered}"); + assert!( + rendered.contains("failed_check=\"scope\""), + "logs: {rendered}" + ); + assert!( + rendered.contains("scope_claim=\"scope\""), + "logs: {rendered}" + ); + assert!( + rendered.contains("required_scope=\"offers:create\""), + "logs: {rendered}" + ); + assert!(!rendered.contains("scope-canary"), "logs: {rendered}"); + } + #[tokio::test] async fn a_refused_proof_logs_the_failed_check_without_the_proof_or_nonce() { let buffer = TestLogBuffer::default(); @@ -5310,4 +5548,373 @@ mod tests { assert_eq!(error.kind(), io::ErrorKind::InvalidInput); } } + + /// An Evidence boundary that refuses: the catalog when `catalog_refused` + /// is set, and every issuance otherwise. + struct RefusingIssuer { + inner: RecordingIssuer, + catalog_refused: bool, + } + + #[async_trait] + impl CredentialIssuer for RefusingIssuer { + async fn catalog(&self) -> Result, IssuanceError> { + if self.catalog_refused { + return Err(IssuanceError::Refused); + } + self.inner.catalog().await + } + + async fn issue(&self, _: HolderBoundRequestSpec) -> Result, IssuanceError> { + Err(IssuanceError::Refused) + } + } + + fn refusing_server( + directory: &Path, + catalog_refused: bool, + ) -> (TestServer, Arc) { + let service = Arc::new(DeliveryService::with_halves( + load_deployment(directory), + Arc::new(StubAuthorizer { + accepted: OFFER_TOKEN.to_owned(), + }), + Arc::new(RefusingIssuer { + inner: RecordingIssuer::new(), + catalog_refused, + }), + test_audit(), + )); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + fn unreachable_key_set_server(directory: &Path) -> (TestServer, Arc) { + let service = Arc::new(DeliveryService::with_halves( + load_deployment(directory), + Arc::new(UnreachableKeySetAuthorizer), + Arc::new(RecordingIssuer::new()), + test_audit(), + )); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + fn draft13_server(directory: &Path) -> (TestServer, Arc) { + let mut config = load_deployment(directory); + config.draft13_profile = true; + let (service, _) = wired_service_over(config); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + fn limited_server(directory: &Path) -> (TestServer, Arc) { + let mut config = load_deployment(directory); + config.rate_limits = tight_limits(); + let (service, _) = wired_service_over(config); + (TestServer::new(build_app(Arc::clone(&service))), service) + } + + /// One refusal as the golden freezes it: status, the headers a caller or + /// proxy acts on, and the body. A `retry-after` on a 429 is the bucket's + /// remaining wait, which moves with the clock, so only its presence is + /// frozen there. + fn frozen_answer(response: &axum_test::TestResponse) -> Value { + let status = response.status_code().as_u16(); + let mut headers = serde_json::Map::new(); + for name in [ + "content-type", + "www-authenticate", + "cache-control", + "pragma", + "retry-after", + ] { + if let Some(value) = response.maybe_header(name) { + let text = if name == "retry-after" && status == 429 { + "".to_owned() + } else { + value.to_str().expect("ASCII header").to_owned() + }; + headers.insert(name.to_owned(), text.into()); + } + } + let body: Value = serde_json::from_slice(response.as_bytes()).expect("a JSON body"); + json!({"status": status, "headers": headers, "body": body}) + } + + /// Every refusal a caller can provoke, with the name the golden files it + /// under and the check that refuses it, or `None` where the answer + /// carries no check. + /// + /// Each case also names which of the returned services answered it, so a + /// test can read that service's counter. + async fn refusal_cases() -> ( + Vec<(&'static str, Option, Value, usize)>, + Vec>, + ) { + let mut cases = Vec::new(); + let current = std::cell::Cell::new(0_usize); + let mut put = |name, check, response: axum_test::TestResponse| { + cases.push((name, check, frozen_answer(&response), current.get())); + }; + let directory = canonical_tempdir(); + let (service, _) = wired_service(directory.path()); + let mut services = vec![Arc::clone(&service)]; + let server = TestServer::new(build_app(service)); + let offer = |authorization: Option<&str>| { + let mut request = server.post(OFFERS_PATH); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.json(&offer_body(false)) + }; + put( + "offer-no-header", + Some(FailedCheck::CredentialMissing), + offer(None).await, + ); + put( + "offer-non-bearer-scheme", + Some(FailedCheck::CredentialMissing), + offer(Some("Basic dXNlcjpwYXNz")).await, + ); + put( + "offer-wrong-token", + Some(FailedCheck::TokenSignature), + offer(Some("Bearer not-the-offer-token")).await, + ); + put( + "token-unknown-code", + Some(FailedCheck::OneTimeCredential), + server + .post(TOKEN_PATH) + .form(&token_form("unknown-code", None)) + .await, + ); + let created = offer(Some(&format!("Bearer {OFFER_TOKEN}"))).await; + let code = offered_code(&created.json()); + server + .post(TOKEN_PATH) + .form(&token_form(&code, None)) + .await + .assert_status_ok(); + put( + "token-redeemed-code", + Some(FailedCheck::OneTimeCredential), + server.post(TOKEN_PATH).form(&token_form(&code, None)).await, + ); + put( + "credential-no-header", + Some(FailedCheck::CredentialMissing), + server.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + put( + "credential-unknown-token", + Some(FailedCheck::OneTimeCredential), + server + .post(CREDENTIAL_PATH) + .add_header("authorization", "Bearer unknown-token") + .json(&json!({})) + .await, + ); + + // The draft 13 profile's own handlers. + let (draft13, service) = draft13_server(directory.path()); + services.push(service); + current.set(1); + put( + "draft13-credential-no-header", + Some(FailedCheck::CredentialMissing), + draft13 + .post(crate::draft13::CREDENTIAL_PATH) + .json(&json!({})) + .await, + ); + put( + "draft13-credential-unknown-token", + Some(FailedCheck::OneTimeCredential), + draft13 + .post(crate::draft13::CREDENTIAL_PATH) + .add_header("authorization", "Bearer unknown-token") + .json(&json!({})) + .await, + ); + put( + "draft13-token-unknown-code", + Some(FailedCheck::OneTimeCredential), + draft13 + .post(crate::draft13::TOKEN_PATH) + .form(&token_form("unknown-code", None)) + .await, + ); + + // Spent budgets. + let (limited, service) = limited_server(directory.path()); + services.push(service); + current.set(2); + limited.post(NONCE_PATH).await.assert_status_ok(); + put( + "nonce-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(NONCE_PATH).await, + ); + put( + "setup-token", + Some(FailedCheck::OneTimeCredential), + limited.post(TOKEN_PATH).form(&token_form("x", None)).await, + ); + put( + "token-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(TOKEN_PATH).form(&token_form("x", None)).await, + ); + put( + "setup-credential", + Some(FailedCheck::CredentialMissing), + limited.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + put( + "credential-rate-limited", + Some(FailedCheck::RateLimit), + limited.post(CREDENTIAL_PATH).json(&json!({})).await, + ); + let offers = || { + limited + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + }; + offers().await; + put( + "offer-rate-limited", + Some(FailedCheck::RateLimit), + offers().await, + ); + + // An issuer key set that cannot be reached. + let (unreachable, service) = unreachable_key_set_server(directory.path()); + services.push(service); + current.set(3); + put( + "offer-key-source-unavailable", + Some(FailedCheck::KeySourceUnavailable), + unreachable + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + .await, + ); + + // Evidence refusing. + let (refused_catalog, service) = refusing_server(directory.path(), true); + services.push(service); + current.set(4); + put( + "offer-evidence-refused", + Some(FailedCheck::SourceAuthority), + refused_catalog + .post(OFFERS_PATH) + .add_header("authorization", format!("Bearer {OFFER_TOKEN}")) + .json(&offer_body(false)) + .await, + ); + let (refused_issue, service) = refusing_server(directory.path(), false); + services.push(service); + current.set(5); + let token = access_token(&refused_issue).await; + let nonce = minted_nonce(&refused_issue).await; + let key = private_jwk("refusal-golden"); + put( + "credential-evidence-refused", + Some(FailedCheck::SourceAuthority), + refused_issue + .post(CREDENTIAL_PATH) + .add_header("authorization", format!("Bearer {token}")) + .json(&json!({ + "credential_configuration_id": CONFIGURATION_ID, + "proofs": {"jwt": [proof_jwt(&key, "https://wallet.example.org", &nonce, now())]}, + })) + .await, + ); + (cases, services) + } + + /// The refusals as the whole router answers them, frozen in a checked-in + /// file that was written from the tree before any recording existed. Run + /// with `REGISTRY_OID4VCI_WRITE_GOLDEN=1` to rewrite it. + #[tokio::test] + async fn refusal_answers_match_the_golden() { + let mut answers = serde_json::Map::new(); + for (name, _, answer, _) in refusal_cases().await.0 { + // Setup requests spend a budget and are counted, but are not part + // of the frozen set. + if !name.starts_with("setup-") { + answers.insert(name.to_owned(), answer); + } + } + let actual = Value::Object(answers); + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + if std::env::var_os("REGISTRY_OID4VCI_WRITE_GOLDEN").is_some() { + fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: Value = + serde_json::from_slice(&fs::read(&path).expect("golden file")).expect("golden json"); + assert_eq!(actual, expected); + } + + /// Every refusal is counted under its check in the service that answered + /// it, nothing else is counted, and the log carries fixed lines only. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_its_check() { + // The shared capture keeps a parallel test that reaches the refusal + // callsite with no subscriber from disabling it for this one. + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let _logging = tracing::dispatcher::set_default(&captured.subscriber()); + + let (cases, services) = refusal_cases().await; + for (index, service) in services.iter().enumerate() { + for check in FailedCheck::ALL { + let expected = cases + .iter() + .filter(|(_, case_check, _, case_index)| { + *case_index == index && *case_check == Some(check) + }) + .count() as u64; + assert_eq!( + service + .metrics + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is declared"), + expected, + "service {index}, check {}", + check.as_str() + ); + } + } + let rendered = captured.text(); + for (name, check, _, _) in &cases { + let check = check.expect("every case names its check"); + assert!( + rendered.contains(&format!("\"failed_check\":\"{}\"", check.as_str())), + "{name}: no log line for {}: {rendered}", + check.as_str() + ); + } + assert!(rendered.contains("request refused"), "{rendered}"); + for canary in [ + OFFER_TOKEN, + "not-the-offer-token", + "unknown-token", + "unknown-code", + SELECTOR_VALUE, + "adopter-front-end", + "Basic dXNlcjpwYXNz", + ] { + assert!(!rendered.contains(canary), "logs rendered {canary}"); + } + } } diff --git a/crates/registry-evidence-oid4vci/src/service/draft13.rs b/crates/registry-evidence-oid4vci/src/service/draft13.rs index 698059d4a9..dacfbbb874 100644 --- a/crates/registry-evidence-oid4vci/src/service/draft13.rs +++ b/crates/registry-evidence-oid4vci/src/service/draft13.rs @@ -108,8 +108,9 @@ async fn credential( headers: HeaderMap, body: Bytes, ) -> Response { - let Some(access_token) = bearer_credential(&headers) else { - return unauthorized("a bearer access token is required"); + let access_token = match bearer_credential(&headers) { + Ok(access_token) => access_token, + Err(check) => return unauthorized(check, "a bearer access token is required"), }; let access_token = Zeroizing::new(access_token.to_owned()); stage.mark_claiming_token(); @@ -125,7 +126,10 @@ async fn credential( Ok(prepared) => prepared, Err(StoreError::Unknown) => { service.metrics.record_outcome(Outcome::TokenClaimRefused); - return unauthorized("the access token cannot be used"); + return unauthorized( + FailedCheck::OneTimeCredential, + "the access token cannot be used", + ); } Err(error) => return store_response(&service, &error, Outcome::TokenClaimRefused), }; diff --git a/crates/registry-evidence-oid4vci/tests/audit_attribution.rs b/crates/registry-evidence-oid4vci/tests/audit_attribution.rs index b65935a33a..2b92cef986 100644 --- a/crates/registry-evidence-oid4vci/tests/audit_attribution.rs +++ b/crates/registry-evidence-oid4vci/tests/audit_attribution.rs @@ -46,7 +46,7 @@ impl CapturedLines { async fn offer_audit_refuses_an_exchange_without_a_verified_identity() { let captured = CapturedLines::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile is valid"); @@ -64,7 +64,7 @@ async fn offer_audit_refuses_an_exchange_without_a_verified_identity() { async fn offer_and_delivery_audit_is_correlated_and_privacy_safe() { let captured = CapturedLines::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile is valid"); diff --git a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs index 2de7611290..a08676207f 100644 --- a/crates/registry-evidence-oid4vci/tests/draft13_profile.rs +++ b/crates/registry-evidence-oid4vci/tests/draft13_profile.rs @@ -48,6 +48,7 @@ use registry_evidence_verifier::{ EVIDENCE_SCHEMA_V1, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{hmac_sha256_base64url_no_pad, sign, PrivateJwk}; use registry_platform_sdjwt::SdJwtIssuer; use serde_json::{json, Value}; @@ -151,7 +152,7 @@ impl OfferAuthorizer for StubAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), @@ -313,7 +314,7 @@ fn harness(draft13: bool) -> Harness { Arc::clone(&issuer) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -1254,7 +1255,7 @@ async fn inspect_shows_the_draft13_metadata_only_when_the_profile_is_on() { Arc::new(SigningIssuer::new()) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(std::io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(std::io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/golden/refusals.json b/crates/registry-evidence-oid4vci/tests/golden/refusals.json new file mode 100644 index 0000000000..d2c0b0463c --- /dev/null +++ b/crates/registry-evidence-oid4vci/tests/golden/refusals.json @@ -0,0 +1,217 @@ +{ + "credential-evidence-refused": { + "body": { + "error": "credential_request_denied", + "error_description": "this credential request cannot be completed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "credential-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "credential-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "credential-unknown-token": { + "body": { + "error": "invalid_token", + "error_description": "the access token cannot be used" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-credential-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-credential-unknown-token": { + "body": { + "error": "invalid_token", + "error_description": "the access token cannot be used" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "draft13-token-unknown-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "nonce-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "offer-evidence-refused": { + "body": { + "error": "invalid_credential_request", + "error_description": "the credential source refused this request" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 403 + }, + "offer-key-source-unavailable": { + "body": { + "error": "temporarily_unavailable", + "error_description": "offers cannot be authorized at the moment" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 503 + }, + "offer-no-header": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "offer-non-bearer-scheme": { + "body": { + "error": "invalid_token", + "error_description": "a bearer access token is required" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "offer-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "offer-wrong-token": { + "body": { + "error": "invalid_token", + "error_description": "the presented credential was refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-rate-limited": { + "body": { + "error": "temporarily_unavailable", + "error_description": "too many requests; retry after the interval in Retry-After" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache", + "retry-after": "" + }, + "status": 429 + }, + "token-redeemed-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + }, + "token-unknown-code": { + "body": { + "error": "invalid_grant", + "error_description": "the pre-authorized code cannot be redeemed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "pragma": "no-cache" + }, + "status": 400 + } +} diff --git a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs index f8c97e3799..26827cc5fe 100644 --- a/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs +++ b/crates/registry-evidence-oid4vci/tests/inji_interoperability.rs @@ -62,6 +62,7 @@ use registry_evidence_verifier::{ EVIDENCE_SCHEMA_V1, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{hmac_sha256_base64url_no_pad, sign, PrivateJwk, PublicJwk}; use registry_platform_sdjwt::{presentation_disclosure_hash, SdJwtIssuer}; use serde_json::{json, Value}; @@ -165,7 +166,7 @@ impl OfferAuthorizer for FixtureAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("fixture-adopter".to_owned()), @@ -365,7 +366,7 @@ fn deployment() -> (tempfile::TempDir, Arc, TestServer) { Arc::clone(&issuer) as Arc, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs index fa8a1e9287..f86b1c689a 100644 --- a/crates/registry-evidence-oid4vci/tests/offer_authorization.rs +++ b/crates/registry-evidence-oid4vci/tests/offer_authorization.rs @@ -28,6 +28,7 @@ use registry_evidence_oid4vci::{ config::{AccessTokenAlgorithm, OfferAuthorizationConfig, Restriction}, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, PrivateJwk, PublicJwk}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier}; use registry_thunderid_tooling::{ @@ -134,7 +135,7 @@ async fn a_token_without_the_required_offer_scope_is_refused() { config.required_scopes = Restriction::Listed(vec!["oid4vci:offer".to_owned()]); assert_eq!( resource_server(&config, &key_set).authorize(&issued).await, - Err(AuthorizationError::Refused), + Err(AuthorizationError::Refused(FailedCheck::Scope)), "a correctly signed audience-matching token with no offer scope authorized an offer" ); @@ -221,7 +222,7 @@ async fn restricted_and_unrestricted_clients_audit_the_same_canonical_azp() { let captured = AuditCapture::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile loads"); @@ -263,7 +264,7 @@ async fn a_sub_only_offer_token_is_accepted_and_audited_without_inventing_a_clie let captured = AuditCapture::default(); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(captured.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the audit profile loads"); @@ -295,7 +296,7 @@ async fn an_offer_token_without_a_nonempty_client_or_subject_is_refused() { let (token, keys) = signed_offer_fixture(identities); assert_eq!( resource_server(&config, &keys).authorize(&token).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenClient)) ); } } @@ -321,13 +322,13 @@ async fn task_bound_and_partial_grants_cannot_create_deferred_wallet_offers() { }; assert_eq!( resource_server(&config, &keys).authorize(&task_bound).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)) ); let (partial, keys) = signed_offer_fixture(json!({"registry_grant_id":"grant-a"})); assert_eq!( resource_server(&config, &keys).authorize(&partial).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TaskGrantClaims)) ); } @@ -362,7 +363,7 @@ async fn a_token_issued_for_another_resource_server_is_refused() { ) .authorize(&token) .await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenAudience)) ); } @@ -378,11 +379,13 @@ async fn a_token_this_issuer_did_not_sign_is_refused() { let forged = format!("{}.{}", parts.join("."), URL_SAFE_NO_PAD.encode([0_u8; 64])); assert_eq!( server.authorize(&forged).await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused(FailedCheck::TokenSignature)) ); assert_eq!( server.authorize("not-a-token").await, - Err(AuthorizationError::Refused) + Err(AuthorizationError::Refused( + FailedCheck::CredentialMalformed + )) ); assert_eq!(server.authorize("").await, Err(AuthorizationError::Missing)); } diff --git a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs index 2a598910cf..25e4fe04c2 100644 --- a/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs +++ b/crates/registry-evidence-oid4vci/tests/state_machine_recovery.rs @@ -37,6 +37,7 @@ use registry_evidence_oid4vci::{ PRE_AUTHORIZED_CODE_GRANT_TYPE, }; use registry_platform_audit::AuditWriter; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, PrivateJwk}; use serde_json::{json, Value}; use tokio::sync::Barrier; @@ -123,7 +124,7 @@ impl OfferAuthorizer for StubAuthorizer { return Err(AuthorizationError::Missing); } if credential != OFFER_TOKEN { - return Err(AuthorizationError::Refused); + return Err(AuthorizationError::Refused(FailedCheck::TokenSignature)); } Ok(AuthorizedOffer { client: Some("adopter-front-end".to_owned()), @@ -403,7 +404,7 @@ fn service_with_issuer( issuer, Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -873,7 +874,7 @@ async fn post_claim_evidence_failures_are_terminal_and_never_restore_the_token() let audit_capture = AuditCapture::default(); let audit = Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(audit_capture.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(audit_capture.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), @@ -942,7 +943,7 @@ async fn a_post_claim_timeout_is_terminal_and_never_restores_the_token() { let audit_capture = AuditCapture::default(); let audit = Arc::new( DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(audit_capture.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(audit_capture.clone())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"), diff --git a/crates/registry-evidence-oid4vci/tests/store_contract.rs b/crates/registry-evidence-oid4vci/tests/store_contract.rs index 405ef69a79..9d594f8c87 100644 --- a/crates/registry-evidence-oid4vci/tests/store_contract.rs +++ b/crates/registry-evidence-oid4vci/tests/store_contract.rs @@ -1093,7 +1093,7 @@ store: std::fs::write(&path, SERVICE_CONFIG).expect("write the test deployment"); let config = DeliveryConfig::load(&path).expect("the test deployment loads"); let audit = DeliveryAudit::with_writer( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), b"0123456789abcdef0123456789abcdef".to_vec(), ) .expect("the test audit profile is valid"); diff --git a/crates/registry-evidence-oid4vci/tests/token_characterisation.rs b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs new file mode 100644 index 0000000000..c2fcad6e01 --- /dev/null +++ b/crates/registry-evidence-oid4vci/tests/token_characterisation.rs @@ -0,0 +1,187 @@ +//! Characterises the Evidence OID4VCI offer endpoint's access-token +//! authentication against the shared token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Every row of `expected.yaml` with an `evidence-oid4vci` cell runs through +//! `MintResourceServer::from_config`, the constructor the server calls, with +//! the issuer key set served over HTTP from a loopback listener. +//! +//! `OfferAuthorizer::authorize` collapses every verifier refusal into one +//! error, so the refusal stage is named by a second verifier built from the +//! exported `verifier_profile` over the same configuration. It is consulted +//! only after the real resource server has refused. + +use std::sync::Arc; + +use axum::{routing::get, Json, Router}; +use jsonwebtoken::jwk::JwkSet; +use registry_evidence_oid4vci::{ + authorizer::{verifier_profile, AuthorizationError, MintResourceServer, OfferAuthorizer}, + config::{AccessTokenAlgorithm, OfferAuthorizationConfig, Restriction, ValidationMode}, +}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier}; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenSigner, +}; +use serde_json::Value; + +/// The audience the product under test is configured with. +const PRODUCT_AUDIENCE: &str = "evidence-oid4vci-fixture"; + +/// The client the `default` configuration admits when a fixture names none, +/// and the scope the `recipe` configuration requires when a fixture carries +/// none. +const FALLBACK_CLIENT: &str = "journey-app"; +const FALLBACK_SCOPE: &str = "oid4vci:offer"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +fn fixture_client(case: &FixtureCase) -> Option { + literal_string(case, "client_id").or_else(|| literal_string(case, "azp")) +} + +/// The first scope the fixture carries, read from `scope` or `scp`. +fn first_scope(case: &FixtureCase) -> Option { + case.fixture + .read_scope("scope") + .or_else(|| case.fixture.read_scope("scp")) +} + +/// The algorithm the offer boundary is configured with for the row: the +/// fixture's own where the product admits it, and ES256 otherwise. +fn configured_algorithm(case: &FixtureCase) -> AccessTokenAlgorithm { + match case + .fixture + .header + .as_ref() + .map(|header| header.alg.as_str()) + { + Some("RS256") => AccessTokenAlgorithm::RS256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::ES256, + } +} + +fn row_config(case: &FixtureCase, jwks_uri: &str) -> OfferAuthorizationConfig { + let allowed_clients = match (case.configuration, fixture_client(case)) { + (Configuration::Default, client) => { + Restriction::Listed(vec![client.unwrap_or_else(|| FALLBACK_CLIENT.to_owned())]) + } + (_, Some(client)) => Restriction::Listed(vec![client]), + (_, None) => Restriction::Unrestricted, + }; + let required_scopes = match case.configuration { + Configuration::Default => Restriction::Unrestricted, + _ => Restriction::Listed(vec![ + first_scope(case).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()) + ]), + }; + OfferAuthorizationConfig { + claims: Default::default(), + issuer: case.issuer.clone(), + jwks_uri: jwks_uri.to_owned(), + allow_insecure_http: true, + audiences: vec![case.audience.clone()], + algorithms: vec![configured_algorithm(case)], + allowed_clients, + required_scopes, + maximum_token_lifetime_seconds: 86_400, + } +} + +/// Serve the signer's public key set from a loopback listener and return the +/// origin, which doubles as the issuer. +async fn serve_key_set(key_set: Value) -> String { + let app = Router::new().route( + "/jwks.json", + get(move || { + let key_set = key_set.clone(); + async move { Json(key_set) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback port is free"); + let port = listener + .local_addr() + .expect("the listener has an address") + .port(); + tokio::spawn(async move { + axum::serve(listener, app) + .await + .expect("the key set server runs for the test"); + }); + format!("http://127.0.0.1:{port}") +} + +/// The stage at which the shared verifier, under the product's own profile, +/// refuses the token. A token it admits is refused by the product's scope gate +/// or by its own claim rules. +async fn refusal_stage(config: &OfferAuthorizationConfig, case: &FixtureCase) -> Stage { + let jwks: JwkSet = serde_json::from_value(case.jwks.clone()).expect("the key set parses"); + let verifier = TokenVerifier::new( + verifier_profile(config), + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ); + match verifier.verify(case.token.expose()).await { + Err(error) => match Outcome::refused_by(&error) { + Outcome::Refused(stage) => stage, + other => panic!("the verifier error {error:?} is not a refusal: {other:?}"), + }, + Ok(verified) => { + let present: Vec<&str> = verified.scopes.iter().map(String::as_str).collect(); + let scope_missing = config + .required_scopes + .items() + .iter() + .any(|scope| !present.contains(&scope.as_str())); + if scope_missing { + Stage::Scope + } else { + Stage::Claims + } + } + } +} + +async fn authorize(case: FixtureCase, key_set_uri: String) -> Outcome { + let config = row_config(&case, &key_set_uri); + let server = + MintResourceServer::from_config(&config, ValidationMode::SupervisedLocalDevelopment); + match server.authorize(case.token.expose()).await { + Ok(_) => Outcome::Admitted(None), + Err(AuthorizationError::Missing) => Outcome::Refused(Stage::Header), + Err(AuthorizationError::KeySource) => Outcome::Refused(Stage::Unavailable), + Err(AuthorizationError::Refused(_)) => { + Outcome::Refused(refusal_stage(&config, &case).await) + } + } +} + +#[tokio::test] +async fn evidence_oid4vci_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let origin = serve_key_set(signer.public_key_set()).await; + let key_set_uri = format!("{origin}/jwks.json"); + let report = corpus + .run_product_async( + "evidence-oid4vci", + &signer, + &origin, + PRODUCT_AUDIENCE, + |case| authorize(case, key_set_uri.clone()), + ) + .await + .expect("the corpus runs for evidence-oid4vci"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran through the offer boundary" + ); + report.assert_matches(); +} diff --git a/crates/registry-evidence-oid4vp/Cargo.toml b/crates/registry-evidence-oid4vp/Cargo.toml index 7e58d24d42..d3906c2bb0 100644 --- a/crates/registry-evidence-oid4vp/Cargo.toml +++ b/crates/registry-evidence-oid4vp/Cargo.toml @@ -31,12 +31,12 @@ chrono.workspace = true clap.workspace = true der.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-crypto = { workspace = true, features = ["jwe"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["refusal-trace-id", "server"] } registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true registry-platform-ratelimit.workspace = true diff --git a/crates/registry-evidence-oid4vp/src/audit.rs b/crates/registry-evidence-oid4vp/src/audit.rs index b1cdee7998..6ca40e502b 100644 --- a/crates/registry-evidence-oid4vp/src/audit.rs +++ b/crates/registry-evidence-oid4vp/src/audit.rs @@ -47,7 +47,7 @@ impl SessionAudit { master_secret: Zeroizing>, ) -> Result { let profile = AuditProfile::production_from_secret_bytes(master_secret)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher: profile.key_hasher(), diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index b1d382282e..809858bab6 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -9,7 +9,9 @@ use std::{sync::Arc, time::Duration}; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, DeclaredScope, FailedCheck, +}; use registry_platform_config::{JwksSource, SecretResolver}; use registry_platform_oidc::{ parse_static_jwks, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, @@ -24,14 +26,25 @@ const ACCESS_TOKEN_TYPES: [&str; 2] = ["at+jwt", "application/at+jwt"]; /// Why a request was not authenticated. #[derive(Debug, Eq, PartialEq, thiserror::Error)] pub enum AuthError { - #[error("the request carried no bearer credential")] - Missing, + /// The caller's credential was refused, under the check that refused it. #[error("the presented credential was refused")] - Refused, + Refused(FailedCheck), #[error("the issuer key set is unavailable")] KeySource, } +impl AuthError { + /// The check the request failed. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) => *check, + Self::KeySource => FailedCheck::KeySourceUnavailable, + } + } +} + /// Why an authenticator could not be built at startup. #[derive(Debug, thiserror::Error)] pub enum AuthSetupError { @@ -41,8 +54,10 @@ pub enum AuthSetupError { Discovery, #[error("the static key set secret could not be read")] StaticKeySecret, - #[error("the static key set is not a valid JWKS")] - StaticKeySet, + /// The validator's account of the rule the document broke. It names a key + /// position and a member, never a value. + #[error("the static key set is not a valid JWKS: {0}")] + StaticKeySet(String), } /// Verifies bearer tokens from one issuer and extracts the caller. @@ -50,6 +65,8 @@ pub struct TokenAuthenticator { verifier: TokenVerifier, issuer: String, required_scope: String, + /// The claim the verifier reads scopes from. + scope_claim: String, } impl std::fmt::Debug for TokenAuthenticator { @@ -96,12 +113,12 @@ impl TokenAuthenticator { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets .resolve(document_ref) .map_err(|_| AuthSetupError::StaticKeySecret)?; let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| AuthSetupError::StaticKeySet)?; + .map_err(|error| AuthSetupError::StaticKeySet(error.to_string()))?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -124,27 +141,33 @@ impl TokenAuthenticator { if let Some(client) = &config.allowed_client { profile = profile.with_allowed_clients(vec![client.clone()]); } + let scope_claim = profile.scope_claim.clone(); Ok(Self { verifier: TokenVerifier::new(profile, Arc::new(fetcher)), issuer, required_scope: config.required_scope.clone(), + scope_claim, }) } + /// What a scope refusal may say about this gate: the configured claim and + /// the configured scope, never a value the token carried. + #[must_use] + pub fn declared_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.required_scope) + } + /// Authenticate the value of an `Authorization` header. pub async fn authenticate(&self, authorization: Option<&str>) -> Result { - let header = authorization.ok_or(AuthError::Missing)?; - let token = parse_bearer_token(header).map_err(|_| AuthError::Missing)?; + let header = authorization.ok_or(AuthError::Refused(FailedCheck::CredentialMissing))?; + let token = parse_bearer_token(header).map_err(|error| match error { + BearerParseError::InvalidScheme => AuthError::Refused(FailedCheck::CredentialMissing), + _ => AuthError::Refused(FailedCheck::CredentialMalformed), + })?; let verified = match self.verifier.verify(token).await { Ok(verified) => verified, - Err(error) if is_key_source_failure(&error) => { - tracing::warn!( - target: "registry_evidence_oid4vp::auth", - "the issuer key set is unavailable" - ); - return Err(AuthError::KeySource); - } - Err(_) => return Err(AuthError::Refused), + Err(error) if is_key_source_failure(&error) => return Err(AuthError::KeySource), + Err(error) => return Err(AuthError::Refused(error.failed_check())), }; // The scope gate runs on the verified token's scope set: a correctly // signed token for this audience without the scope grants nothing. @@ -153,7 +176,7 @@ impl TokenAuthenticator { .iter() .any(|scope| scope == &self.required_scope) { - return Err(AuthError::Refused); + return Err(AuthError::Refused(FailedCheck::Scope)); } let client = match verified.matched_client_id() { Ok(Some(client)) => Some(client.to_owned()), @@ -162,12 +185,12 @@ impl TokenAuthenticator { .azp .clone() .or_else(|| verified.claims.client_id.clone()), - Err(_) => return Err(AuthError::Refused), + Err(_) => return Err(AuthError::Refused(FailedCheck::TokenClient)), } .filter(|client| !client.is_empty()); let subject = verified.claims.sub.clone().filter(|sub| !sub.is_empty()); if client.is_none() && subject.is_none() { - return Err(AuthError::Refused); + return Err(AuthError::Refused(FailedCheck::TokenClient)); } Ok(Principal { issuer: verified diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index c3c497d959..30f6e508f8 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -62,7 +62,7 @@ const REMOVED_KEYS: &[RemovedKey] = &[ /// The shared runtime reader for a runtime file. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: OID4VP_RUNTIME_API_VERSION, kind: OID4VP_RUNTIME_KIND, }) @@ -1288,7 +1288,9 @@ impl VerifierDocument { ("/applicantTokens", &self.applicant_tokens.provider), ("/evidenceCredentials", &self.evidence_credentials.provider), ] { - if let JwksSource::Static { document_ref } = &provider.jwks_source { + if let JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } = + &provider.jwks_source + { if self .secret_providers .check_reference(pointer, document_ref) @@ -1321,7 +1323,7 @@ impl VerifierDocument { &self.evidence_credentials.provider, ), ] { - let Err(error) = provider.check(field, false) else { + let Err(error) = provider.check_without_posture(field, false) else { continue; }; let member = error.field().rsplit('.').next().unwrap_or_default(); diff --git a/crates/registry-evidence-oid4vp/src/metrics.rs b/crates/registry-evidence-oid4vp/src/metrics.rs index 7d728733bf..db98facfdb 100644 --- a/crates/registry-evidence-oid4vp/src/metrics.rs +++ b/crates/registry-evidence-oid4vp/src/metrics.rs @@ -13,6 +13,7 @@ use axum::{ routing::get, Router, }; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, MetricsError, CONTENT_TYPE as METRICS_TYPE, }; @@ -115,6 +116,7 @@ impl Event { /// The service's counters. pub struct Metrics { events: CounterVec, + refusals: Arc, } impl Metrics { @@ -127,9 +129,17 @@ impl Metrics { "Presentation session, request, response, and read events by outcome.", LabelSpace::closed_zero_filled(&["event"], &declared)?, )?, + refusals: Arc::new(RefusalRecorder::new("evidence_oid4vp")?), }) } + /// The recorder that counts each refused request under its check and + /// admits a bounded number of log lines. + #[must_use] + pub const fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + pub fn record(&self, event: Event) { if self.events.inc(&[event.label()]).is_err() { tracing::error!("a metric event was refused by its closed label space"); @@ -145,6 +155,7 @@ impl Metrics { pub fn render(&self, store: &SessionStore) -> Result { let mut out = Exposition::new(); self.events.write(&mut out)?; + self.refusals.counter().write(&mut out)?; out.header( "evidence_oid4vp_sessions", Some("Presentation sessions held in memory, expired ones not yet cleaned up included."), @@ -174,3 +185,36 @@ async fn scrape(State(state): State) -> Response { Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } + +#[cfg(test)] +mod tests { + use registry_platform_authcommon::FailedCheck; + + use super::*; + use crate::session::system_clock; + + #[test] + fn the_scrape_publishes_every_check_at_zero_and_counts_a_refusal_under_its_check() { + let metrics = Metrics::new().expect("the metrics declare"); + let store = SessionStore::new(4, 1024, system_clock()); + let scrape = metrics.render(&store).expect("the scrape renders"); + for check in FailedCheck::ALL { + let series = format!( + "evidence_oid4vp_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + assert!( + scrape.contains(&format!("{series}0")), + "{} is published at zero", + check.as_str() + ); + } + + assert!(metrics + .refusal_recorder() + .record(FailedCheck::Scope) + .is_some()); + let scrape = metrics.render(&store).expect("the scrape renders"); + assert!(scrape.contains("evidence_oid4vp_request_refusals_total{check=\"scope\"} 1")); + } +} diff --git a/crates/registry-evidence-oid4vp/src/service.rs b/crates/registry-evidence-oid4vp/src/service.rs index 03c6411459..22e6a6332a 100644 --- a/crates/registry-evidence-oid4vp/src/service.rs +++ b/crates/registry-evidence-oid4vp/src/service.rs @@ -23,10 +23,11 @@ use axum::{ Json, Router, }; use chrono::{DateTime, SecondsFormat, Utc}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck, RefusalNote, RefusalRecorder}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit, security_headers, CspBuilder, - FrameworkRejection, Problem, TraceContext, + normalize_framework_rejection, request_body_limit, security_headers_without_posture, + CspBuilder, FrameworkRejection, Problem, TraceContext, }; use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, @@ -39,7 +40,7 @@ use zeroize::Zeroizing; use crate::{ audit::{AuditFailure, Pending, SessionAudit}, - auth::{AuthError, TokenAuthenticator}, + auth::{AuthError, AuthSetupError, TokenAuthenticator}, client_identifier::RequestIdentity, config::{Oid4vpConfig, PolicyConfig}, metrics::{metrics_app, Event, Metrics}, @@ -95,7 +96,7 @@ impl StartupError { fn new( code: &'static str, pointer: &'static str, - message: &'static str, + message: impl Into, action: &'static str, ) -> Self { Self { @@ -204,11 +205,11 @@ impl VerifierService { let jwks = (!keys.is_empty()).then(|| json!({ "keys": keys }).to_string()); let applicants = TokenAuthenticator::build(&config.applicant_tokens, &resolver) .await - .map_err(|_| issuer_unavailable("/applicantTokens"))?; + .map_err(|error| issuer_unavailable("/applicantTokens", &error))?; let evidence_credentials = TokenAuthenticator::build(&config.evidence_credentials, &resolver) .await - .map_err(|_| issuer_unavailable("/evidenceCredentials"))?; + .map_err(|error| issuer_unavailable("/evidenceCredentials", &error))?; let audit_key = resolver .resolve_binary_reference(&config.audit.key.hash_key_ref) @@ -375,12 +376,24 @@ impl VerifierService { } } -fn issuer_unavailable(pointer: &'static str) -> StartupError { +fn issuer_unavailable(pointer: &'static str, error: &AuthSetupError) -> StartupError { + // A static key set the validator refused says which rule it broke, so the + // fix starts at the document rather than at the issuer's reachability. + let (message, action) = match error { + AuthSetupError::StaticKeySet(refusal) => ( + refusal.clone(), + "Replace the document behind jwksSource.documentRef with a public key set that follows the rule named here.", + ), + _ => ( + "the token issuer or its key source could not be set up".to_owned(), + "Check the issuer, its key source, and that the service can reach it.", + ), + }; StartupError::new( "evidence.oid4vp.issuer-unavailable", pointer, - "the token issuer or its key source could not be set up", - "Check the issuer, its key source, and that the service can reach it.", + message, + action, ) } @@ -412,6 +425,7 @@ pub fn build_app(service: Arc) -> Router { .route(RESPONSE_PATH, post(receive_response)) .layer(DefaultBodyLimit::max(response::MAX_BODY_BYTES)) .layer(request_body_limit(response::MAX_BODY_BYTES)); + let refusals = Arc::clone(service.metrics.refusal_recorder()); general .merge(responses) .fallback(unknown_route) @@ -419,8 +433,11 @@ pub fn build_app(service: Arc) -> Router { .with_state(service) .layer(from_fn_with_state(timeout, bound_request_time)) .layer(from_fn(normalize_rejections)) - .layer(security_headers(CspBuilder::deny_by_default())) + .layer(security_headers_without_posture( + CspBuilder::deny_by_default(), + )) .layer(from_fn(apply_trace_context)) + .layer(from_fn_with_state(refusals, record_refusals)) } /// The outermost layer: every response, whichever layer or handler produced @@ -485,7 +502,30 @@ async fn normalize_rejections(request: Request, next: Next) -> Response { response } +/// Whether the answer to this problem is an authentication or authorization +/// refusal, which names the check that failed. +fn is_refusal(status: StatusCode) -> bool { + matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) +} + +/// A problem answer that is not an authentication or authorization refusal. +/// Those are built by [`unauthorized`], which takes the failed check. fn problem(code: ProblemCode, detail: &str) -> Response { + let response = problem_answer(code, detail); + if is_refusal(response.status()) { + tracing::error!( + target: "registry_evidence_oid4vp::service", + "a refusal was built without naming its failed check" + ); + debug_assert!( + false, + "a refusal is built with `unauthorized`, which names its check" + ); + } + response +} + +fn problem_answer(code: ProblemCode, detail: &str) -> Response { let status = StatusCode::from_u16(code.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); Problem::new(&code.type_uri(), code.title(), status) @@ -500,6 +540,78 @@ fn retry_after(mut response: Response, seconds: u64) -> Response { response } +/// The answer carrying the check that refused the caller in its response +/// extensions, which are never serialized. The recording layer reads it. +fn refused(mut response: Response, check: FailedCheck) -> Response { + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +/// The 401 a caller without an acceptable bearer credential receives. +fn unauthorized(check: FailedCheck) -> Response { + let mut response = problem_answer( + ProblemCode::Unauthorized, + "a valid bearer token is required", + ); + response + .headers_mut() + .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + refused(response, check) +} + +/// The 401 for a caller the authenticator refused. A scope refusal also +/// carries the gate's configured values for the operator's log line. +fn refused_by(check: FailedCheck, authenticator: &TokenAuthenticator) -> Response { + let mut response = unauthorized(check); + if check == FailedCheck::Scope { + response + .extensions_mut() + .insert(authenticator.declared_scope()); + } + response +} + +/// The 503 a caller receives when the issuer's key set cannot be used. +fn issuer_unavailable_answer() -> Response { + refused( + retry_after( + problem( + ProblemCode::IssuerUnavailable, + "the token issuer is unavailable", + ), + 5, + ), + FailedCheck::KeySourceUnavailable, + ) +} + +/// Count each refusal answer under its check and write the admitted log line. +/// The trace id is the one the answer carries. +async fn record_refusals( + State(refusals): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + let declared = response.extensions().get::(); + match registry_platform_httpsec::response_trace_id(response.headers()) { + Ok(trace) => { + registry_platform_authcommon::record_refusal!( + refusals, + *note, + trace_id = trace, + declared = declared + ); + } + Err(_) => { + registry_platform_authcommon::record_refusal!(refusals, *note, declared = declared); + } + } + } + response +} + async fn unknown_route() -> Response { problem(ProblemCode::NotFound, "no such route") } @@ -562,33 +674,27 @@ async fn ready(State(service): State>) -> Response { } } +/// The `Authorization` header as text. A header that is present but not +/// readable as text reads as an empty value, which the authenticator refuses as +/// a malformed credential rather than counting it as absent. +fn authorization_header(headers: &HeaderMap) -> Option<&str> { + headers + .get(AUTHORIZATION) + .map(|value| value.to_str().unwrap_or_default()) +} + /// Authenticate the applicant, or return the response that refuses them. async fn applicant(service: &VerifierService, headers: &HeaderMap) -> Result { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()); + let authorization = authorization_header(headers); match service.applicants.authenticate(authorization).await { Ok(principal) => Ok(principal), Err(AuthError::KeySource) => { service.metrics.record(Event::SessionRefusedUnavailable); - Err(retry_after( - problem( - ProblemCode::IssuerUnavailable, - "the token issuer is unavailable", - ), - 5, - )) + Err(issuer_unavailable_answer()) } - Err(AuthError::Missing | AuthError::Refused) => { + Err(AuthError::Refused(check)) => { service.metrics.record(Event::SessionRefusedAuthentication); - let mut response = problem( - ProblemCode::Unauthorized, - "a valid bearer token is required", - ); - response - .headers_mut() - .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - Err(response) + Err(refused_by(check, &service.applicants)) } } } @@ -769,7 +875,10 @@ async fn session_status( } None => { service.metrics.record(Event::StatusNotFound); - problem(ProblemCode::SessionNotFound, "no such session") + refused( + problem(ProblemCode::SessionNotFound, "no such session"), + FailedCheck::Visibility, + ) } } } @@ -869,9 +978,12 @@ fn response_unavailable(wait_seconds: u64) -> Response { async fn admit_response(limiter: &TokenBucketLimiter, key: &str) -> Result<(), Response> { match limiter.check(key, 1).await { Ok(()) => Ok(()), - Err(TokenBucketError::Exceeded { retry_after: wait }) => Err(retry_after( - oauth_error(StatusCode::TOO_MANY_REQUESTS, "temporarily_unavailable"), - wait.as_secs() + 1, + Err(TokenBucketError::Exceeded { retry_after: wait }) => Err(refused( + retry_after( + oauth_error(StatusCode::TOO_MANY_REQUESTS, "temporarily_unavailable"), + wait.as_secs() + 1, + ), + FailedCheck::RateLimit, )), Err(_) => Err(response_unavailable(CAPACITY_RETRY_SECONDS)), } @@ -1143,9 +1255,7 @@ async fn read_presentation( headers: HeaderMap, body: Bytes, ) -> Response { - let authorization = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()); + let authorization = authorization_header(&headers); let reader = match service .evidence_credentials .authenticate(authorization) @@ -1154,24 +1264,11 @@ async fn read_presentation( Ok(reader) => reader, Err(AuthError::KeySource) => { service.metrics.record(Event::ReadUnavailable); - return retry_after( - problem( - ProblemCode::IssuerUnavailable, - "the token issuer is unavailable", - ), - 5, - ); + return issuer_unavailable_answer(); } - Err(AuthError::Missing | AuthError::Refused) => { + Err(AuthError::Refused(check)) => { service.metrics.record(Event::ReadRefusedAuthentication); - let mut response = problem( - ProblemCode::Unauthorized, - "a valid bearer token is required", - ); - response - .headers_mut() - .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); - return response; + return refused_by(check, &service.evidence_credentials); } }; if let Err(response) = admit( @@ -1251,10 +1348,17 @@ async fn read_presentation( match verdict { // A principal that is not the creator reads exactly as an unknown // reference. - ReadVerdict::NotFound | ReadVerdict::PrincipalMismatch => { + ReadVerdict::NotFound => { service.metrics.record(Event::ReadNotFound); problem(ProblemCode::SessionNotFound, "no such session") } + ReadVerdict::PrincipalMismatch => { + service.metrics.record(Event::ReadNotFound); + refused( + problem(ProblemCode::SessionNotFound, "no such session"), + FailedCheck::Ownership, + ) + } ReadVerdict::Pending => { service.metrics.record(Event::ReadPending); problem( @@ -1331,19 +1435,22 @@ async fn admit( limiter: &TokenBucketLimiter, key: &str, metrics: &Metrics, - refused: Event, + event: Event, ) -> Result<(), Response> { match limiter.check(key, 1).await { Ok(()) => Ok(()), Err(TokenBucketError::Exceeded { retry_after: wait }) => { - metrics.record(refused); - Err(retry_after( - problem(ProblemCode::RateLimited, "too many requests; retry later"), - wait.as_secs() + 1, + metrics.record(event); + Err(refused( + retry_after( + problem(ProblemCode::RateLimited, "too many requests; retry later"), + wait.as_secs() + 1, + ), + FailedCheck::RateLimit, )) } Err(_) => { - metrics.record(refused); + metrics.record(event); Err(retry_after( problem(ProblemCode::Capacity, "the service is at capacity"), CAPACITY_RETRY_SECONDS, @@ -1439,3 +1546,37 @@ async fn wait_for_stop(mut stopped: watch::Receiver) { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_unauthorized_answer_carries_its_failed_check() { + let response = unauthorized(FailedCheck::CredentialMissing); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert!(response.extensions().get::().is_some()); + } + + #[test] + fn every_problem_code_answered_as_a_refusal_is_built_by_unauthorized() { + for &code in ProblemCode::ALL { + let status = problem_answer(code, "detail").status(); + assert_eq!( + is_refusal(status), + code == ProblemCode::Unauthorized, + "{code:?} answers {status}" + ); + } + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal is built with `unauthorized`")] + fn a_refusal_built_without_a_failed_check_is_caught() { + let _ = problem( + ProblemCode::Unauthorized, + "a valid bearer token is required", + ); + } +} diff --git a/crates/registry-evidence-oid4vp/tests/common/mod.rs b/crates/registry-evidence-oid4vp/tests/common/mod.rs index 2fa48c91ab..e07173a257 100644 --- a/crates/registry-evidence-oid4vp/tests/common/mod.rs +++ b/crates/registry-evidence-oid4vp/tests/common/mod.rs @@ -73,6 +73,12 @@ pub struct Options { pub wallet_response_burst: u32, pub response_burst_per_request: u32, pub evidence_read_burst: u32, + /// Serve the applicant-token key set from this static document instead of + /// the test issuer's key endpoint. + pub applicant_static_jwks: Option<&'static str>, + /// Fetch the applicant-token key set from this URI instead of the test + /// issuer's key endpoint. + pub applicant_jwks_uri: Option<&'static str>, } impl Default for Options { @@ -92,6 +98,8 @@ impl Default for Options { wallet_response_burst: 50, response_burst_per_request: 20, evidence_read_burst: 50, + applicant_static_jwks: None, + applicant_jwks_uri: None, } } } @@ -235,6 +243,18 @@ impl Harness { keys.registered_jwk.as_bytes(), ); write_secret(&secrets, "audit-hash-key", &[7u8; 48]); + let applicant_jwks_source = match options.applicant_static_jwks { + Some(document) => { + write_secret(&secrets, "applicant-jwks.json", document.as_bytes()); + "type: static\n documentRef: secret:file/applicant-jwks.json".to_owned() + } + None => format!( + "type: uri\n uri: {}", + options + .applicant_jwks_uri + .map_or_else(|| idp.jwks_uri().to_string(), str::to_owned) + ), + }; let audit_path = dir.path().join("audit.jsonl"); let authorities = if options.trusted_authorities { @@ -296,8 +316,7 @@ applicantTokens: audience: {AUDIENCE} allowInsecureHttp: true jwksSource: - type: uri - uri: {jwks} + {applicant_jwks_source} algorithms: [EdDSA] requiredScope: {SESSION_SCOPE} evidenceCredentials: diff --git a/crates/registry-evidence-oid4vp/tests/golden/refusals.json b/crates/registry-evidence-oid4vp/tests/golden/refusals.json new file mode 100644 index 0000000000..3a6eaeaee2 --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/golden/refusals.json @@ -0,0 +1,265 @@ +{ + "create-garbage-token": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-key-source-unavailable": { + "body": { + "detail": "the token issuer is unavailable", + "status": 503, + "title": "Service Unavailable", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/issuer-unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "5", + "x-content-type-options": "nosniff" + }, + "status": 503 + }, + "create-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-non-bearer-scheme": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "create-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "create-wrong-scope": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-another-principal": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "read-client-not-allowed": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-garbage-token": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "read-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "read-unknown-reference": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "read-wrong-scope": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "request-rate-limited": { + "body": { + "detail": "too many requests; retry later", + "status": 429, + "title": "Too Many Requests", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/rate-limited" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "response-rate-limited": { + "body": { + "error": "temporarily_unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/json", + "retry-after": "", + "x-content-type-options": "nosniff" + }, + "status": 429 + }, + "status-another-principal": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + }, + "status-no-header": { + "body": { + "detail": "a valid bearer token is required", + "status": 401, + "title": "Unauthorized", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer", + "x-content-type-options": "nosniff" + }, + "status": 401 + }, + "status-unknown-reference": { + "body": { + "detail": "no such session", + "status": 404, + "title": "Not Found", + "type": "https://id.registrystack.org/problems/registry-evidence-oid4vp/session-not-found" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "x-content-type-options": "nosniff" + }, + "status": 404 + } +} diff --git a/crates/registry-evidence-oid4vp/tests/refusal_golden.rs b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs new file mode 100644 index 0000000000..a5e274999a --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/refusal_golden.rs @@ -0,0 +1,282 @@ +//! The refusals a caller can provoke, answered through the whole router and +//! frozen in `tests/golden/refusals.json`. Each answer is its status, the +//! headers a caller or proxy acts on, and the body without its per-request +//! trace id. Run with `REGISTRY_OID4VP_WRITE_GOLDEN=1` to rewrite the file. + +mod common; + +use std::path::Path; + +use axum_test::{TestResponse, TestServer}; +use common::{bearer, Harness, Options}; +use serde_json::{json, Map, Value}; + +const HEADERS: [&str; 5] = [ + "content-type", + "www-authenticate", + "cache-control", + "retry-after", + "x-content-type-options", +]; + +/// The answer as the golden freezes it. A `retry-after` on a 429 is the +/// bucket's remaining wait, which moves with the clock, so only its presence +/// is frozen there. +fn frozen(response: &TestResponse) -> Value { + let status = response.status_code().as_u16(); + let mut headers = Map::new(); + for name in HEADERS { + if let Some(value) = response.maybe_header(name) { + let text = value.to_str().expect("ASCII header").to_owned(); + let text = if name == "retry-after" && status == 429 { + "".to_owned() + } else { + text + }; + headers.insert(name.to_owned(), text.into()); + } + } + let mut body: Value = serde_json::from_slice(response.as_bytes()).expect("a JSON body"); + if let Some(object) = body.as_object_mut() { + object.remove("traceId"); + } + json!({"status": status, "headers": headers, "body": body}) +} + +async fn create(server: &TestServer, authorization: Option<&str>) -> TestResponse { + let mut request = server.post("/v1/sessions"); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.json(&json!({"policy": "national-id"})).await +} + +async fn status_of( + server: &TestServer, + reference: &str, + authorization: Option<&str>, +) -> TestResponse { + let mut request = server.get(&format!("/v1/sessions/{reference}")); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request.await +} + +async fn read( + server: &TestServer, + authorization: Option<&str>, + reference: &str, + issuer: &str, + subject: &str, +) -> TestResponse { + let mut request = server.post("/v1/presentations/read"); + if let Some(value) = authorization { + request = request.add_header("authorization", value.to_owned()); + } + request + .json(&json!({ + "reference": reference, + "principal": {"issuer": issuer, "subject": subject}, + })) + .await +} + +/// Every refusal case, in a fixed order, answered by a fresh deployment where +/// the case needs a spent budget. +async fn answers() -> Value { + let mut answers = Map::new(); + let mut put = |name: &str, response: &TestResponse| { + answers.insert(name.to_owned(), frozen(response)); + }; + + let harness = Harness::new(&Options::default()).await; + let (server, _) = harness.server().await; + let issuer = harness.idp.issuer().to_string(); + let creator = harness.applicant_token("portal", "user-1"); + let created: Value = server + .post("/v1/sessions") + .add_header("authorization", bearer(&creator)) + .json(&json!({"policy": "national-id"})) + .await + .json(); + let reference = created["reference"].as_str().expect("reference").to_owned(); + + put("create-no-header", &create(&server, None).await); + put( + "create-non-bearer-scheme", + &create(&server, Some("Basic dXNlcjpwYXNz")).await, + ); + put( + "create-garbage-token", + &create(&server, Some("Bearer not-a-token")).await, + ); + let unscoped = harness.token("portal", "user-1", "something:else"); + put( + "create-wrong-scope", + &create(&server, Some(&bearer(&unscoped))).await, + ); + + put( + "status-no-header", + &status_of(&server, &reference, None).await, + ); + put( + "status-unknown-reference", + &status_of(&server, &"A".repeat(43), Some(&bearer(&creator))).await, + ); + let other = harness.applicant_token("portal", "user-2"); + put( + "status-another-principal", + &status_of(&server, &reference, Some(&bearer(&other))).await, + ); + + put( + "read-no-header", + &read(&server, None, &reference, &issuer, "user-1").await, + ); + put( + "read-garbage-token", + &read( + &server, + Some("Bearer not-a-token"), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let applicant_as_reader = harness.token("portal", "user-1", "oid4vp:read-result"); + put( + "read-client-not-allowed", + &read( + &server, + Some(&bearer(&applicant_as_reader)), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let reader_wrong_scope = harness.token("evidence", "evidence-service", "something:else"); + put( + "read-wrong-scope", + &read( + &server, + Some(&bearer(&reader_wrong_scope)), + &reference, + &issuer, + "user-1", + ) + .await, + ); + let reader = harness.evidence_token(); + put( + "read-another-principal", + &read( + &server, + Some(&bearer(&reader)), + &reference, + &issuer, + "user-2", + ) + .await, + ); + put( + "read-unknown-reference", + &read( + &server, + Some(&bearer(&reader)), + &"B".repeat(43), + &issuer, + "user-1", + ) + .await, + ); + + // Spent budgets, each in a deployment whose burst is one. + let limited = Harness::new(&Options { + session_creation_burst: 1, + wallet_request_burst: 1, + wallet_response_burst: 1, + evidence_read_burst: 1, + ..Options::default() + }) + .await; + let (server, _) = limited.server().await; + let token = limited.applicant_token("portal", "user-1"); + let first = create(&server, Some(&bearer(&token))).await; + assert_eq!(first.status_code().as_u16(), 201); + put( + "create-rate-limited", + &create(&server, Some(&bearer(&token))).await, + ); + let first = server.get("/v1/requests/unknown").await; + assert_eq!(first.status_code().as_u16(), 404); + put( + "request-rate-limited", + &server.get("/v1/requests/unknown").await, + ); + let issuer = limited.idp.issuer().to_string(); + let reader = limited.evidence_token(); + let first = read( + &server, + Some(&bearer(&reader)), + &"C".repeat(43), + &issuer, + "user-1", + ) + .await; + assert_eq!(first.status_code().as_u16(), 404); + put( + "read-rate-limited", + &read( + &server, + Some(&bearer(&reader)), + &"C".repeat(43), + &issuer, + "user-1", + ) + .await, + ); + let form = |server: &TestServer| { + server + .post("/v1/responses/unknown") + .content_type("application/x-www-form-urlencoded") + .text("response=x") + }; + let first = form(&server).await; + assert_eq!(first.status_code().as_u16(), 400); + put("response-rate-limited", &form(&server).await); + + let unreachable = Harness::new(&Options { + applicant_jwks_uri: Some("http://127.0.0.1:1/jwks"), + ..Options::default() + }) + .await; + let (down, _) = unreachable.server().await; + let down_token = unreachable.applicant_token("portal", "user-1"); + put( + "create-key-source-unavailable", + &create(&down, Some(&bearer(&down_token))).await, + ); + + Value::Object(answers) +} + +#[tokio::test] +async fn refusal_answers_match_the_golden() { + let actual = answers().await; + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + if std::env::var_os("REGISTRY_OID4VP_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + std::fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: Value = + serde_json::from_slice(&std::fs::read(&path).expect("golden file")).expect("golden json"); + assert_eq!(actual, expected); +} diff --git a/crates/registry-evidence-oid4vp/tests/refusal_recording.rs b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs new file mode 100644 index 0000000000..a19b576c2f --- /dev/null +++ b/crates/registry-evidence-oid4vp/tests/refusal_recording.rs @@ -0,0 +1,434 @@ +//! Every refusal the service answers is counted in +//! `evidence_oid4vp_request_refusals_total{check}` and written as one +//! `request refused` line that carries the check and no caller value. +//! +//! The log subscriber is process-wide (see `certificate_expiry_log.rs` for +//! why a thread-scoped one is not reliable), so this binary holds one test. + +mod common; + +use std::{ + future::IntoFuture, + sync::{Arc, Mutex}, +}; + +use axum_test::{TestResponse, TestServer}; +use common::{bearer, Harness, Options}; +use registry_evidence_oid4vp::service::VerifierService; +use registry_platform_authcommon::FailedCheck; +use serde_json::{json, Value}; + +#[derive(Clone, Default)] +struct LogBuffer(Arc>>); + +impl std::io::Write for LogBuffer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogBuffer { + type Writer = Self; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +impl LogBuffer { + fn text(&self) -> String { + String::from_utf8(self.0.lock().unwrap().clone()).unwrap() + } +} + +fn count(service: &VerifierService, check: FailedCheck) -> u64 { + service + .metrics() + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is declared") +} + +fn total(service: &VerifierService) -> u64 { + FailedCheck::ALL + .iter() + .map(|check| count(service, *check)) + .sum() +} + +/// What a caller sent that must never reach a log line. +struct Canaries(Vec); + +/// Run one request and require that exactly its member moved by one, that +/// one new log line names it, and that no canary reached the log. +async fn expect( + service: &VerifierService, + logs: &LogBuffer, + canaries: &Canaries, + check: FailedCheck, + status: u16, + request: impl std::future::Future, +) { + let (before, lines_before, total_before) = ( + count(service, check), + logs.text() + .matches(&format!("failed_check=\"{}\"", check.as_str())) + .count() + + logs + .text() + .matches(&format!("failed_check={}", check.as_str())) + .count(), + total(service), + ); + let response = request.await; + assert_eq!(response.status_code().as_u16(), status, "{check:?}"); + assert_eq!(count(service, check), before + 1, "{check:?}"); + assert_eq!( + total(service), + total_before + 1, + "{check:?} moved another member" + ); + let text = logs.text(); + let lines_after = text + .matches(&format!("failed_check=\"{}\"", check.as_str())) + .count() + + text + .matches(&format!("failed_check={}", check.as_str())) + .count(); + assert_eq!(lines_after, lines_before + 1, "{check:?}\n{text}"); + for canary in &canaries.0 { + assert!( + !text.contains(canary.as_str()), + "the log carries a caller value" + ); + } +} + +#[tokio::test] +async fn each_refusal_is_counted_and_logged_under_its_check() { + let logs = LogBuffer::default(); + tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_writer(logs.clone()) + .with_ansi(false) + .finish(), + ) + .expect("this binary installs one log subscriber"); + + let harness = Harness::new(&Options::default()).await; + let (server, service) = harness.server().await; + // Nothing is counted before a refusal, and every member is declared. + for check in FailedCheck::ALL { + assert_eq!(count(&service, check), 0); + } + let issuer = harness.idp.issuer().to_string(); + let creator = harness.applicant_token("portal", "user-1"); + let other = harness.applicant_token("portal", "user-2"); + let unscoped = harness.token("portal", "user-1", "something:else"); + let reader = harness.evidence_token(); + let applicant_as_reader = harness.token("portal", "user-1", "oid4vp:read-result"); + let reader_wrong_scope = harness.token("evidence", "evidence-service", "something:else"); + let canaries = Canaries(vec![ + creator.clone(), + other.clone(), + unscoped.clone(), + reader.clone(), + "user-1".to_owned(), + "user-2".to_owned(), + "portal".to_owned(), + "canary-token-7f3a".to_owned(), + ]); + let created: Value = server + .post("/v1/sessions") + .add_header("authorization", bearer(&creator)) + .json(&json!({"policy": "national-id"})) + .await + .json(); + let reference = created["reference"].as_str().unwrap().to_owned(); + + let create = |authorization: Option| { + let mut request = server.post("/v1/sessions"); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request.json(&json!({"policy": "national-id"})) + }; + let status = |reference: String, authorization: Option| { + let mut request = server.get(&format!("/v1/sessions/{reference}")); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request + }; + let read = |authorization: Option, reference: String, subject: &str| { + let mut request = server.post("/v1/presentations/read"); + if let Some(value) = authorization { + request = request.add_header("authorization", value); + } + request.json(&json!({ + "reference": reference, + "principal": {"issuer": issuer, "subject": subject}, + })) + }; + + let (s, l, c) = (&service, &logs, &canaries); + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + create(None).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + create(Some("Basic dXNlcjpwYXNz".to_owned())).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + create(Some("Bearer canary-token-7f3a".to_owned())).into_future(), + ) + .await; + // A credential the server cannot read as text was sent, so it is + // malformed rather than missing. + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + server + .post("/v1/sessions") + .add_header( + "authorization", + axum::http::HeaderValue::from_bytes(b"Bearer \x80\x81 canary-token-7f3a") + .expect("a byte above 0x7F is a legal header value"), + ) + .json(&json!({"policy": "national-id"})) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Scope, + 401, + create(Some(bearer(&unscoped))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + status(reference.clone(), None).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Visibility, + 404, + status("A".repeat(43), Some(bearer(&creator))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Visibility, + 404, + status(reference.clone(), Some(bearer(&other))).into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMissing, + 401, + read(None, reference.clone(), "user-1").into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + read( + Some("Bearer canary-token-7f3a".to_owned()), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::TokenClient, + 401, + read( + Some(bearer(&applicant_as_reader)), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Scope, + 401, + read( + Some(bearer(&reader_wrong_scope)), + reference.clone(), + "user-1", + ) + .into_future(), + ) + .await; + expect( + s, + l, + c, + FailedCheck::Ownership, + 404, + read(Some(bearer(&reader)), reference.clone(), "user-2").into_future(), + ) + .await; + + expect( + s, + l, + c, + FailedCheck::CredentialMalformed, + 401, + create(Some("Bearer canary-token-7f3a".to_owned())).into_future(), + ) + .await; + + // A read of a reference nobody holds is not recorded: the consult maps + // only another principal's session. + let before = total(&service); + let absent = read(Some(bearer(&reader)), "B".repeat(43), "user-1").await; + assert_eq!(absent.status_code().as_u16(), 404); + assert_eq!(total(&service), before); + + // An issuer key set that cannot be reached answers 503 and is counted. + let unreachable = Harness::new(&Options { + applicant_jwks_uri: Some("http://127.0.0.1:1/jwks"), + ..Options::default() + }) + .await; + let (down, down_service) = unreachable.server().await; + let down_token = unreachable.applicant_token("portal", "user-1"); + expect( + &down_service, + &logs, + &canaries, + FailedCheck::KeySourceUnavailable, + 503, + down.post("/v1/sessions") + .add_header("authorization", bearer(&down_token)) + .json(&json!({"policy": "national-id"})) + .into_future(), + ) + .await; + + // Spent budgets, each in a deployment whose burst is one. + let limited = Harness::new(&Options { + session_creation_burst: 1, + wallet_request_burst: 1, + wallet_response_burst: 1, + evidence_read_burst: 1, + ..Options::default() + }) + .await; + let (server, service) = limited.server().await; + let token = limited.applicant_token("portal", "user-1"); + let reader = limited.evidence_token(); + let issuer = limited.idp.issuer().to_string(); + let create = || { + server + .post("/v1/sessions") + .add_header("authorization", bearer(&token)) + .json(&json!({"policy": "national-id"})) + }; + let first = create().await; + assert_eq!(first.status_code().as_u16(), 201); + let (s, l) = (&service, &logs); + expect(s, l, c, FailedCheck::RateLimit, 429, create().into_future()).await; + server + .get("/v1/requests/unknown") + .await + .assert_status_not_found(); + expect( + s, + l, + c, + FailedCheck::RateLimit, + 429, + server.get("/v1/requests/unknown").into_future(), + ) + .await; + let read = || { + server + .post("/v1/presentations/read") + .add_header("authorization", bearer(&reader)) + .json(&json!({ + "reference": "C".repeat(43), + "principal": {"issuer": issuer, "subject": "user-1"}, + })) + }; + read().await.assert_status_not_found(); + expect(s, l, c, FailedCheck::RateLimit, 429, read().into_future()).await; + let form = |server: &TestServer| { + server + .post("/v1/responses/unknown") + .content_type("application/x-www-form-urlencoded") + .text("response=x") + }; + form(&server).await.assert_status_bad_request(); + expect( + s, + l, + c, + FailedCheck::RateLimit, + 429, + form(&server).into_future(), + ) + .await; + + // A scope refusal names the claim and the scopes the configuration + // declares for each gate, and none of the scopes the tokens held. + let text = logs.text(); + assert!(text.contains("scope_claim=\"scope\""), "{text}"); + assert!( + text.contains("required_scope=\"oid4vp:read-result\""), + "{text}" + ); + assert!(text.contains("required_scope=\"oid4vp:session\""), "{text}"); + assert!(!text.contains("something:else"), "{text}"); +} diff --git a/crates/registry-evidence-oid4vp/tests/startup.rs b/crates/registry-evidence-oid4vp/tests/startup.rs index b44faf7b09..7e21509d8c 100644 --- a/crates/registry-evidence-oid4vp/tests/startup.rs +++ b/crates/registry-evidence-oid4vp/tests/startup.rs @@ -559,3 +559,44 @@ async fn startup_code_for(harness: &Harness) -> String { .code .clone() } + +const PUBLIC_KEY_WITH_EXT: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","kid":"issuer-key","ext":true,"x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#; +const KEY_WITH_PRIVATE_MEMBER: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","kid":"issuer-key","d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}]}"#; + +#[tokio::test] +async fn a_static_key_set_with_an_ext_member_loads() { + let harness = Harness::new(&Options { + applicant_static_jwks: Some(PUBLIC_KEY_WITH_EXT), + ..Options::default() + }) + .await; + harness + .try_service() + .await + .expect("a public key with an ext member is a valid static key set"); +} + +#[tokio::test] +async fn a_static_key_set_with_a_private_member_is_refused_with_the_validator_text() { + let harness = Harness::new(&Options { + applicant_static_jwks: Some(KEY_WITH_PRIVATE_MEMBER), + ..Options::default() + }) + .await; + let error = harness + .try_service() + .await + .expect_err("a key set holding a private member is refused at startup"); + let diagnostic = error.diagnostic(); + assert_eq!(diagnostic.code, "evidence.oid4vp.issuer-unavailable"); + assert_eq!(diagnostic.path, "/applicantTokens"); + assert!( + diagnostic.message.contains("private-key member \"d\""), + "the startup message names the broken rule: {}", + diagnostic.message + ); + assert!( + !diagnostic.message.contains("jpsQnnGQmL"), + "the key material is never repeated" + ); +} diff --git a/crates/registry-evidence/Cargo.toml b/crates/registry-evidence/Cargo.toml index c020bd7e07..31e3c74917 100644 --- a/crates/registry-evidence/Cargo.toml +++ b/crates/registry-evidence/Cargo.toml @@ -50,11 +50,11 @@ registry-evidence-client.workspace = true registry-discovery-profile.workspace = true p256.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-crypto = { workspace = true, features = ["transit"] } registry-platform-config.workspace = true -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-metrics.workspace = true registry-platform-httputil.workspace = true registry-platform-oidc.workspace = true @@ -99,6 +99,7 @@ rcgen.workspace = true registry-evidence-authoring.workspace = true registry-evidence-presentation.workspace = true registry-platform-crypto = { workspace = true, features = ["test-support", "transit"] } +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } serde_norway.workspace = true tokio-rustls.workspace = true wiremock.workspace = true diff --git a/crates/registry-evidence/src/audit.rs b/crates/registry-evidence/src/audit.rs index 8b220188cd..55f914de27 100644 --- a/crates/registry-evidence/src/audit.rs +++ b/crates/registry-evidence/src/audit.rs @@ -12,7 +12,7 @@ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_audit::{ AuditDestination, AuditEntry, AuditError, AuditKeyHasher, AuditPhase as EntryPhase, AuditProfile, AuditSegments, AuditUnavailable, AuditWriter, AuthorizationAuditEvent, - AuthorizationOutcome, + AuthorizationOutcome, StoredAuditEntry, }; use registry_platform_crypto::canonicalize_json; use registry_platform_oidc::ActorKind; @@ -1260,7 +1260,7 @@ impl EvidenceAuditLog { key_version: u32, ) -> Result { let key_hasher = identifier_key_hasher(master_secret, key_version)?; - let writer = AuditWriter::open(destination).await?; + let writer = AuditWriter::open_without_posture(destination).await?; Ok(Self { writer, key_hasher, @@ -1269,7 +1269,7 @@ impl EvidenceAuditLog { } /// Wrap a writer that is already open, such as one built with - /// [`AuditWriter::from_line_sink`] to observe or refuse writes. + /// [`AuditWriter::from_line_sink_without_posture`] to observe or refuse writes. pub fn with_writer( writer: AuditWriter, master_secret: Vec, @@ -1580,18 +1580,6 @@ struct LocalPublicCheckOperationEvent { safe_error_category: Option, } -/// One stored line as the platform writer lays it out. -#[derive(Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct StoredAuditEntry { - schema: String, - event_id: String, - time: String, - phase: EntryPhase, - correlation: String, - record: serde_json::Value, -} - /// Largest stored line the local reader accepts, matching the writer's entry /// bound. const MAXIMUM_LOCAL_AUDIT_LINE_BYTES: u64 = 1024 * 1024; @@ -2356,8 +2344,7 @@ fn read_local_audit_file( if line.pop() != Some(b'\n') { return Err(invalid_audit_data()); } - let entry: StoredAuditEntry = - serde_json::from_slice(&line).map_err(|_| invalid_audit_data())?; + let entry = AuditSegments::parse_line(&line)?; collector.collect(entry)?; } } @@ -3621,7 +3608,7 @@ mod tests { fn captured_log() -> (EvidenceAuditLog, CapturedLines) { let captured = CapturedLines::default(); - let writer = AuditWriter::from_line_sink(Box::new(captured.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(captured.clone())); let log = EvidenceAuditLog::with_writer(writer, MASTER.to_vec(), 1).expect("audit key derives"); (log, captured) @@ -3642,7 +3629,7 @@ mod tests { /// Write entries exactly as given, bypassing the native record checks, so /// the local reader's own checks are what a test exercises. async fn append_raw_entries(path: &Path, entries: Vec) { - let writer = AuditWriter::open(file_destination(path)) + let writer = AuditWriter::open_without_posture(file_destination(path)) .await .expect("raw writer opens"); for entry in entries { @@ -3718,7 +3705,8 @@ mod tests { #[test] fn pseudonyms_keep_key_epochs_distinguishable() { let pseudonym = |master: &[u8], version: u32| { - let writer = AuditWriter::from_line_sink(Box::new(CapturedLines::default())); + let writer = + AuditWriter::from_line_sink_without_posture(Box::new(CapturedLines::default())); EvidenceAuditLog::with_writer(writer, master.to_vec(), version) .expect("audit key derives") .pseudonym("requester-v1", "urn:example:trust", b"principal-canary") @@ -3815,6 +3803,7 @@ mod tests { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" @@ -3833,7 +3822,7 @@ mod tests { #[tokio::test] async fn a_refused_write_stops_every_later_append() { - let writer = AuditWriter::from_line_sink(Box::new(RefusingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(RefusingSink)); let log = EvidenceAuditLog::with_writer(writer, MASTER.to_vec(), 1).expect("audit key derives"); assert!(matches!( @@ -3879,7 +3868,7 @@ mod tests { .expect("audit reads") .lines() .map(|line| { - let entry: StoredAuditEntry = serde_json::from_str(line).expect("entry parses"); + let entry = AuditSegments::parse_line(line.as_bytes()).expect("entry parses"); assert_eq!(entry.schema, AUDIT_SCHEMA); assert_eq!(entry.phase, EntryPhase::Request); entry.correlation diff --git a/crates/registry-evidence/src/auth.rs b/crates/registry-evidence/src/auth.rs index 6b0312db45..00a08eeed2 100644 --- a/crates/registry-evidence/src/auth.rs +++ b/crates/registry-evidence/src/auth.rs @@ -7,7 +7,7 @@ use std::{ #[cfg(test)] use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ actor_kind, grant_claims, ActorKind, Audience, ClaimError, ClaimNames, GrantClaims, @@ -76,6 +76,8 @@ pub struct Authenticator { /// Resource identifiers accepted by the verifier. A task grant must name /// the one member that actually matched the token audience. resources: Vec, + /// The claim the verifier reads scopes from, as the configuration names it. + scope_claim: String, key_source: Arc>, } @@ -118,6 +120,8 @@ pub struct AuthenticatedContext { pub enum TaskGrantError { #[error("task-grant claims are invalid")] Claims, + #[error("task grant has expired")] + Expired, #[error("task-grant principal does not match the authenticated principal")] PrincipalMismatch, #[error("task-grant client context is invalid")] @@ -234,23 +238,46 @@ impl std::fmt::Debug for AuthenticatedContext { } } +/// Why a bearer token was refused. Every variant names the check that failed, +/// so the operator-side count and log line can say which of the checks it was. +/// The caller sees one closed `401` whichever variant this is. #[derive(Debug, Error)] pub enum AuthenticationError { #[error("access token is malformed")] Malformed, #[error("access token verification failed")] - Verification, + Verification(FailedCheck), #[error("required authenticated context is missing or invalid")] - Context, + Context(FailedCheck), #[error("access token is bound to a sender proof this profile cannot validate")] SenderConstrained, } +impl AuthenticationError { + /// The check this refusal failed. Written to no response. + #[deny(clippy::wildcard_enum_match_arm)] + pub fn failed_check(&self) -> FailedCheck { + match self { + Self::Malformed => FailedCheck::CredentialMalformed, + Self::Verification(check) | Self::Context(check) => *check, + Self::SenderConstrained => FailedCheck::SenderConstraint, + } + } + + /// A required claim is absent or not in its configured shape. + fn claims() -> Self { + Self::Context(FailedCheck::TokenClaims) + } +} + /// RFC 7800 confirmation claim. Its presence means the authorization server /// issued a token that is only valid when presented with a matching proof of /// possession, such as DPoP or mutual TLS. const CONFIRMATION_CLAIM: &str = "cnf"; +/// The claim the platform verifier reads scopes from unless configured. +const DEFAULT_SCOPE_CLAIM: &str = "scope"; + impl Authenticator { /// Build the one strict resource-server profile from the loaded bundle. /// @@ -304,6 +331,7 @@ impl Authenticator { jwks_fetch_policy(config), issuer_roots, )); + let scope_claim = verifier_config.scope_claim.clone(); let verifier = Arc::new(TokenVerifier::new(verifier_config, fetcher)); let claims = AuthenticationClaimsConfig { principal_claim: config.principal_claim.clone(), @@ -313,6 +341,7 @@ impl Authenticator { actor_claim: config.actor_claim.clone(), }; Self::new(verifier, claims) + .with_scope_claim(scope_claim) .with_required_scopes(config.required_scopes.admitted()) .with_resources(vec![config.audience().to_owned()]) } @@ -323,6 +352,7 @@ impl Authenticator { claims, required_scopes: Vec::new(), resources: Vec::new(), + scope_claim: DEFAULT_SCOPE_CLAIM.to_owned(), key_source: Arc::new(Mutex::new(KeySourceState::default())), } } @@ -336,6 +366,24 @@ impl Authenticator { self } + /// Name the claim the verifier reads scopes from. The platform verifier + /// reads `scope` unless told otherwise. + #[must_use] + pub fn with_scope_claim(mut self, scope_claim: String) -> Self { + self.scope_claim = scope_claim; + self + } + + /// What a scope refusal may say about the deployment: the claim name and + /// the scopes the configuration requires. Both are configured values, so + /// the line they appear in carries nothing the caller's token held. + pub fn declared_scope(&self) -> Option { + (!self.required_scopes.is_empty()).then(|| { + DeclaredScope::new(&self.scope_claim) + .with_required_scope(self.required_scopes.join(" ")) + }) + } + #[must_use] pub fn with_resources(mut self, resources: Vec) -> Self { self.resources = resources; @@ -353,7 +401,7 @@ impl Authenticator { if is_key_source_failure(&error) { self.report_key_source_failure(&error); } - return Err(AuthenticationError::Verification); + return Err(AuthenticationError::Verification(error.failed_check())); } }; // The scope gate reads only the verified token's scope set. It runs @@ -371,7 +419,7 @@ impl Authenticator { .iter() .all(|scope| present.contains(scope.as_str())) { - return Err(AuthenticationError::Verification); + return Err(AuthenticationError::Verification(FailedCheck::Scope)); } } self.extract_context(verified) @@ -463,7 +511,7 @@ impl Authenticator { .jwks_uri() .unwrap_or(STATIC_KEY_SOURCE), cause = describe_causes(error), - "the access-token issuer key set could not be retrieved; every request is rejected until it can be" + "the access-token issuer key set could not be retrieved or used" ); } @@ -521,17 +569,21 @@ impl Authenticator { verified: VerifiedToken, ) -> Result { let actor_kind = actor_kind(&verified.claims, &self.claims.contextual_claims) - .map_err(|_| AuthenticationError::Context)?; + .map_err(|_| AuthenticationError::Context(FailedCheck::ActorKind))?; let now_unix = SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|_| AuthenticationError::Context)? + .map_err(|_| AuthenticationError::Context(FailedCheck::TokenTime))? .as_secs(); let mut task_grant = - grant_claims(&verified.claims, &self.claims.contextual_claims, now_unix) - .map_err(|_: ClaimError| TaskGrantError::Claims); + grant_claims(&verified.claims, &self.claims.contextual_claims, now_unix).map_err( + |error| match error { + ClaimError::Expired => TaskGrantError::Expired, + _ => TaskGrantError::Claims, + }, + ); let claims = - serde_json::to_value(&verified.claims).map_err(|_| AuthenticationError::Context)?; - let claims_object = claims.as_object().ok_or(AuthenticationError::Context)?; + serde_json::to_value(&verified.claims).map_err(|_| AuthenticationError::claims())?; + let claims_object = claims.as_object().ok_or_else(AuthenticationError::claims)?; // Retain a bounded identifier from the verified token for denial audit // even when expiry or another grant member fails validation. This is // never an authorization input and is emitted only as a keyed pseudonym. @@ -563,7 +615,7 @@ impl Authenticator { &self.claims.evidence_audience_claim, MAX_PRINCIPAL_BYTES, )?; - url::Url::parse(&evidence_audience).map_err(|_| AuthenticationError::Context)?; + url::Url::parse(&evidence_audience).map_err(|_| AuthenticationError::claims())?; let requester_tags = required_string_array(claims_object, &self.claims.requester_tags_claim, MAX_TAGS)?; let actor = self @@ -579,7 +631,9 @@ impl Authenticator { } else { match exactly_matched_resource(verified.claims.aud.as_ref(), &self.resources) { Some(resource) => { - if let Err(error) = grant.verify_context(&verified, resource) { + if let Err(error) = + grant.verify_context_without_peer_policy(&verified, resource) + { task_grant = Err(match error { GrantContextError::MissingVerifiedClient | GrantContextError::InvalidVerifiedClient @@ -646,41 +700,10 @@ fn jwks_fetch_policy(config: &OidcAuthenticationConfig) -> FetchUrlPolicy { } /// Whether a verification failure was this deployment's key source rather than -/// the caller's token. -/// -/// Every known failure is listed rather than folded into the wildcard, which -/// covers only variants added to the shared verifier after this was written. -/// Those default to the caller's side: a failure this code has never seen is -/// one it cannot honestly describe as an unreachable key set, and an operator -/// misdirected by a confident wrong message is worse off than one who reads -/// the same `auth.invalid-credential` twice. +/// the caller's token. The shared verifier owns the classification, so the +/// operator log line and the `key-source-unavailable` count agree. fn is_key_source_failure(error: &OidcError) -> bool { - match error { - OidcError::Transport(_) - | OidcError::BoundedRead(_) - | OidcError::FetchUrl(_) - | OidcError::HttpStatus(_) - | OidcError::InvalidUrl - | OidcError::Parse - | OidcError::InvalidJwk - | OidcError::EmptyKeySet - | OidcError::MissingIssuer => true, - OidcError::IssuerMismatch { .. } - | OidcError::MalformedToken - | OidcError::AlgorithmNotAllowed - | OidcError::TokenTypeNotAllowed - | OidcError::MissingKid - | OidcError::KidTooLong - | OidcError::UnknownKid - | OidcError::TokenExpired - | OidcError::TokenNotYetValid - | OidcError::AudienceMismatch - | OidcError::SignatureInvalid - | OidcError::InvalidToken - | OidcError::ClientNotAllowed - | OidcError::AssertionIssuerNotAllowed => false, - _ => false, - } + error.is_key_source_unavailable() } /// Render an error together with the causes beneath it, bounded. @@ -719,7 +742,7 @@ fn required_direct_string( name: &str, maximum_bytes: usize, ) -> Result { - optional_direct_string(claims, name, maximum_bytes)?.ok_or(AuthenticationError::Context) + optional_direct_string(claims, name, maximum_bytes)?.ok_or_else(AuthenticationError::claims) } fn optional_direct_string( @@ -730,9 +753,9 @@ fn optional_direct_string( let Some(value) = claims.get(name) else { return Ok(None); }; - let value = value.as_str().ok_or(AuthenticationError::Context)?; + let value = value.as_str().ok_or_else(AuthenticationError::claims)?; if value.is_empty() || value.len() > maximum_bytes { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } Ok(Some(value.to_owned())) } @@ -745,15 +768,15 @@ fn required_string_array( let values = claims .get(name) .and_then(Value::as_array) - .ok_or(AuthenticationError::Context)?; + .ok_or_else(AuthenticationError::claims)?; if values.is_empty() || values.len() > maximum_items { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } let mut output = Vec::with_capacity(values.len()); for value in values { - let value = value.as_str().ok_or(AuthenticationError::Context)?; + let value = value.as_str().ok_or_else(AuthenticationError::claims)?; if value.is_empty() || value.len() > MAX_PRINCIPAL_BYTES { - return Err(AuthenticationError::Context); + return Err(AuthenticationError::claims()); } output.push(value.to_owned()); } @@ -1195,6 +1218,44 @@ mod tests { assert_eq!(context.grant(), Err(TaskGrantError::PrincipalMismatch)); } + #[test] + fn an_expired_task_grant_is_kept_apart_from_a_malformed_one() { + let now = chrono::Utc::now().timestamp(); + let claims = |grant_exp: i64| { + serde_json::from_value(serde_json::json!({ + "iss": "https://issuer.invalid", + "aud": "evidence-resource", + "sub": "institutional-agent", + "exp": now + 300, + "registry_actor_kind": "agent", + "registry_purpose": "eligibility-check", + "registry_grant_id": "grant-1", + "registry_grant_source_issuer": "https://casework.invalid", + "registry_grant_client": "evidence-agent", + "registry_grant_resource": "evidence-resource", + "registry_grant_exp": grant_exp, + "registry_grant_bounds": {"type":"evidence", "requirement":"urn:example:requirement"}, + "registry_approver": "h:synthetic-approver", + "evidence_tags": ["caseworker"], + "evidence_audience": "https://relying-party.invalid" + })) + .expect("claims parse") + }; + let grant_of = |claims| { + context_extraction_authenticator("sub") + .extract_context(VerifiedToken { + claims, + matched_client: Some("client_id:evidence-agent".to_owned()), + scopes: Vec::new(), + }) + .expect("verified product context extracts") + .grant() + .map(|grant| grant.is_some()) + }; + assert_eq!(grant_of(claims(now - 1)), Err(TaskGrantError::Expired)); + assert_eq!(grant_of(claims(now + 300)), Ok(true)); + } + #[test] fn token_without_actor_kind_is_refused_during_context_extraction() { let now = chrono::Utc::now().timestamp(); @@ -1217,7 +1278,10 @@ mod tests { }) .expect_err("a token without registry_actor_kind is refused"); - assert!(matches!(error, AuthenticationError::Context)); + assert!(matches!( + error, + AuthenticationError::Context(FailedCheck::ActorKind) + )); } #[test] diff --git a/crates/registry-evidence/src/authority.rs b/crates/registry-evidence/src/authority.rs index eeecd4bf0f..f5ebf703a8 100644 --- a/crates/registry-evidence/src/authority.rs +++ b/crates/registry-evidence/src/authority.rs @@ -1080,7 +1080,9 @@ mod tests { accepted, }; let log = EvidenceAuditLog::with_writer( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(sink.clone())), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + )), b"activation-audit-key-canary-32-bytes".to_vec(), 1, ) diff --git a/crates/registry-evidence/src/config.rs b/crates/registry-evidence/src/config.rs index 26393c7a7a..42d3803970 100644 --- a/crates/registry-evidence/src/config.rs +++ b/crates/registry-evidence/src/config.rs @@ -2545,7 +2545,7 @@ impl RuntimeConfig { /// The shared loader configured with the Evidence envelope and the keys /// it no longer accepts. pub fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(EVIDENCE_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(EVIDENCE_RUNTIME_ENVELOPE) .removed_keys(EVIDENCE_RUNTIME_REMOVED_KEYS) .retired_api_versions(EVIDENCE_RETIRED_RUNTIME_API_VERSIONS) } @@ -3524,7 +3524,7 @@ impl OidcAuthenticationConfig { } } self.provider - .check( + .check_without_posture( "authentication.oidc", assurance_profile == AssuranceProfile::Local, ) diff --git a/crates/registry-evidence/src/observability.rs b/crates/registry-evidence/src/observability.rs index 38ccbb7576..e0e88d26f9 100644 --- a/crates/registry-evidence/src/observability.rs +++ b/crates/registry-evidence/src/observability.rs @@ -24,6 +24,10 @@ //! drifted from the declared projection and emits rate-limited operator WARN //! records that name the source, declared JSON pointers, and closed reasons, //! never a response value, an undeclared member name, a selector, or a subject. +//! +//! The refusal counter is the second exception. Its `check` label is the +//! closed [`FailedCheck`](registry_platform_authcommon::FailedCheck) set, fixed +//! and zero-filled at construction, so no request can extend it. use std::{ collections::BTreeMap, @@ -44,6 +48,7 @@ use axum::{ routing::get, Router, }; +use registry_platform_authcommon::{record_refusal, DeclaredScope, RefusalNote, RefusalRecorder}; use registry_platform_httpsec::{TraceContext, TraceId}; use registry_platform_metrics::{ Exposition, HistogramSnapshot, MetricKind, SumCountOrder, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -153,6 +158,25 @@ pub(crate) fn operation_id(extensions: &axum::http::Extensions) -> OperationId { ) } +/// Whether a public problem code is a refusal the check counter covers: the +/// authentication, authorization and rate-limit answers. +#[deny(clippy::wildcard_enum_match_arm)] +pub(crate) fn is_refusal_code(code: ProblemCode) -> bool { + match code { + ProblemCode::AuthenticationFailed + | ProblemCode::NotAuthorized + | ProblemCode::RateLimited => true, + ProblemCode::MalformedRequest + | ProblemCode::InvalidRequestNonce + | ProblemCode::InvalidSelector + | ProblemCode::ResponseFormatNotAcceptable + | ProblemCode::EvidenceNotAvailable + | ProblemCode::DependencyUnavailable + | ProblemCode::ServiceUnavailable + | ProblemCode::ResourceNotFound => false, + } +} + /// Coarse outcome class. Operational records report the class, never the exact /// status, because the exact status of a denial is part of the closed public /// problem contract rather than an operational signal. @@ -212,6 +236,7 @@ pub(crate) async fn observe( .get::() .map_or(NO_CATEGORY, |category| category.0); operation.apply_trace(response.headers_mut()); + record_response_refusal(&metrics, &response, &operation); metrics.record(route, method, status, error, elapsed); tracing::info!( @@ -228,6 +253,39 @@ pub(crate) async fn observe( response } +/// Count and log the refusal a response carries, once, at the single point +/// every route passes. +/// +/// The note is in the response extensions, which are not serialized, so this +/// reads nothing a caller was given. A refusal code that arrives without a note +/// is a defect in the code that built it: it is reported, not counted under a +/// check it never named. +fn record_response_refusal(metrics: &Metrics, response: &Response, operation: &OperationId) { + match response.extensions().get::() { + Some(note) => { + record_refusal!( + metrics.refusals, + *note, + trace_id = operation.trace_id(), + declared = metrics.declared_scope.as_ref() + ); + } + None => { + if response + .extensions() + .get::() + .is_some_and(|code| is_refusal_code(*code)) + { + tracing::error!( + target: module_path!(), + trace_id = operation.trace_id().as_str(), + "a refusal was answered without the check that failed" + ); + } + } + } +} + /// Choose the W3C trace for one request. /// /// Every route continues a valid inbound `traceparent` except the public @@ -280,7 +338,6 @@ fn duration_milliseconds(elapsed: Duration) -> u64 { /// /// Series are keyed only by the closed label set above, so the registry is /// bounded by the route table regardless of traffic and needs no eviction. -#[derive(Default)] pub(crate) struct Metrics { series: Mutex>, /// Current count of pseudonym keys tracked by the rate limiter, for the @@ -297,6 +354,24 @@ pub(crate) struct Metrics { /// The per-source counters the runtime's source executors increment. /// `None` for registries built without a runtime. source_diagnostics: Option>, + /// Counts refusals by the check that failed and bounds the log lines they + /// write. Keyed by no request value. + refusals: RefusalRecorder, + /// The configured values a scope refusal's log line names. + declared_scope: Option, +} + +impl Default for Metrics { + fn default() -> Self { + Self { + series: Mutex::default(), + rate_limiter_tracked_keys: AtomicUsize::default(), + rate_limiter: None, + source_diagnostics: None, + refusals: RefusalRecorder::new("evidence").expect(DECLARATION), + declared_scope: None, + } + } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] @@ -339,6 +414,12 @@ impl Metrics { } } + /// Name the configured values a scope refusal's log line carries. + pub(crate) fn with_declared_scope(mut self, declared_scope: Option) -> Self { + self.declared_scope = declared_scope; + self + } + fn record( &self, route: &'static str, @@ -426,6 +507,7 @@ impl Metrics { self.rate_limiter_tracked_keys.load(Ordering::Relaxed), ) .expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); if let Some(source_diagnostics) = &self.source_diagnostics { source_diagnostics.render(&mut out); } diff --git a/crates/registry-evidence/src/observability/golden-scrape.txt b/crates/registry-evidence/src/observability/golden-scrape.txt index 298e7270f0..89d3c341d6 100644 --- a/crates/registry-evidence/src/observability/golden-scrape.txt +++ b/crates/registry-evidence/src/observability/golden-scrape.txt @@ -70,6 +70,53 @@ evidence_http_request_duration_seconds_count{route="unmatched",method="other",st # HELP evidence_rate_limiter_tracked_keys Pseudonym keys currently tracked by the rate limiter. # TYPE evidence_rate_limiter_tracked_keys gauge evidence_rate_limiter_tracked_keys 5 +# HELP evidence_request_refusals_total Requests refused, by the check that failed. +# TYPE evidence_request_refusals_total counter +evidence_request_refusals_total{check="credential-missing"} 0 +evidence_request_refusals_total{check="credential-malformed"} 0 +evidence_request_refusals_total{check="token-algorithm"} 0 +evidence_request_refusals_total{check="token-type"} 0 +evidence_request_refusals_total{check="token-key"} 0 +evidence_request_refusals_total{check="token-signature"} 0 +evidence_request_refusals_total{check="token-issuer"} 0 +evidence_request_refusals_total{check="token-audience"} 0 +evidence_request_refusals_total{check="token-time"} 0 +evidence_request_refusals_total{check="token-client"} 0 +evidence_request_refusals_total{check="token-assertion-issuer"} 0 +evidence_request_refusals_total{check="token-claims"} 0 +evidence_request_refusals_total{check="actor-kind"} 0 +evidence_request_refusals_total{check="delegation"} 0 +evidence_request_refusals_total{check="sender-constraint"} 0 +evidence_request_refusals_total{check="key-source-unavailable"} 0 +evidence_request_refusals_total{check="shared-secret"} 0 +evidence_request_refusals_total{check="one-time-credential"} 0 +evidence_request_refusals_total{check="delivery-signature"} 0 +evidence_request_refusals_total{check="delivery-freshness"} 0 +evidence_request_refusals_total{check="delivery-binding"} 0 +evidence_request_refusals_total{check="host-origin"} 0 +evidence_request_refusals_total{check="scope"} 0 +evidence_request_refusals_total{check="access-profile"} 0 +evidence_request_refusals_total{check="requester-client"} 0 +evidence_request_refusals_total{check="purpose"} 0 +evidence_request_refusals_total{check="operation"} 0 +evidence_request_refusals_total{check="disclosure"} 0 +evidence_request_refusals_total{check="subject-selector"} 0 +evidence_request_refusals_total{check="revision-pin"} 0 +evidence_request_refusals_total{check="acquisition-channel"} 0 +evidence_request_refusals_total{check="source-authority"} 0 +evidence_request_refusals_total{check="separation-of-duties"} 0 +evidence_request_refusals_total{check="task-grant-missing"} 0 +evidence_request_refusals_total{check="task-grant-claims"} 0 +evidence_request_refusals_total{check="task-grant-expired"} 0 +evidence_request_refusals_total{check="task-grant-binding"} 0 +evidence_request_refusals_total{check="task-grant-scope"} 0 +evidence_request_refusals_total{check="task-grant-lifetime"} 0 +evidence_request_refusals_total{check="task-grant-status"} 0 +evidence_request_refusals_total{check="row-boundary"} 0 +evidence_request_refusals_total{check="ownership"} 0 +evidence_request_refusals_total{check="visibility"} 0 +evidence_request_refusals_total{check="action-guard"} 0 +evidence_request_refusals_total{check="rate-limit"} 0 # HELP evidence_build_info Running version and captured governed identities. # TYPE evidence_build_info gauge evidence_build_info{version="{VERSION}",bundle="bundle\"x\\y\nz",authority="package"} 1 diff --git a/crates/registry-evidence/src/refusal_recording_tests.rs b/crates/registry-evidence/src/refusal_recording_tests.rs new file mode 100644 index 0000000000..6acf2b010e --- /dev/null +++ b/crates/registry-evidence/src/refusal_recording_tests.rs @@ -0,0 +1,587 @@ +//! Every refusal the Evidence boundary answers with 401, 403 or 429 is counted +//! under the check that failed, logged once with that check, and answered with +//! the bytes it has always had. +//! +//! The golden file holds each answer's status, headers and body (minus the +//! per-request trace id). It was written from the tree before the check was +//! threaded through, so a pass proves no refusal answer changed. +//! `REGISTRY_EVIDENCE_WRITE_GOLDEN=1` rewrites it. + +use super::*; +use registry_platform_authcommon::FailedCheck; + +const GOLDEN: &str = "tests/golden/refusal_answers.json"; +const TOKEN_CANARY: &str = "refusal-token-canary-value"; +const CLIENT_CANARY: &str = "refusal-client-canary-value"; + +/// What the request carries besides its route. +enum Credential { + Absent, + Header(&'static str), + Repeated, + Token(String), +} + +struct Scenario { + name: &'static str, + method: &'static str, + route: &'static str, + credential: Credential, + accept: Option<&'static str>, + body: Option, + status: StatusCode, + check: FailedCheck, +} + +fn evidence( + name: &'static str, + credential: Credential, + body: EvidenceRequest, + status: StatusCode, + check: FailedCheck, +) -> Scenario { + Scenario { + name, + method: "POST", + route: "/v1/evidence", + credential, + accept: None, + body: Some(body), + status, + check, + } +} + +fn claims_without(removed: &[&str], replaced: Value) -> Value { + let now = Utc::now().timestamp(); + let mut claims = json!({ + "iss": TOKEN_ISSUER, + "aud": TOKEN_AUDIENCE, + "sub": "requester-principal-canary", + "iat": now - 1, + "exp": now + 298, + "client_id": "evidence-task-agent", + "registry_actor_kind": "service", + "evidence_tags": ["fixture-agency"], + "evidence_audience": EVIDENCE_AUDIENCE + }); + let object = claims.as_object_mut().expect("claims are an object"); + for name in removed { + object.remove(*name); + } + object.extend( + replaced + .as_object() + .expect("replacements are an object") + .clone(), + ); + claims +} + +/// A well-formed token whose signature segment is not the signature of its +/// payload. +fn token_with_tampered_signature() -> String { + let token = access_token(None); + let (signing_input, _) = token.rsplit_once('.').expect("a compact token"); + format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode([0u8; 64])) +} + +/// A token whose header names a key the verifier does not hold. +fn token_with_unknown_key() -> String { + let token = access_token(None); + let mut segments = token.split('.'); + let _ = segments.next(); + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg": "ES256", "kid": "unknown-key", "typ": "at+jwt"})) + .expect("header serializes"), + ); + format!( + "{header}.{}.{}", + segments.next().expect("payload"), + segments.next().expect("signature") + ) +} + +fn scenarios() -> Vec { + let now = Utc::now().timestamp(); + let adult = adult_request; + let mut wrong_purpose = adult_request(); + wrong_purpose.purpose = "no-such-purpose".to_owned(); + let mut unknown_profile = adult_request(); + unknown_profile.subjects[0].selector.profile = "no-such-profile".to_owned(); + let mut pinned = adult_request(); + pinned.expected_configuration_revision = Some(format!("sha256:{}", "0".repeat(64))); + let unauthorized = StatusCode::UNAUTHORIZED; + let forbidden = StatusCode::FORBIDDEN; + vec![ + evidence( + "no-authorization-header", + Credential::Absent, + adult(), + unauthorized, + FailedCheck::CredentialMissing, + ), + evidence( + "non-bearer-scheme", + Credential::Header("Basic abc"), + adult(), + unauthorized, + FailedCheck::CredentialMissing, + ), + evidence( + "repeated-authorization-header", + Credential::Repeated, + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "double-space-separator", + Credential::Header("Bearer abc"), + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "not-a-compact-token", + Credential::Header("Bearer refusal-token-canary-value"), + adult(), + unauthorized, + FailedCheck::CredentialMalformed, + ), + evidence( + "wrong-issuer", + Credential::Token(access_token_for_issuer( + "https://other.invalid", + "requester-principal-canary", + None, + )), + adult(), + unauthorized, + FailedCheck::TokenIssuer, + ), + evidence( + "expired-token", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"iat": now - 900, "exp": now - 600}), + ))), + adult(), + unauthorized, + FailedCheck::TokenTime, + ), + evidence( + "wrong-audience", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"aud": "https://other.invalid/audience"}), + ))), + adult(), + unauthorized, + FailedCheck::TokenAudience, + ), + evidence( + "unknown-key", + Credential::Token(token_with_unknown_key()), + adult(), + unauthorized, + FailedCheck::TokenKey, + ), + evidence( + "tampered-signature", + Credential::Token(token_with_tampered_signature()), + adult(), + unauthorized, + FailedCheck::TokenSignature, + ), + evidence( + "client-not-admitted", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"client_id": CLIENT_CANARY}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClient, + ), + evidence( + "sender-constrained-token", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"cnf": {"jkt": "thumbprint"}}), + ))), + adult(), + unauthorized, + FailedCheck::SenderConstraint, + ), + evidence( + "unknown-actor-kind", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"registry_actor_kind": "not-a-kind"}), + ))), + adult(), + unauthorized, + FailedCheck::ActorKind, + ), + evidence( + "evidence-audience-claim-is-not-a-url", + Credential::Token(signed_access_token(claims_without( + &[], + json!({"evidence_audience": "not a url"}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClaims, + ), + evidence( + "requester-tags-claim-absent", + Credential::Token(signed_access_token(claims_without( + &["evidence_tags"], + json!({}), + ))), + adult(), + unauthorized, + FailedCheck::TokenClaims, + ), + evidence( + "expired-task-grant", + Credential::Token(access_token(Some({ + let mut grant = parent_grant_claims(); + grant["registry_grant_exp"] = json!(now - 1); + grant + }))), + adult(), + forbidden, + FailedCheck::TaskGrantExpired, + ), + Scenario { + name: "batch-without-credential", + method: "POST", + route: "/v1/evidence/batch", + credential: Credential::Absent, + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::CredentialMissing, + }, + Scenario { + name: "discovery-without-credential", + method: "GET", + route: "/v1/evidence-definitions", + credential: Credential::Absent, + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::CredentialMissing, + }, + Scenario { + name: "discovery-with-wrong-issuer", + method: "GET", + route: "/v1/evidence-definitions", + credential: Credential::Token(access_token_for_issuer( + "https://other.invalid", + "requester-principal-canary", + None, + )), + accept: None, + body: None, + status: unauthorized, + check: FailedCheck::TokenIssuer, + }, + evidence( + "no-entitlement-for-the-requester", + Credential::Token(access_token(Some( + json!({"evidence_tags": ["unmatched-agency"]}), + ))), + adult(), + forbidden, + FailedCheck::AccessProfile, + ), + evidence( + "purpose-not-permitted", + Credential::Token(access_token(None)), + wrong_purpose, + forbidden, + FailedCheck::Purpose, + ), + evidence( + "selector-profile-not-granted", + Credential::Token(access_token(None)), + unknown_profile, + forbidden, + FailedCheck::SubjectSelector, + ), + evidence( + "revision-pin-mismatch", + Credential::Token(access_token(None)), + pinned, + forbidden, + FailedCheck::RevisionPin, + ), + Scenario { + name: "response-format-not-permitted", + method: "POST", + route: "/v1/evidence", + credential: Credential::Token(access_token(None)), + accept: Some(EVIDENCE_SD_JWT_VC_MEDIA_TYPE), + body: Some(adult_request()), + status: forbidden, + check: FailedCheck::Disclosure, + }, + ] +} + +fn build_request(scenario: &Scenario) -> HttpRequest { + let mut builder = HttpRequest::builder() + .method(scenario.method) + .uri(scenario.route) + .header("content-type", "application/json"); + match &scenario.credential { + Credential::Absent => {} + Credential::Header(value) => builder = builder.header("authorization", *value), + Credential::Repeated => { + builder = builder + .header("authorization", "Bearer first.second.third") + .header("authorization", "Bearer first.second.third"); + } + Credential::Token(token) => { + builder = builder.header("authorization", format!("Bearer {token}")); + } + } + if let Some(accept) = scenario.accept { + builder = builder.header("accept", accept); + } + let body = scenario.body.as_ref().map_or_else(Body::empty, |body| { + Body::from(serde_json::to_vec(body).expect("the request serializes")) + }); + builder.body(body).expect("the request builds") +} + +/// The family line of `evidence_request_refusals_total` for one check, or zero +/// when the exposition carries no such series. +fn counted(exposition: &str, check: FailedCheck) -> u64 { + let prefix = format!( + "evidence_request_refusals_total{{check=\"{}\"}} ", + check.as_str() + ); + exposition + .lines() + .find_map(|line| line.strip_prefix(&prefix)) + .map_or(0, |value| value.parse().expect("a counter value")) +} + +struct Observed { + answer: Value, + exposition: String, +} + +/// Serve one scenario on a fresh runtime, so its counter and log budget are its +/// own, and return what the caller received and what the registry then held. +async fn serve(scenario: &Scenario) -> Observed { + let fixture = acceptance_runtime().await; + let (app, metrics) = build_app_with_metrics(Arc::clone(&fixture.runtime)); + let response = app + .oneshot(build_request(scenario)) + .await + .expect("the router answers"); + let status = response.status(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("ASCII header").to_owned()) + }; + let headers = json!({ + "content-type": header("content-type"), + "www-authenticate": header("www-authenticate"), + "retry-after": header("retry-after"), + "cache-control": header("cache-control"), + "vary": header("vary"), + }); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("the body reads"); + let mut body: Value = serde_json::from_slice(&bytes).expect("a problem body"); + body.as_object_mut() + .expect("a problem object") + .insert("traceId".to_owned(), json!("")); + Observed { + answer: json!({"status": status.as_u16(), "headers": headers, "body": body}), + exposition: metrics.render(), + } +} + +fn golden_path() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join(GOLDEN) +} + +#[test] +fn every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before() { + let scenarios = scenarios(); + let mut answers = serde_json::Map::new(); + let mut failures = Vec::new(); + for scenario in &scenarios { + let slot: Arc>> = Arc::new(Mutex::new(None)); + let sink = Arc::clone(&slot); + let emitted = capture_evidence_logs(|| async { + *sink.lock().expect("observation slot") = Some(serve(scenario).await); + }); + let observed = slot + .lock() + .expect("observation slot") + .take() + .expect("the scenario ran"); + answers.insert(scenario.name.to_owned(), observed.answer.clone()); + + if observed.answer["status"] != json!(scenario.status.as_u16()) { + failures.push(format!( + "{}: status {} where {} was expected", + scenario.name, observed.answer["status"], scenario.status + )); + continue; + } + let count = counted(&observed.exposition, scenario.check); + if count != 1 { + failures.push(format!( + "{}: the {} series counted {count}, expected 1", + scenario.name, + scenario.check.as_str() + )); + } + for other in FailedCheck::ALL { + if other != scenario.check && counted(&observed.exposition, other) != 0 { + failures.push(format!( + "{}: {} was counted as well", + scenario.name, + other.as_str() + )); + } + } + let refused: Vec<&Value> = emitted + .iter() + .filter(|record| record["fields"]["decision"] == json!("refused")) + .collect(); + if refused.len() != 1 + || refused[0]["fields"]["failed_check"] != json!(scenario.check.as_str()) + { + failures.push(format!( + "{}: expected one refused line for {}, saw {refused:?}", + scenario.name, + scenario.check.as_str() + )); + } + let raw = serde_json::to_string(&emitted).expect("captured records serialize"); + for canary in [TOKEN_CANARY, CLIENT_CANARY, "requester-principal-canary"] { + if raw.contains(canary) { + failures.push(format!("{}: a log line carried {canary}", scenario.name)); + } + } + } + + let answers = Value::Object(answers); + if std::env::var_os("REGISTRY_EVIDENCE_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("the golden serializes"); + text.push('\n'); + fs::write(golden_path(), text).expect("the golden is written"); + } else { + let golden: Value = serde_json::from_str( + &fs::read_to_string(golden_path()).expect("the golden file is readable"), + ) + .expect("the golden parses"); + assert_eq!(answers, golden, "a refusal answer changed"); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// A request over the per-principal budget is a `429` counted under +/// `rate-limit`, with its `Retry-After` unchanged. +#[tokio::test] +async fn a_request_over_the_rate_budget_is_counted_under_rate_limit() { + let prepared = prepare_acceptance("subject-binding-secret-canary-32-bytes-minimum").await; + make_writable(&prepared.bundle_root); + let configuration_path = prepared.bundle_root.join("evidence.yaml"); + mutate_acceptance_configuration(&configuration_path, |configuration| { + configuration["rateLimits"]["requestsPerPrincipalPerMinute"] = json!(1); + configuration["rateLimits"]["burstPerPrincipal"] = json!(1); + }); + refresh_package_envelope(&prepared.bundle_root); + make_read_only(&prepared.bundle_root); + let runtime = Arc::new( + EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator()) + .await + .expect("rate-limited runtime initializes"), + ); + let (app, metrics) = build_app_with_metrics(runtime); + let http = TestServer::new(app); + let token = access_token(None); + + http.get("/v1/evidence-definitions") + .add_header("authorization", format!("Bearer {token}")) + .await + .assert_status_ok(); + assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 0); + let limited = http + .get("/v1/evidence-definitions") + .add_header("authorization", format!("Bearer {token}")) + .await; + assert_eq!(limited.status_code(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(limited.header("retry-after"), "1"); + assert_eq!(limited.header("content-type"), "application/problem+json"); + assert_eq!(limited.header("cache-control"), "no-store"); + let body: Value = limited.json(); + assert_eq!(body["status"], json!(429)); + assert_eq!(body["code"], json!("evidence.rate-limited")); + assert_eq!(body["title"], json!("Evidence request rate is exhausted")); + assert_eq!( + body["detail"], + json!("the Evidence request rate is exhausted") + ); + assert_eq!(counted(&metrics.render(), FailedCheck::RateLimit), 1); +} + +/// A scope refusal names the claim and the scopes the configuration declares. +/// Nothing the token carried reaches the line, whatever scopes it held. +#[test] +fn a_scope_refusal_logs_the_declared_values_and_none_of_the_tokens() { + const SCOPE_CANARY: &str = "scope-canary-held-by-the-token"; + let scenario = evidence( + "token-lacks-the-required-scope", + Credential::Token(access_token(Some(json!({"scope": SCOPE_CANARY})))), + adult_request(), + StatusCode::UNAUTHORIZED, + FailedCheck::Scope, + ); + let answered: Arc>> = Arc::new(Mutex::new(None)); + let sink = Arc::clone(&answered); + let emitted = capture_evidence_logs(|| async { + let fixture = acceptance_runtime_with( + authenticator().with_required_scopes(vec!["evidence:invoke".to_owned()]), + ) + .await; + let (app, _metrics) = build_app_with_metrics(Arc::clone(&fixture.runtime)); + let response = app + .oneshot(build_request(&scenario)) + .await + .expect("the router answers"); + *sink.lock().expect("status slot") = Some(response.status()); + }); + assert_eq!( + answered.lock().expect("status slot").take(), + Some(StatusCode::UNAUTHORIZED) + ); + let refused: Vec<&Value> = emitted + .iter() + .filter(|record| record["fields"]["decision"] == json!("refused")) + .collect(); + assert_eq!(refused.len(), 1, "{refused:?}"); + let fields = &refused[0]["fields"]; + assert_eq!(fields["failed_check"], json!("scope")); + assert_eq!(fields["scope_claim"], json!("scope")); + assert_eq!(fields["required_scope"], json!("evidence:invoke")); + let raw = serde_json::to_string(&emitted).expect("captured records serialize"); + assert!( + !raw.contains(SCOPE_CANARY), + "a log line carried the token's scope" + ); +} diff --git a/crates/registry-evidence/src/runtime.rs b/crates/registry-evidence/src/runtime.rs index c902906297..d66d432d48 100644 --- a/crates/registry-evidence/src/runtime.rs +++ b/crates/registry-evidence/src/runtime.rs @@ -13,6 +13,7 @@ use async_trait::async_trait; use chrono::{SubsecRound as _, Utc}; use registry_adapter_engine::route::EvidenceHttpDiagnostic; use registry_platform_audit::{AuditDestination, AuditError, AuditProfile}; +use registry_platform_authcommon::{DeclaredScope, FailedCheck}; use registry_platform_crypto::{ LocalJwkSigner, PrivateJwk, SigningProvider, TransitInitializationError, TransitSigner, TransitSignerConfig, @@ -412,6 +413,9 @@ pub async fn validate_verification_material( pub struct RuntimeFailure { problem: ProblemCode, category: &'static str, + /// The check a refusal failed. Present exactly when the problem is one of + /// the refusal codes, which only [`refusal`] builds. + check: Option, } impl RuntimeFailure { @@ -422,6 +426,12 @@ impl RuntimeFailure { pub fn category(self) -> &'static str { self.category } + + /// The check a refusal failed, for the operator's count and log line. It is + /// written to no response. + pub fn check(self) -> Option { + self.check + } } impl std::fmt::Debug for RuntimeFailure { @@ -430,6 +440,7 @@ impl std::fmt::Debug for RuntimeFailure { .debug_struct("RuntimeFailure") .field("problem", &self.problem) .field("category", &self.category) + .field("check", &self.check.map(FailedCheck::as_str)) .finish() } } @@ -513,6 +524,12 @@ pub(crate) trait RuntimeAuthenticator: Send + Sync { async fn announce_key_source(&self); async fn key_source_ready(&self) -> bool; + + /// What a scope refusal may say about the deployment, when it has a scope + /// gate. + fn declared_scope(&self) -> Option { + None + } } #[async_trait] @@ -532,6 +549,10 @@ impl RuntimeAuthenticator for Authenticator { Authenticator::announce_key_source(self).await; } + fn declared_scope(&self) -> Option { + Authenticator::declared_scope(self) + } + async fn key_source_ready(&self) -> bool { Authenticator::key_source_ready(self).await } @@ -841,6 +862,11 @@ impl EvidenceRuntime { /// The per-source diagnostics whose counters back the /// `evidence_source_shape_drift_total` series on the metrics listener. + /// The configured values a scope refusal's log line may name. + pub(crate) fn declared_scope(&self) -> Option { + self.authenticator.declared_scope() + } + pub(crate) fn source_diagnostics(&self) -> Arc { Arc::clone(&self.source_diagnostics) } @@ -947,7 +973,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self .audit @@ -1292,9 +1318,10 @@ impl EvidenceRuntime { )); } if self.bundle().configuration_revision(requirement) != Some(expected) { - return Err(failure( + return Err(refusal( ProblemCode::NotAuthorized, "configuration-revision", + FailedCheck::RevisionPin, )); } Ok(()) @@ -1337,7 +1364,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let grant_deadline = grant_release_deadline(&context); let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self @@ -1435,7 +1462,10 @@ impl EvidenceRuntime { }; let matched = match match_entitlement(self.bundle(), &request, &context) { Ok(matched) => matched, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1448,7 +1478,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => return Err(map_authority(error)), }; @@ -1477,7 +1507,11 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "response-format")); + return Err(refusal( + ProblemCode::NotAuthorized, + "response-format", + FailedCheck::Disclosure, + )); } let selector_limit_input = canonical_pair( @@ -1495,7 +1529,10 @@ impl EvidenceRuntime { .map_err(map_selector_limit)?; let resolved = match resolve_selectors(self.bundle(), &request, &context, &matched) { Ok(resolved) => resolved, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1508,7 +1545,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => { if error == AuthorizationError::Selector { @@ -1810,7 +1847,7 @@ impl EvidenceRuntime { .authenticator .authenticate(access_token) .await - .map_err(|_| failure(ProblemCode::AuthenticationFailed, "authentication"))?; + .map_err(|error| authentication_refusal(&error))?; let grant_deadline = grant_release_deadline(&context); let rate_scope = rate_limit_scope(&self.bundle().config.service.trust_domain); let request_limit_key = self @@ -1881,7 +1918,10 @@ impl EvidenceRuntime { let matched = match match_entitlement(self.bundle(), request, &context) { Ok(matched) => matched, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1894,7 +1934,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => return Err(map_authority(error)), }; @@ -1921,7 +1961,11 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "response-format")); + return Err(refusal( + ProblemCode::NotAuthorized, + "response-format", + FailedCheck::Disclosure, + )); } // Only the batch container carries more than one credential, so every // other media type answers at most one presented key, in either binding @@ -1965,7 +2009,10 @@ impl EvidenceRuntime { .map_err(map_selector_limit)?; let resolved = match resolve_selectors(self.bundle(), request, &context, &matched) { Ok(resolved) => resolved, - Err(AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority) => { + Err( + error @ (AuthorizationError::Unauthorized(_) + | AuthorizationError::AmbiguousAuthority), + ) => { self.append_authorization_refusal( operation, AuditCaller { @@ -1978,7 +2025,7 @@ impl EvidenceRuntime { started, ) .await?; - return Err(failure(ProblemCode::NotAuthorized, "authorization")); + return Err(map_authority(error)); } Err(error) => { if error == AuthorizationError::Selector { @@ -3777,13 +3824,21 @@ fn acquisition_source_for_subjects<'a>( for subject in subjects { let source = acquisition .source_for_profile(&subject.selector_profile) - .ok_or_else(|| failure(ProblemCode::NotAuthorized, "acquisition-channel"))?; + .ok_or_else(acquisition_channel_refusal)?; if selected.is_some_and(|previous| previous != source) { - return Err(failure(ProblemCode::NotAuthorized, "acquisition-channel")); + return Err(acquisition_channel_refusal()); } selected = Some(source); } - selected.ok_or_else(|| failure(ProblemCode::NotAuthorized, "acquisition-channel")) + selected.ok_or_else(acquisition_channel_refusal) +} + +fn acquisition_channel_refusal() -> RuntimeFailure { + refusal( + ProblemCode::NotAuthorized, + "acquisition-channel", + FailedCheck::AcquisitionChannel, + ) } /// The shared value-free source failure classification used by serving and offline tooling. @@ -3791,7 +3846,13 @@ pub fn pack_source_failure(error: PackSourceError) -> RuntimeFailure { let (problem, category) = match error { PackSourceError::Plan => (ProblemCode::ServiceUnavailable, "source-plan"), PackSourceError::Inputs => (ProblemCode::ServiceUnavailable, "source-inputs"), - PackSourceError::Authority => (ProblemCode::NotAuthorized, "source-authority"), + PackSourceError::Authority => { + return refusal( + ProblemCode::NotAuthorized, + "source-authority", + FailedCheck::SourceAuthority, + ) + } PackSourceError::Audit => (ProblemCode::ServiceUnavailable, "access-audit"), PackSourceError::Budget => (ProblemCode::DependencyUnavailable, "acquisition-budget"), PackSourceError::Protocol => (ProblemCode::DependencyUnavailable, "source-protocol"), @@ -4120,7 +4181,11 @@ pub(crate) fn release_admission( if grant_deadline .is_some_and(|deadline| deadline.is_expired_at(Utc::now().timestamp_millis(), now)) { - return Err(failure(ProblemCode::NotAuthorized, "grant-expired")); + return Err(refusal( + ProblemCode::NotAuthorized, + "grant-expired", + FailedCheck::TaskGrantExpired, + )); } if now >= acquisition_deadline { return Err(failure( @@ -4131,8 +4196,40 @@ pub(crate) fn release_admission( Ok(()) } +/// A failure that is not a refusal. The refusal codes carry the check that +/// failed, so they are built by [`refusal`] and by nothing else. fn failure(problem: ProblemCode, category: &'static str) -> RuntimeFailure { - RuntimeFailure { problem, category } + debug_assert!( + !crate::observability::is_refusal_code(problem), + "a refusal code is built with `refusal`, which names its check" + ); + RuntimeFailure { + problem, + category, + check: None, + } +} + +/// An authentication, authorization or rate-limit refusal, with the check that +/// failed. +fn refusal(problem: ProblemCode, category: &'static str, check: FailedCheck) -> RuntimeFailure { + debug_assert!( + crate::observability::is_refusal_code(problem), + "`refusal` builds only the refusal codes" + ); + RuntimeFailure { + problem, + category, + check: Some(check), + } +} + +fn authentication_refusal(error: &AuthenticationError) -> RuntimeFailure { + refusal( + ProblemCode::AuthenticationFailed, + "authentication", + error.failed_check(), + ) } fn evidence_unavailable_failure() -> RuntimeFailure { @@ -4148,16 +4245,25 @@ fn public_check_miss() -> RuntimeFailure { fn map_authority(error: AuthorizationError) -> RuntimeFailure { match error { AuthorizationError::Selector => failure(ProblemCode::InvalidSelector, "selector"), - AuthorizationError::Unauthorized | AuthorizationError::AmbiguousAuthority => { - failure(ProblemCode::NotAuthorized, "authorization") + AuthorizationError::Unauthorized(check) => { + refusal(ProblemCode::NotAuthorized, "authorization", check) } + AuthorizationError::AmbiguousAuthority => refusal( + ProblemCode::NotAuthorized, + "authorization", + FailedCheck::AccessProfile, + ), AuthorizationError::Binding => failure(ProblemCode::ServiceUnavailable, "subject-binding"), } } fn map_request_limit(error: RateLimitError) -> RuntimeFailure { match error { - RateLimitError::RequestExceeded => failure(ProblemCode::RateLimited, "request-rate"), + RateLimitError::RequestExceeded => refusal( + ProblemCode::RateLimited, + "request-rate", + FailedCheck::RateLimit, + ), // No wait admits a cost the burst cannot hold, so this is a request // the deployment will never accept, not a retryable rate limit: it // carries no Retry-After and charges nothing. @@ -4168,9 +4274,11 @@ fn map_request_limit(error: RateLimitError) -> RuntimeFailure { fn map_selector_limit(error: RateLimitError) -> RuntimeFailure { match error { - RateLimitError::FailedSelectorExceeded => { - failure(ProblemCode::RateLimited, "selector-rate") - } + RateLimitError::FailedSelectorExceeded => refusal( + ProblemCode::RateLimited, + "selector-rate", + FailedCheck::RateLimit, + ), _ => failure(ProblemCode::ServiceUnavailable, "selector-rate"), } } @@ -4496,6 +4604,11 @@ mod tests { let failure = pack_source_failure(error); assert_eq!(failure.problem, problem); assert_eq!(failure.category, category); + assert_eq!( + failure.check(), + (category == "source-authority").then_some(FailedCheck::SourceAuthority), + "only the authority refusal is recorded as a refusal: {category}" + ); assert!( categories.insert(category), "two pack failures share the category {category}" @@ -4508,6 +4621,25 @@ mod tests { } } + #[test] + fn refusals_built_outside_the_request_path_carry_the_check_that_refused() { + let channel = acquisition_channel_refusal(); + assert_eq!(channel.problem(), ProblemCode::NotAuthorized); + assert_eq!(channel.check(), Some(FailedCheck::AcquisitionChannel)); + + let request_rate = map_request_limit(RateLimitError::RequestExceeded); + assert_eq!(request_rate.problem(), ProblemCode::RateLimited); + assert_eq!(request_rate.check(), Some(FailedCheck::RateLimit)); + let selector_rate = map_selector_limit(RateLimitError::FailedSelectorExceeded); + assert_eq!(selector_rate.problem(), ProblemCode::RateLimited); + assert_eq!(selector_rate.check(), Some(FailedCheck::RateLimit)); + assert_eq!( + map_request_limit(RateLimitError::CostExceedsBurst).check(), + None, + "a request the burst can never hold is not a rate-limit refusal" + ); + } + #[test] fn audit_scope_is_unambiguous_for_component_boundaries() { assert_ne!( diff --git a/crates/registry-evidence/src/runtime_tests.rs b/crates/registry-evidence/src/runtime_tests.rs index bcfc0ceb1d..5c9788d1a8 100644 --- a/crates/registry-evidence/src/runtime_tests.rs +++ b/crates/registry-evidence/src/runtime_tests.rs @@ -82,6 +82,8 @@ use registry_evidence_verifier::model::{ mod discovery_channel_tests; #[path = "evidence_source_tests.rs"] mod evidence_source_tests; +#[path = "refusal_recording_tests.rs"] +mod refusal_recording_tests; #[path = "wallet_channel_tests.rs"] mod wallet_channel_tests; @@ -3562,7 +3564,7 @@ async fn admission_gates_refuse_unadmitted_clients_and_missing_scopes() { .await .expect_err(&format!("{label} was accepted")); assert!( - matches!(error, AuthenticationError::Verification), + matches!(error, AuthenticationError::Verification(_)), "{label}: {error:?}" ); } @@ -3584,7 +3586,7 @@ async fn admission_gates_refuse_unadmitted_clients_and_missing_scopes() { .await .expect_err(&format!("{label} was accepted")); assert!( - matches!(error, AuthenticationError::Verification), + matches!(error, AuthenticationError::Verification(_)), "{label}: {error:?}" ); } @@ -3818,10 +3820,19 @@ async fn release_admission_needs_both_the_acquisition_deadline_and_the_grant_ahe release_admission(ahead, Some(deadline(wall_seconds - 1))).expect_err("grant expired"); assert_eq!(expired_grant.problem(), ProblemCode::NotAuthorized); assert_eq!(expired_grant.category(), "grant-expired"); + assert_eq!( + expired_grant.check(), + Some(registry_platform_authcommon::FailedCheck::TaskGrantExpired) + ); let expired_budget = release_admission(behind, Some(deadline(expiry_ahead))).expect_err("budget spent"); assert_eq!(expired_budget.problem(), ProblemCode::DependencyUnavailable); assert_eq!(expired_budget.category(), "acquisition-budget"); + assert_eq!( + expired_budget.check(), + None, + "a spent budget is not a refusal" + ); } #[test] @@ -3964,7 +3975,7 @@ async fn admitted_release_append_completes_and_returns_bytes_after_deadline() { let captured = Arc::new(Mutex::new(Vec::new())); let release_started = Arc::new(Mutex::new(None)); let audit = EvidenceAuditLog::with_writer( - AuditWriter::from_line_sink(Box::new(SlowDisclosureSink { + AuditWriter::from_line_sink_without_posture(Box::new(SlowDisclosureSink { bytes: Arc::clone(&captured), release_started: Arc::clone(&release_started), delay: Duration::from_millis(1_500), @@ -8651,6 +8662,10 @@ async fn failed_selector_budget_is_enforced_by_the_runtime_and_scoped_to_authori .await .expect_err("the next request is rejected before selector resolution"); assert_eq!(exhausted.problem(), ProblemCode::RateLimited); + assert_eq!( + exhausted.check(), + Some(registry_platform_authcommon::FailedCheck::RateLimit) + ); retained_failures.push_str(&format!("{exhausted:?} {exhausted}\n")); let now = Utc::now().timestamp(); @@ -9812,9 +9827,13 @@ fn acceptance_case_time( } async fn acceptance_runtime() -> AcceptanceRuntime { + acceptance_runtime_with(authenticator()).await +} + +async fn acceptance_runtime_with(authenticator: Authenticator) -> AcceptanceRuntime { let prepared = prepare_acceptance("subject-binding-secret-canary-32-bytes-minimum").await; let runtime = Arc::new( - EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator()) + EvidenceRuntime::initialize_with_authenticator(&prepared.runtime_path, authenticator) .await .expect("one immutable acceptance runtime initializes"), ); @@ -12613,7 +12632,7 @@ fn fetching_authenticator(jwks_uri: &str) -> Authenticator { Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri.to_owned(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), )); Authenticator::new( diff --git a/crates/registry-evidence/src/secrets.rs b/crates/registry-evidence/src/secrets.rs index e806b932a8..7957afa2f1 100644 --- a/crates/registry-evidence/src/secrets.rs +++ b/crates/registry-evidence/src/secrets.rs @@ -1,7 +1,8 @@ //! Shared bounded secret resolution used by Evidence. //! //! The implementation lives in `registry-platform-config` so Evidence applies -//! the shared anchored, no-follow, owner-only file policy. +//! the shared anchored secret-file rule: relative links below the root only, +//! one hard link, and the owner and mode checks of `SecretFileCheck`. pub use registry_platform_config::{ ProtectedSecret, SecretError, SecretProvider, SecretResolver, MAX_SECRET_BYTES, diff --git a/crates/registry-evidence/src/selector.rs b/crates/registry-evidence/src/selector.rs index 0049d99852..052ecd50f6 100644 --- a/crates/registry-evidence/src/selector.rs +++ b/crates/registry-evidence/src/selector.rs @@ -3,12 +3,13 @@ use std::{collections::BTreeSet, fmt}; use chrono::NaiveDate; +use registry_platform_authcommon::FailedCheck; use registry_platform_oidc::ActorKind; use serde_json::Value; use thiserror::Error; use crate::{ - auth::AuthenticatedContext, + auth::{AuthenticatedContext, TaskGrantError}, binding::{ subject_binding, BindingError, SelectorField as BindingField, SelectorScalar as BindingScalar, SubjectBindingInput, SubjectBindingScope, @@ -53,8 +54,11 @@ pub(crate) fn validate_subject_binding_key( #[derive(Debug, Error, Clone, Copy, PartialEq, Eq)] pub enum AuthorizationError { + /// The request is refused. The check says which part of the decision did + /// it, for the operator's count and log line. The caller learns only that + /// the request is not permitted. #[error("the Evidence request is not authorized")] - Unauthorized, + Unauthorized(FailedCheck), #[error("the Evidence request selector is invalid")] Selector, #[error("the Evidence authorization decision is ambiguous")] @@ -459,6 +463,18 @@ pub fn authority_selected_by_principal( .all(|required| requester_tags.iter().any(|actual| actual == required)) } +/// The check a present but untrustworthy task grant failed. +#[deny(clippy::wildcard_enum_match_arm)] +fn task_grant_check(error: TaskGrantError) -> FailedCheck { + match error { + TaskGrantError::Claims => FailedCheck::TaskGrantClaims, + TaskGrantError::Expired => FailedCheck::TaskGrantExpired, + TaskGrantError::PrincipalMismatch | TaskGrantError::Client | TaskGrantError::Resource => { + FailedCheck::TaskGrantBinding + } + } +} + /// Match exactly one complete entitlement without inspecting selector values. /// /// Keeping this decision separate lets the service charge invalid selector @@ -471,7 +487,8 @@ pub fn match_entitlement( ) -> Result { let has_task_grant = match context.grant() { Ok(Some(_)) if context.actor_kind() == ActorKind::Agent => true, - Ok(Some(_)) | Err(_) => return Err(AuthorizationError::Unauthorized), + Ok(Some(_)) => return Err(AuthorizationError::Unauthorized(FailedCheck::ActorKind)), + Err(error) => return Err(AuthorizationError::Unauthorized(task_grant_check(error))), Ok(None) => false, }; let requirement = bundle @@ -479,22 +496,31 @@ pub fn match_entitlement( .requirements .iter() .find(|candidate| candidate.id == request.requirement) - .ok_or(AuthorizationError::Unauthorized)?; - if requirement.grant_ceiling.as_ref().is_some_and(|ceiling| { - !ceiling + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; + if let Some(ceiling) = &requirement.grant_ceiling { + if !ceiling.actor_kinds.contains(&context.actor_kind()) { + return Err(AuthorizationError::Unauthorized(FailedCheck::ActorKind)); + } + if !ceiling .audiences .iter() .any(|audience| audience == context.evidence_audience()) - || !ceiling.actor_kinds.contains(&context.actor_kind()) - }) { - return Err(AuthorizationError::Unauthorized); + { + // The audience is the caller's own claim. It is a grant binding + // only when the caller presented a task grant. + return Err(AuthorizationError::Unauthorized(if has_task_grant { + FailedCheck::TaskGrantBinding + } else { + FailedCheck::AccessProfile + })); + } } if !requirement .purposes .iter() .any(|purpose| purpose == &request.purpose) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized(FailedCheck::Purpose)); } validate_request_subject_shape(requirement, &request.subjects)?; @@ -545,7 +571,7 @@ pub fn match_entitlement( match matched.len() { 1 => Ok(matched.remove(0)), - 0 => Err(AuthorizationError::Unauthorized), + 0 => Err(AuthorizationError::Unauthorized(FailedCheck::AccessProfile)), _ => Err(AuthorizationError::AmbiguousAuthority), } } @@ -589,7 +615,7 @@ pub fn resolve_selectors( .requirements .iter() .find(|candidate| candidate.id == request.requirement) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; let subjects = resolve_grant_subjects( bundle, requirement, @@ -667,7 +693,9 @@ pub(crate) fn validate_entitlement_context( .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); if uses_authenticated_grant && context.grant_id().is_none() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + )); } for grant in &matched.subjects { @@ -678,11 +706,15 @@ pub(crate) fn validate_entitlement_context( .config .selector_profiles .get(&grant.selector_profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let claims = grant .value_claims .as_ref() - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let values = claims .iter() .map(|(field, path)| { @@ -733,7 +765,7 @@ pub(crate) fn resolve_request_origin_subjects( .iter() .any(|configured| configured == purpose) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized(FailedCheck::Purpose)); } // Value origin belongs to the configured request shape. At least one @@ -757,7 +789,9 @@ pub(crate) fn resolve_request_origin_subjects( .all(|subject| subject.value_origin == ValueOrigin::Request) }); if !configured_as_request_origin { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } // Emit the requirement's declaration order. Request array position has no @@ -770,12 +804,16 @@ pub(crate) fn resolve_request_origin_subjects( let subject = requested .iter() .find(|subject| subject.role == declared.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let profile = bundle .config .selector_profiles .get(&subject.selector.profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let values = subject .selector .values @@ -859,7 +897,7 @@ pub fn resolve_offline_fixture_authorization( }) .map(|grant| (authority, grant)) }) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized(FailedCheck::AccessProfile))?; let claims = case .get("verifiedTokenClaims") .or_else(|| common.and_then(|value| value.get("verifiedTokenClaims"))) @@ -869,67 +907,73 @@ pub fn resolve_offline_fixture_authorization( .subjects .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); - let (actor_kind, client, task_grant) = if uses_task_grant { - let client = authority - .requester_clients - .first() - .ok_or(AuthorizationError::Unauthorized)?; - let source_issuer = authority - .grant_source_issuer - .as_deref() - .ok_or(AuthorizationError::Unauthorized)?; - let resource = bundle.config.authentication.oidc.audience(); - let names = &bundle.config.authentication.oidc.claims; - let now = chrono::Utc::now().timestamp(); - let mut grant_claims = serde_json::json!({ - "sub": "offline-fixture-principal", - "exp": now + 300, - }); - let object = grant_claims - .as_object_mut() - .ok_or(AuthorizationError::Unauthorized)?; - object.insert( - names.grant_id.clone(), - Value::String("offline-fixture-grant".to_owned()), - ); - object.insert( - names.grant_source_issuer.clone(), - Value::String(source_issuer.to_owned()), - ); - object.insert(names.grant_client.clone(), Value::String(client.to_owned())); - object.insert( - names.grant_resource.clone(), - Value::String(resource.to_owned()), - ); - object.insert( - names.purpose.clone(), - Value::String(request.purpose.clone()), - ); - object.insert(names.grant_exp.clone(), Value::from(now + 300)); - object.insert( - names.grant_bounds.clone(), - serde_json::json!({"type": "evidence", "requirement": request.requirement}), - ); - object.insert( - names.approver.clone(), - Value::String("h:offline-fixture-approver".to_owned()), - ); - let parsed: registry_platform_oidc::Claims = - serde_json::from_value(grant_claims).map_err(|_| AuthorizationError::Unauthorized)?; - let grant = registry_platform_oidc::grant_claims( - &parsed, - names, - u64::try_from(now).map_err(|_| AuthorizationError::Unauthorized)?, - ) - .map_err(|_| AuthorizationError::Unauthorized)?; - (ActorKind::Agent, Some(client.as_str()), Ok(grant)) - } else { - ( - authority.actor_kind.unwrap_or(ActorKind::Service), - None, - Ok(None), - ) - }; + let (actor_kind, client, task_grant) = + if uses_task_grant { + let client = + authority + .requester_clients + .first() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantBinding, + ))?; + let source_issuer = authority.grant_source_issuer.as_deref().ok_or( + AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding), + )?; + let resource = bundle.config.authentication.oidc.audience(); + let names = &bundle.config.authentication.oidc.claims; + let now = chrono::Utc::now().timestamp(); + let mut grant_claims = serde_json::json!({ + "sub": "offline-fixture-principal", + "exp": now + 300, + }); + let object = grant_claims + .as_object_mut() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + ))?; + object.insert( + names.grant_id.clone(), + Value::String("offline-fixture-grant".to_owned()), + ); + object.insert( + names.grant_source_issuer.clone(), + Value::String(source_issuer.to_owned()), + ); + object.insert(names.grant_client.clone(), Value::String(client.to_owned())); + object.insert( + names.grant_resource.clone(), + Value::String(resource.to_owned()), + ); + object.insert( + names.purpose.clone(), + Value::String(request.purpose.clone()), + ); + object.insert(names.grant_exp.clone(), Value::from(now + 300)); + object.insert( + names.grant_bounds.clone(), + serde_json::json!({"type": "evidence", "requirement": request.requirement}), + ); + object.insert( + names.approver.clone(), + Value::String("h:offline-fixture-approver".to_owned()), + ); + let parsed: registry_platform_oidc::Claims = serde_json::from_value(grant_claims) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?; + let grant = registry_platform_oidc::grant_claims( + &parsed, + names, + u64::try_from(now) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?, + ) + .map_err(|_| AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims))?; + (ActorKind::Agent, Some(client.as_str()), Ok(grant)) + } else { + ( + authority.actor_kind.unwrap_or(ActorKind::Service), + None, + Ok(None), + ) + }; let context = AuthenticatedContext::offline_fixture_context( authority.requester_tags.clone().into_vec(), audience, @@ -965,7 +1009,7 @@ fn fixture_audience<'a>( }, }; if ceiling.is_some_and(|allowed| !allowed.iter().any(|entry| entry == audience)) { - return Err(AuthorizationError::Unauthorized.into()); + return Err(AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding).into()); } Ok(audience) } @@ -986,7 +1030,7 @@ fn fixture_purpose<'a>( .find(|purpose| purpose.as_str() == declared) .map(String::as_str) .ok_or(OfflineFixtureError::Authorization( - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::Purpose), )) } None => match purposes { @@ -1052,13 +1096,17 @@ fn fixture_subjects_from_selectors( && grant.purpose == purpose && same_subject_tuples(&grant.subjects, &requested) }) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; for subject in &mut requested { let granted = grant .subjects .iter() .find(|granted| granted.role == subject.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; if granted.value_origin != ValueOrigin::Request { subject.selector.values = None; } @@ -1136,24 +1184,32 @@ fn validate_request_subject_shape( requested: &[RequestedSubject], ) -> Result<(), AuthorizationError> { if requested.len() != requirement.subject_roles.len() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } let mut roles = BTreeSet::new(); for subject in requested { if !roles.insert(subject.role.as_str()) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } let configured = requirement .subject_roles .iter() .find(|configured| configured.role == subject.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; if !configured .selector_profiles .iter() .any(|profile| profile == &subject.selector.profile) { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } } Ok(()) @@ -1181,10 +1237,14 @@ fn resolve_grant_subjects( .iter() .any(|subject| subject.value_origin == ValueOrigin::AuthenticatedGrant); if uses_authenticated_grant && context.grant_id().is_none() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::TaskGrantClaims, + )); } if granted.len() != requirement.subject_roles.len() { - return Err(AuthorizationError::Unauthorized); + return Err(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + )); } requirement @@ -1194,16 +1254,22 @@ fn resolve_grant_subjects( let grant = granted .iter() .find(|grant| grant.role == declared.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let subject = requested .iter() .find(|subject| subject.role == grant.role) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let profile = bundle .config .selector_profiles .get(&grant.selector_profile) - .ok_or(AuthorizationError::Unauthorized)?; + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; let input = match grant.value_origin { ValueOrigin::Request => subject .selector @@ -1215,10 +1281,13 @@ fn resolve_grant_subjects( if subject.selector.values.is_some() { return Err(AuthorizationError::Selector); } - let claims = grant - .value_claims - .as_ref() - .ok_or(AuthorizationError::Unauthorized)?; + let claims = + grant + .value_claims + .as_ref() + .ok_or(AuthorizationError::Unauthorized( + FailedCheck::SubjectSelector, + ))?; claims .iter() .map(|(field, path)| { @@ -1424,6 +1493,22 @@ mod tests { use crate::model::HolderPublicKey; + #[test] + fn every_task_grant_error_is_counted_under_the_member_that_names_it() { + for (error, check) in [ + (TaskGrantError::Claims, FailedCheck::TaskGrantClaims), + (TaskGrantError::Expired, FailedCheck::TaskGrantExpired), + ( + TaskGrantError::PrincipalMismatch, + FailedCheck::TaskGrantBinding, + ), + (TaskGrantError::Client, FailedCheck::TaskGrantBinding), + (TaskGrantError::Resource, FailedCheck::TaskGrantBinding), + ] { + assert_eq!(task_grant_check(error), check, "{error:?}"); + } + } + #[test] fn resolved_selector_debug_never_exposes_values() { let subject = ResolvedSubject { @@ -1675,7 +1760,7 @@ mod tests { let outside = fixture_object(serde_json::json!({"audience":"urn:example:outside"})); assert_eq!( fixture_audience(Some(&ceiling), None, &outside, "urn:legacy:fixture"), - Err(AuthorizationError::Unauthorized.into()) + Err(AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding).into()) ); let multiple = vec![ "urn:example:first".to_owned(), @@ -1746,7 +1831,9 @@ mod tests { assert_eq!(error, OfflineFixtureError::Purpose); assert_ne!( error, - OfflineFixtureError::Authorization(AuthorizationError::Unauthorized), + OfflineFixtureError::Authorization(AuthorizationError::Unauthorized( + FailedCheck::Purpose + )), "an unselected fixture purpose must not be reported as an authorization denial" ); } @@ -1774,7 +1861,7 @@ mod tests { &fixture_object(serde_json::json!({"purpose": "other"})) ), Err(OfflineFixtureError::Authorization( - AuthorizationError::Unauthorized + AuthorizationError::Unauthorized(FailedCheck::Purpose) )) ); } diff --git a/crates/registry-evidence/src/server.rs b/crates/registry-evidence/src/server.rs index efd5de0773..33a215927d 100644 --- a/crates/registry-evidence/src/server.rs +++ b/crates/registry-evidence/src/server.rs @@ -33,7 +33,9 @@ use axum::{ routing::{get, post}, Router, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, BearerParseError, FailedCheck, RefusalNote, +}; use registry_platform_crypto::parse_json_strict; use registry_platform_httpsec::CspBuilder; use serde::Serialize; @@ -155,6 +157,7 @@ fn build_app_with_tracker_at( // use, on the separate opt-in metrics listener. let rate_limiter = runtime.rate_limiter(); let source_diagnostics = runtime.source_diagnostics(); + let declared_scope = runtime.declared_scope(); let state = Arc::new(ServerState { runtime, maximum_request_bytes, @@ -210,7 +213,9 @@ fn build_app_with_tracker_at( authentication_challenge, attach_authentication_challenge, )); - let metrics = Arc::new(Metrics::new(rate_limiter, source_diagnostics)); + let metrics = Arc::new( + Metrics::new(rate_limiter, source_diagnostics).with_declared_scope(declared_scope), + ); ( response_layers(routes, Arc::clone(&metrics)), evaluations, @@ -273,7 +278,8 @@ fn response_layers(routes: Router, metrics: Arc) -> Router { .layer(from_fn(add_no_store)) .layer(registry_platform_httpsec::corp_conditional()) .layer( - registry_platform_httpsec::security_headers(CspBuilder::restrictive()).without_hsts(), + registry_platform_httpsec::security_headers_without_posture(CspBuilder::restrictive()) + .without_hsts(), ) // Outermost, so that every response including both fallbacks carries a // correlation identifier and produces exactly one operational record. @@ -466,7 +472,14 @@ async fn create_evidence_negotiated(state: Arc, request: Request token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; // Strict media negotiation resolves the requested response format before // the body is read and long before credential acquisition or source @@ -603,7 +616,14 @@ async fn create_evidence_batch_negotiated( let access_token = match bearer_token(request.headers()) { Ok(token) => token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; if !has_exact_accept(request.headers(), EVIDENCE_REQUEST_BATCH_MEDIA_TYPE) { return problem_response( @@ -863,7 +883,14 @@ async fn discover_evidence( let started = Instant::now(); let access_token = match bearer_token(request.headers()) { Ok(token) => token.to_owned(), - Err(code) => return problem_response(code, "authentication", &operation), + Err(check) => { + return refusal_response( + ProblemCode::AuthenticationFailed, + "authentication", + check, + &operation, + ) + } }; if request.uri().query().is_some() || content_length_exceeds(request.headers(), 0) { return problem_response(ProblemCode::MalformedRequest, "request-shape", &operation); @@ -1130,18 +1157,32 @@ fn parse_evidence_request_batch(bytes: &[u8]) -> Result Result<&str, ProblemCode> { +/// The bearer token the request carries, or the check its header failed: no +/// header, or one that is not a bearer credential, is a missing credential. A +/// repeated, unreadable or misshapen one is a malformed credential. A value too +/// short to carry the scheme is misshapen only when it is the start of +/// `Bearer`, and otherwise names some other scheme. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { let mut values = headers.get_all(AUTHORIZATION).iter(); - let value = values.next().ok_or(ProblemCode::AuthenticationFailed)?; + let value = values.next().ok_or(FailedCheck::CredentialMissing)?; if values.next().is_some() { - return Err(ProblemCode::AuthenticationFailed); + return Err(FailedCheck::CredentialMalformed); } - parse_bearer_token( - value - .to_str() - .map_err(|_| ProblemCode::AuthenticationFailed)?, - ) - .map_err(|_| ProblemCode::AuthenticationFailed) + let value = value + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(value).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + BearerParseError::Malformed if !is_scheme_prefix(value) => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) +} + +/// Whether the value is the start of the `Bearer` scheme name, compared ASCII +/// case-insensitively. +fn is_scheme_prefix(value: &str) -> bool { + const SCHEME: &[u8] = b"Bearer"; + value.len() <= SCHEME.len() && SCHEME[..value.len()].eq_ignore_ascii_case(value.as_bytes()) } fn has_exact_content_type(headers: &HeaderMap, expected: &str) -> bool { @@ -1172,7 +1213,10 @@ fn remaining(limit: Duration, started: Instant) -> Option { } fn runtime_failure_response(failure: RuntimeFailure, operation: &OperationId) -> Response { - problem_response(failure.problem(), failure.category(), operation) + match failure.check() { + Some(check) => refusal_response(failure.problem(), failure.category(), check, operation), + None => problem_response(failure.problem(), failure.category(), operation), + } } /// Build one problem response, recording the internal category that caused it. @@ -1187,6 +1231,37 @@ fn problem_response( code: ProblemCode, category: &'static str, operation: &OperationId, +) -> Response { + debug_assert!( + !observability::is_refusal_code(code), + "a refusal is answered with `refusal_response`, which names its check" + ); + answer(code, category, None, operation) +} + +/// Build the answer to an authentication, authorization or rate-limit refusal. +/// +/// The check rides in the response extensions with the code and category. The +/// observation layer counts and logs it. It is not serialized, so the caller's +/// bytes are the ones `problem_response` would have produced. +fn refusal_response( + code: ProblemCode, + category: &'static str, + check: FailedCheck, + operation: &OperationId, +) -> Response { + debug_assert!( + observability::is_refusal_code(code), + "`refusal_response` answers only the refusal codes" + ); + answer(code, category, Some(check), operation) +} + +fn answer( + code: ProblemCode, + category: &'static str, + check: Option, + operation: &OperationId, ) -> Response { let body = code.body(operation.trace_id()); let mut response = serialize_response(code.status(), PROBLEM_MEDIA_TYPE, &body) @@ -1199,6 +1274,9 @@ fn problem_response( response .extensions_mut() .insert(observability::FailureCategory(category)); + if let Some(check) = check { + response.extensions_mut().insert(RefusalNote::new(check)); + } if code == ProblemCode::AuthenticationFailed { response.headers_mut().insert( axum::http::header::WWW_AUTHENTICATE, @@ -1324,29 +1402,40 @@ mod tests { ); } - for invalid in [ - "Basic three.parts.value", - "Bearer", - "Bearer three.parts.value", - "Bearer three.parts.value ", - "Bearer three.parts.value,other", + for (invalid, check) in [ + ("Basic three.parts.value", FailedCheck::CredentialMissing), + ("Basic", FailedCheck::CredentialMissing), + ("Bear", FailedCheck::CredentialMalformed), + ("bearer", FailedCheck::CredentialMalformed), + ("Bearer", FailedCheck::CredentialMalformed), + ( + "Bearer three.parts.value", + FailedCheck::CredentialMalformed, + ), + ( + "Bearer three.parts.value ", + FailedCheck::CredentialMalformed, + ), + ( + "Bearer three.parts.value,other", + FailedCheck::CredentialMalformed, + ), ] { headers.insert( AUTHORIZATION, HeaderValue::from_str(invalid).expect("test header is valid"), ); - assert_eq!( - bearer_token(&headers), - Err(ProblemCode::AuthenticationFailed) - ); + assert_eq!(bearer_token(&headers), Err(check), "{invalid}"); } + headers.clear(); + assert_eq!(bearer_token(&headers), Err(FailedCheck::CredentialMissing)); headers.clear(); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer first")); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer second")); assert_eq!( bearer_token(&headers), - Err(ProblemCode::AuthenticationFailed) + Err(FailedCheck::CredentialMalformed) ); } @@ -1489,9 +1578,10 @@ mod tests { #[tokio::test] async fn problem_responses_have_closed_media_and_challenge_headers() { let operation = operation_id(&axum::http::Extensions::new()); - let authentication = problem_response( + let authentication = refusal_response( ProblemCode::AuthenticationFailed, "authentication", + FailedCheck::CredentialMissing, &operation, ); assert_eq!(authentication.status(), StatusCode::UNAUTHORIZED); @@ -1508,7 +1598,12 @@ mod tests { )) ); - let rate = problem_response(ProblemCode::RateLimited, "rate-limit", &operation); + let rate = refusal_response( + ProblemCode::RateLimited, + "rate-limit", + FailedCheck::RateLimit, + &operation, + ); assert_eq!(rate.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!( rate.headers().get(RETRY_AFTER), diff --git a/crates/registry-evidence/tests/golden/refusal_answers.json b/crates/registry-evidence/tests/golden/refusal_answers.json new file mode 100644 index 0000000000..0335fd54fe --- /dev/null +++ b/crates/registry-evidence/tests/golden/refusal_answers.json @@ -0,0 +1,434 @@ +{ + "batch-without-credential": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "client-not-admitted": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "discovery-with-wrong-issuer": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": null, + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "discovery-without-credential": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": null, + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "double-space-separator": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "evidence-audience-claim-is-not-a-url": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "expired-task-grant": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "expired-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "no-authorization-header": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "no-entitlement-for-the-requester": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "non-bearer-scheme": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "not-a-compact-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "purpose-not-permitted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "repeated-authorization-header": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "requester-tags-claim-absent": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "response-format-not-permitted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "revision-pin-mismatch": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "selector-profile-not-granted": { + "body": { + "code": "evidence.denied", + "detail": "the Evidence request is not permitted", + "status": 403, + "title": "Evidence request is not permitted", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": null + }, + "status": 403 + }, + "sender-constrained-token": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "tampered-signature": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "unknown-actor-kind": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "unknown-key": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "wrong-audience": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + }, + "wrong-issuer": { + "body": { + "code": "auth.invalid-credential", + "detail": "bearer access token validation failed", + "status": 401, + "title": "Bearer access token is invalid", + "traceId": "", + "type": "https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "vary": "Accept", + "www-authenticate": "Bearer realm=\"registry-evidence\", resource_metadata=\"https://evidence.invalid/.well-known/oauth-protected-resource\"" + }, + "status": 401 + } +} diff --git a/crates/registry-evidence/tests/selector_conformance.rs b/crates/registry-evidence/tests/selector_conformance.rs index 59f48f15b4..1f27f3b1bd 100644 --- a/crates/registry-evidence/tests/selector_conformance.rs +++ b/crates/registry-evidence/tests/selector_conformance.rs @@ -38,6 +38,7 @@ use registry_evidence::selector::{ }; use registry_evidence::signing::{jwks_document, EvidenceSigner}; use registry_evidence::verifier::{verify_flattened_jws, EvidenceVerificationPolicy}; +use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::{sign, LocalJwkSigner, PrivateJwk, SigningProvider}; use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier, TokenVerifierConfig}; use serde_json::{json, Value}; @@ -527,7 +528,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { "record_reference", SelectorValue::String("synthetic-record-001".to_owned()), )])), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("identifier-possession-without-entitlement"); @@ -629,14 +630,13 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { "event_reference": "synthetic-event-001" }} })); - assert!(matches!( - service - .authorize(&grant_source_without_id, &grant_request(None)) - .await, - Err(AuthorizationStageError::Authorization( - AuthorizationError::Unauthorized - )) - )); + assert_authorization_error( + &service, + &grant_source_without_id, + &grant_request(None), + AuthorizationError::Unauthorized(FailedCheck::TaskGrantClaims), + ) + .await; executed.insert("authenticated-grant-id-not-bound"); let mut wrong_grant_source_issuer = task_grant_claims(json!({ @@ -651,7 +651,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &access_token(wrong_grant_source_issuer), &grant_request(None), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("authenticated-grant-source-issuer-not-bound"); @@ -663,7 +663,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { PROPERTY_WITH_EVENT, vec![subject("subject", "demographics-v1", None)], ), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("alternative-field-set-not-inferred"); @@ -684,7 +684,13 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { subject("subject-b", "opaque-record-v1", role_a.clone()), ], ); - assert_authorization_error(&service, &base, &swapped, AuthorizationError::Unauthorized).await; + assert_authorization_error( + &service, + &base, + &swapped, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), + ) + .await; executed.insert("swapped-role-selectors"); let substituted = request( @@ -698,7 +704,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &substituted, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unauthorized-subject-b-substitution"); @@ -711,7 +717,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &missing_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("missing-one-role"); @@ -727,7 +733,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &duplicate_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("duplicate-subject-role"); @@ -743,7 +749,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &unknown_role, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unknown-subject-role"); @@ -766,7 +772,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &union_attempt, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; executed.insert("entitlement-union-across-roles"); @@ -887,7 +893,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { ]), )], ), - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::SubjectSelector), ) .await; executed.insert("unauthorized-profile"); @@ -901,7 +907,7 @@ async fn all_runtime_selector_negatives_fail_closed_before_source_access() { &service, &base, &wrong_purpose, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::Purpose), ) .await; executed.insert("unauthorized-purpose"); @@ -969,7 +975,7 @@ async fn standing_agent_requires_an_explicit_agent_profile() { &service, &access_token(json!({"registry_actor_kind": "agent"})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; assert!(service.server.received_requests().await.unwrap().is_empty()); @@ -986,12 +992,63 @@ async fn standing_agent_requires_an_explicit_agent_profile() { &bound, &access_token(json!({"registry_actor_kind": "service"})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; assert!(bound.server.received_requests().await.unwrap().is_empty()); } +/// The package grant ceiling names the actor kinds and audiences a definition +/// serves for every caller, so a standing caller outside it is counted under +/// the member for the claim that failed, not under a task-grant member. +#[tokio::test] +async fn a_package_grant_ceiling_refusal_is_counted_under_the_claim_that_failed() { + let request = grant_request(None); + + let wrong_actor_kind = prepare_service_with_ceiling( + false, + None, + Some(("agent", &format!("\"{EVIDENCE_AUDIENCE}\""))), + ) + .await; + assert_authorization_error( + &wrong_actor_kind, + &access_token(json!({})), + &request, + AuthorizationError::Unauthorized(FailedCheck::ActorKind), + ) + .await; + + let wrong_audience = + prepare_service_with_ceiling(false, None, Some(("service", "\"urn:example:other\""))).await; + assert_authorization_error( + &wrong_audience, + &access_token(json!({})), + &request, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), + ) + .await; + let subject = json!({ + "given_name": "Adaeze", + "family_name": "Okafor", + "birth_date": "1990-07-11", + "event_reference": "synthetic-event-001" + }); + let wrong_audience_for_a_grant = prepare_service_with_ceiling( + false, + None, + Some(("service, agent", "\"urn:example:other\"")), + ) + .await; + assert_authorization_error( + &wrong_audience_for_a_grant, + &access_token(task_grant_claims(subject)), + &request, + AuthorizationError::Unauthorized(FailedCheck::TaskGrantBinding), + ) + .await; +} + #[tokio::test] async fn task_grant_context_is_bound_before_selector_or_source_access() { let service = prepare_service(false).await; @@ -1000,7 +1057,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(json!({})), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::AccessProfile), ) .await; let subject = json!({ @@ -1010,23 +1067,36 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { "event_reference": "synthetic-event-001" }); - for (name, member, value) in [ + for (name, member, value, check) in [ ( "source issuer", "registry_grant_source_issuer", json!("https://other.invalid"), + FailedCheck::AccessProfile, + ), + ( + "client", + "registry_grant_client", + json!("other-client"), + FailedCheck::TaskGrantBinding, ), - ("client", "registry_grant_client", json!("other-client")), ( "resource", "registry_grant_resource", json!("other-resource"), + FailedCheck::TaskGrantBinding, + ), + ( + "purpose", + "registry_purpose", + json!("other-purpose"), + FailedCheck::AccessProfile, ), - ("purpose", "registry_purpose", json!("other-purpose")), ( "requirement", "registry_grant_bounds", json!({"type":"evidence", "requirement":"urn:example:other"}), + FailedCheck::AccessProfile, ), ] { let mut claims = task_grant_claims(subject.clone()); @@ -1035,7 +1105,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(claims), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(check), ) .await; assert!(!name.is_empty()); @@ -1047,7 +1117,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(wrong_actor), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::ActorKind), ) .await; @@ -1057,7 +1127,7 @@ async fn task_grant_context_is_bound_before_selector_or_source_access() { &service, &access_token(expired), &request, - AuthorizationError::Unauthorized, + AuthorizationError::Unauthorized(FailedCheck::TaskGrantExpired), ) .await; @@ -1101,6 +1171,16 @@ async fn prepare_service(write_source_secret: bool) -> PreparedService { async fn prepare_service_for_actor( write_source_secret: bool, profile_actor: Option<&str>, +) -> PreparedService { + prepare_service_with_ceiling(write_source_secret, profile_actor, None).await +} + +/// `ceiling` is the actor kinds and audiences, as YAML flow sequence bodies, +/// that every requirement's package grant ceiling admits. +async fn prepare_service_with_ceiling( + write_source_secret: bool, + profile_actor: Option<&str>, + ceiling: Option<(&str, &str)>, ) -> PreparedService { let temporary = tempfile::tempdir().expect("temporary selector conformance root"); let root = temporary @@ -1130,6 +1210,16 @@ async fn prepare_service_for_actor( ) .unwrap(); } + if let Some((actor_kinds, audiences)) = ceiling { + let config_path = bundle_root.join("evidence.yaml"); + let config = fs::read_to_string(&config_path).unwrap(); + let marker = " purposes:\n"; + assert!(config.contains(marker)); + let block = format!( + " grantCeiling:\n authorities: [statutory, organizational, consent, delegated, explicit-request]\n actorKinds: [{actor_kinds}]\n valueOrigins: [authenticated-context, authenticated-grant, request]\n audiences: [{audiences}]\n{marker}" + ); + fs::write(&config_path, config.replace(marker, &block)).unwrap(); + } write_secret(&secret_root, "audit-key", AUDIT_KEY); write_secret(&secret_root, "binding-key", BINDING_KEY); write_secret(&secret_root, "signing-key", EVIDENCE_PRIVATE_JWK.as_bytes()); @@ -1379,9 +1469,9 @@ async fn assert_authorization_error( let stage = match first { Ok(_) => "authorized", Err(AuthorizationStageError::Authentication) => "authentication", - Err(AuthorizationStageError::Authorization(AuthorizationError::Unauthorized)) => { - "unauthorized" - } + Err(AuthorizationStageError::Authorization(AuthorizationError::Unauthorized( + check, + ))) => check.as_str(), Err(AuthorizationStageError::Authorization(AuthorizationError::Selector)) => "selector", Err(AuthorizationStageError::Authorization(AuthorizationError::AmbiguousAuthority)) => { "ambiguous-authority" diff --git a/crates/registry-evidence/tests/source_authority_paths.rs b/crates/registry-evidence/tests/source_authority_paths.rs index dbe54eb5e8..ce6121b941 100644 --- a/crates/registry-evidence/tests/source_authority_paths.rs +++ b/crates/registry-evidence/tests/source_authority_paths.rs @@ -323,7 +323,7 @@ impl Write for RecordingSink { impl RecordingSink { fn audit(&self) -> EvidenceAuditLog { EvidenceAuditLog::with_writer( - AuditWriter::from_line_sink(Box::new(self.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(self.clone())), b"source-authority-audit-key-32-bytes".to_vec(), 1, ) diff --git a/crates/registry-evidence/tests/token_characterisation.rs b/crates/registry-evidence/tests/token_characterisation.rs new file mode 100644 index 0000000000..0b30c348d2 --- /dev/null +++ b/crates/registry-evidence/tests/token_characterisation.rs @@ -0,0 +1,224 @@ +//! Characterises Evidence's access-token authentication against the shared +//! token fixture corpus in `products/platform/conformance/tokens`. +//! +//! Every row of `expected.yaml` with an `evidence` cell runs through +//! `Authenticator::from_config`, the constructor the server calls, with the +//! issuer key set served over HTTP from a loopback listener. The row's +//! configuration is expressed through the bundle's own authentication members. +//! +//! `Authenticator::authenticate` collapses every verifier refusal into one +//! error, so the refusal stage is named by a second verifier built from the +//! same bundle members. It is consulted only after the real authenticator has +//! refused, and a disagreement between the two fails the test. + +use std::{collections::HashSet, sync::Arc, time::Duration}; + +use axum::{routing::get, Json, Router}; +use jsonwebtoken::{jwk::JwkSet, Algorithm}; +use registry_evidence::{ + auth::{AuthenticationError, Authenticator}, + config::{ + AccessTokenAlgorithm, AccessTokenType, AdmissionGate, AuthenticationConfig, EvidenceConfig, + OidcAuthenticationConfig, + }, +}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_config::JwksSource; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig, TokenVerifier, TokenVerifierConfig}; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, Stage, TokenCorpus, TokenSigner, +}; +use registry_platform_yaml::{BoundedU64, UniqueList, Url}; +use serde_json::Value; + +/// The audience the product under test is configured with. +const PRODUCT_AUDIENCE: &str = "evidence-fixture"; + +/// The client the `default` configuration admits when a fixture names none, +/// and the scope the `recipe` configuration requires when a fixture carries +/// none. +const FALLBACK_CLIENT: &str = "journey-app"; +const FALLBACK_SCOPE: &str = "records:get"; + +/// The bundle Evidence's own acceptance tests start from. +const STARTER_BUNDLE: &str = + "../../products/evidence/fixtures/acceptance/adult-status/evidence.yaml"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +fn fixture_client(case: &FixtureCase) -> Option { + literal_string(case, "client_id").or_else(|| literal_string(case, "azp")) +} + +/// The first scope the fixture carries, read from `scope` or `scp`. +fn first_scope(case: &FixtureCase) -> Option { + case.fixture + .read_scope("scope") + .or_else(|| case.fixture.read_scope("scp")) +} + +fn unique(values: Vec) -> UniqueList { + UniqueList::new(values).expect("the values are distinct") +} + +/// The algorithm Evidence is configured with for the row: the fixture's own +/// where Evidence admits it, and the starter's otherwise. +fn configured_algorithm(case: &FixtureCase) -> AccessTokenAlgorithm { + match case + .fixture + .header + .as_ref() + .map(|header| header.alg.as_str()) + { + Some("RS256") => AccessTokenAlgorithm::RS256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::ES256, + } +} + +fn row_config(case: &FixtureCase, jwks_uri: &str) -> OidcAuthenticationConfig { + let bundle = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(STARTER_BUNDLE); + let bytes = std::fs::read(&bundle).expect("the starter bundle is readable"); + let mut config = EvidenceConfig::parse_yaml(&bytes) + .expect("the starter bundle parses") + .authentication + .oidc; + config.provider.issuer = Url::new(&case.issuer).expect("the issuer is a URL"); + config.provider.audience = case.audience.clone(); + config.provider.jwks_source = JwksSource::Uri { + uri: Url::new(jwks_uri).expect("the key set location is a URL"), + }; + config.provider.allow_insecure_http = true; + config.token_types = vec![AccessTokenType::AtJwt]; + config.algorithms = vec![configured_algorithm(case)]; + config.maximum_token_lifetime_seconds = + BoundedU64::new(86_400).expect("the day is within the lifetime bounds"); + let client = fixture_client(case); + config.allowed_clients = match (case.configuration, client) { + (Configuration::Default, client) => AdmissionGate::listed(unique(vec![ + client.unwrap_or_else(|| FALLBACK_CLIENT.to_owned()) + ])), + (_, Some(client)) => AdmissionGate::listed(unique(vec![client])), + (_, None) => AdmissionGate::unrestricted(), + }; + config.required_scopes = match case.configuration { + Configuration::Default => AdmissionGate::unrestricted(), + _ => AdmissionGate::listed(unique(vec![ + first_scope(case).unwrap_or_else(|| FALLBACK_SCOPE.to_owned()) + ])), + }; + config +} + +/// Serve the signer's public key set from a loopback listener and return the +/// origin, which doubles as the issuer. +async fn serve_key_set(key_set: Value) -> String { + let app = Router::new().route( + "/jwks.json", + get(move || { + let key_set = key_set.clone(); + async move { Json(key_set) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("a loopback port is free"); + let port = listener + .local_addr() + .expect("the listener has an address") + .port(); + tokio::spawn(async move { + axum::serve(listener, app) + .await + .expect("the key set server runs for the test"); + }); + format!("http://127.0.0.1:{port}") +} + +/// The stage at which the shared verifier refuses the token under the row's +/// bundle members, or `None` when it admits it. +async fn verifier_refusal(config: &OidcAuthenticationConfig, case: &FixtureCase) -> Option { + let jwks: JwkSet = serde_json::from_value(case.jwks.clone()).expect("the key set parses"); + let algorithms: Vec = config + .algorithms + .iter() + .map(|algorithm| algorithm.to_jsonwebtoken()) + .collect(); + let verifier = TokenVerifier::new( + TokenVerifierConfig::access_token_profile( + config.issuer().to_owned(), + vec![config.audience().to_owned()], + algorithms, + vec!["at+jwt".to_owned()], + ) + .with_denied_kids(HashSet::new()) + .with_max_token_lifetime(Some(Duration::from_secs( + config.maximum_token_lifetime_seconds.get(), + ))) + .with_allowed_clients(config.allowed_clients.admitted()), + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ); + let error = verifier.verify(case.token.expose()).await.err()?; + match Outcome::refused_by(&error) { + Outcome::Refused(stage) => Some(stage), + other => panic!("the verifier error {error:?} is not a refusal: {other:?}"), + } +} + +async fn authenticate(case: FixtureCase, key_set_uri: String) -> Outcome { + let config = row_config(&case, &key_set_uri); + let authenticator = Authenticator::from_config( + &AuthenticationConfig { + oidc: config.clone(), + }, + Vec::new(), + ); + match authenticator.authenticate(case.token.expose()).await { + Ok(context) => Outcome::Admitted(Some(context.actor_kind().as_str().to_owned())), + Err(AuthenticationError::Malformed) => Outcome::Refused(Stage::Header), + Err(AuthenticationError::Context(_) | AuthenticationError::SenderConstrained) => { + Outcome::Refused(Stage::Claims) + } + Err(AuthenticationError::Verification(check)) => { + match verifier_refusal(&config, &case).await { + Some(stage) => Outcome::Refused(stage), + None => { + assert!( + !config.required_scopes.admitted().is_empty(), + "the authenticator refused a token the verifier admits and no scope gate is set" + ); + assert_eq!( + check, + FailedCheck::Scope, + "a token the verifier admits is refused by the scope gate" + ); + Outcome::Refused(Stage::Scope) + } + } + } + } +} + +#[tokio::test] +async fn evidence_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let origin = serve_key_set(signer.public_key_set()).await; + let key_set_uri = format!("{origin}/jwks.json"); + let report = corpus + .run_product_async("evidence", &signer, &origin, PRODUCT_AUDIENCE, |case| { + authenticate(case, key_set_uri.clone()) + }) + .await + .expect("the corpus runs for evidence"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran through Evidence" + ); + report.assert_matches(); +} diff --git a/crates/registry-evidencectl/Cargo.toml b/crates/registry-evidencectl/Cargo.toml index ffd6ce7d80..b4691acb4c 100644 --- a/crates/registry-evidencectl/Cargo.toml +++ b/crates/registry-evidencectl/Cargo.toml @@ -41,6 +41,7 @@ registry-cli-api.workspace = true registry-cli-reference.workspace = true registry-platform-crypto.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-loopback.workspace = true registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling.workspace = true diff --git a/crates/registry-evidencectl/src/authoring.rs b/crates/registry-evidencectl/src/authoring.rs index c12d206463..e4afc75579 100644 --- a/crates/registry-evidencectl/src/authoring.rs +++ b/crates/registry-evidencectl/src/authoring.rs @@ -2260,7 +2260,10 @@ mod tests { .expect("a reviewed SQLite extract route opens no production channel"); } - fn assert_authentication_diagnostic(bundle: &Value, artifacts: &BTreeMap>) { + fn assert_authentication_mismatch_refused( + bundle: &Value, + artifacts: &BTreeMap>, + ) { let error = validate_source_authentication(bundle, artifacts) .expect_err("a pack and target that name different authentication must be refused"); let diagnostic = error @@ -2291,7 +2294,7 @@ mod tests { ); let artifacts = direct_http_pack(json!({"type": "static-authorization"})); - assert_authentication_diagnostic(&bundle, &artifacts); + assert_authentication_mismatch_refused(&bundle, &artifacts); } #[test] diff --git a/crates/registry-evidencectl/src/client.rs b/crates/registry-evidencectl/src/client.rs index e206112c86..b516bb3732 100644 --- a/crates/registry-evidencectl/src/client.rs +++ b/crates/registry-evidencectl/src/client.rs @@ -413,6 +413,9 @@ fn validate_base_url(url: &Url, allow_local_loopback: bool) -> Result<()> { } } +/// Exactly `127.0.0.1`, the only loopback address a client profile accepts +/// for local-loopback discovery, so a profile written here is one the client +/// library reads back. fn is_loopback_host(host: url::Host<&str>) -> bool { match host { url::Host::Ipv4(address) => address == std::net::Ipv4Addr::LOCALHOST, diff --git a/crates/registry-evidencectl/src/doctor.rs b/crates/registry-evidencectl/src/doctor.rs index 2f8880bdbd..5ff52b66b2 100644 --- a/crates/registry-evidencectl/src/doctor.rs +++ b/crates/registry-evidencectl/src/doctor.rs @@ -38,6 +38,7 @@ use std::{ use anyhow::{anyhow, Context, Result}; use clap::Args; use registry_platform_audit::{AuditDestination, AuditDestinationKind}; +use registry_platform_config::{SecretError, SecretProvider, SecretReference, SecretResolver}; use serde::{Deserialize, Serialize}; use serde_norway::Value as YamlValue; @@ -306,40 +307,52 @@ fn check_secrets( } else if !metadata.is_dir() { root_run.refuse(&root, "is not a directory".to_owned()); } else if metadata.permissions().mode() & 0o077 != 0 { + // Evidence's own startup refuses a root group or other can reach, + // whatever the secret-file rule accepts below it. root_run.refuse(&root, group_or_other(&metadata, 0o700)); } } + // The runtime's own resolver judges each file, so this check gives the + // verdict the runtime would give. A secret file's rule is the shared one, + // stated by `SecretFileCheck`. + // The runtime requires an absolute root. A relative one in the file is + // read from the directory this check runs in, as the other files are. + let absolute_root = std::path::absolute(&root).unwrap_or_else(|_| root.clone()); + let resolver = match SecretResolver::new([SecretProvider::File], &absolute_root) { + Ok(resolver) => resolver, + Err(error) => { + root_run.refuse(&root, describe_secret_refusal(&error)); + return vec![root_run.finish()]; + } + }; let mut secret_run = CheckRun::new("secrets", project); for name in references { let path = root.join(&name); - let Some(metadata) = secret_run.stat(&path) else { - continue; - }; - if metadata.file_type().is_symlink() || !metadata.is_file() { - secret_run.refuse( - &path, - "is not a regular file reached without traversing a symbolic link".to_owned(), - ); - continue; + secret_run.inspected += 1; + let verdict = SecretReference::parse(format!("secret:file/{name}")) + .and_then(|reference| resolver.inspect_reference(&reference)); + if let Err(error) = verdict { + secret_run.refuse(&path, describe_secret_refusal(&error)); } - // Secrets are the one artifact the runtime pins to an exact mode - // rather than to a bound, so report the exact mode back. - let mode = metadata.permissions().mode() & 0o7777; - if !matches!(mode, 0o400 | 0o600) { - secret_run.refuse( - &path, - format!( - "has mode {mode:04o}; the runtime requires exactly 0400 or 0600 (chmod 400 or 600)" - ), - ); - } - require_sole_owner(&mut secret_run, &path, &metadata); } vec![root_run.finish(), secret_run.finish()] } +/// What a secret file's refusal says: the check, its code, and the fix. +fn describe_secret_refusal(error: &SecretError) -> String { + match error { + SecretError::UnsafeFile(check) => format!( + "{} ({}); {}", + check.message(), + check.code(), + check.suggested_action() + ), + other => format!("cannot be resolved: {other}; {}", other.suggested_action()), + } +} + /// The signer this deployment declares, and what settling it needs beyond this /// walk. /// diff --git a/crates/registry-evidencectl/src/suggest/fetch.rs b/crates/registry-evidencectl/src/suggest/fetch.rs index ba4eff9cde..04d68eea4e 100644 --- a/crates/registry-evidencectl/src/suggest/fetch.rs +++ b/crates/registry-evidencectl/src/suggest/fetch.rs @@ -114,8 +114,10 @@ pub fn check_url(value: &str) -> Result { match url.scheme() { "https" => {} "http" => match url.host() { - Some(Host::Ipv4(address)) if address.is_loopback() => {} - Some(Host::Ipv6(address)) if address.is_loopback() => {} + Some(Host::Ipv4(address)) + if registry_platform_loopback::loopback_address(address.into()) => {} + Some(Host::Ipv6(address)) + if registry_platform_loopback::loopback_address(address.into()) => {} _ => { return Err(safe_url_refusal( "evidence.openapi.url-insecure", @@ -211,3 +213,30 @@ pub fn get(url: &Url, max_bytes: u64) -> Result { String::from_utf8(body).with_context(|| format!("decoding the document at {url} as UTF-8")) } + +#[cfg(test)] +mod tests { + use super::check_url; + + #[test] + fn plain_http_follows_the_shared_loopback_rule_for_numeric_hosts() { + for (host, accepted) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", false), + ("LOCALHOST", false), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + check_url(&format!("http://{host}:4010/openapi.json")).is_ok(), + accepted, + "{host}" + ); + } + } +} diff --git a/crates/registry-evidencectl/src/suggest/mod.rs b/crates/registry-evidencectl/src/suggest/mod.rs index e2f3259d91..7ec71886f3 100644 --- a/crates/registry-evidencectl/src/suggest/mod.rs +++ b/crates/registry-evidencectl/src/suggest/mod.rs @@ -404,7 +404,9 @@ fn validate_base_url(raw: &str) -> Result { bail!("an HTTP --base-url must use a numeric loopback address") } }; - if !ip.is_loopback() || parsed.port().is_none_or(|port| port == 0) { + if !registry_platform_loopback::loopback_address(ip) + || parsed.port().is_none_or(|port| port == 0) + { bail!("an HTTP --base-url must use a numeric loopback address and non-zero port"); } } @@ -1695,6 +1697,24 @@ fn missing_flags_message(args: &SuggestArgs) -> String { mod tests { use super::validate_base_url; + #[test] + fn http_source_origins_follow_the_shared_loopback_rule_for_numeric_hosts() { + for (origin, accepted) in [ + ("http://127.0.0.1:4010", true), + ("http://127.0.0.2:4010", true), + ("http://[::1]:4010", true), + ("http://[::ffff:7f00:1]:4010", true), + ("http://localhost:4010", false), + ("http://LOCALHOST:4010", false), + ("http://a.localhost:4010", false), + ("http://localhost.:4010", false), + ("http://10.0.0.1:4010", false), + ("http://example.com:4010", false), + ] { + assert_eq!(validate_base_url(origin).is_ok(), accepted, "{origin}"); + } + } + #[test] fn json_runs_never_prompt() { assert!(!super::prompts_allowed(crate::OutputFormat::Json)); diff --git a/crates/registry-evidencectl/tests/doctor.rs b/crates/registry-evidencectl/tests/doctor.rs index da1030de28..f16c013e5c 100644 --- a/crates/registry-evidencectl/tests/doctor.rs +++ b/crates/registry-evidencectl/tests/doctor.rs @@ -272,7 +272,8 @@ fn doctor_accepts_only_the_runtime_owner_only_secret_modes() { ); assert!( diagnostics.contains("secrets/audit-hmac-key") - && diagnostics.contains("requires exactly 0400 or 0600"), + && diagnostics.contains("platform.secret-file.") + && diagnostics.contains("0400 or 0600"), "doctor did not report unsupported secret mode {mode:04o}:\n{diagnostics}" ); } diff --git a/crates/registry-mcp-edge/Cargo.toml b/crates/registry-mcp-edge/Cargo.toml index d3a5fc7675..5ba528192d 100644 --- a/crates/registry-mcp-edge/Cargo.toml +++ b/crates/registry-mcp-edge/Cargo.toml @@ -26,7 +26,7 @@ async-trait.workspace = true axum.workspace = true http.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true @@ -47,7 +47,7 @@ zeroize.workspace = true [dev-dependencies] base64.workspace = true -registry-platform-testing = { workspace = true, features = ["test-authorization-server"] } +registry-platform-testing = { workspace = true, features = ["test-authorization-server", "token-fixtures"] } reqwest.workspace = true tokio.workspace = true tower.workspace = true diff --git a/crates/registry-mcp-edge/src/audit.rs b/crates/registry-mcp-edge/src/audit.rs index 4474eb8a26..3c355b1c78 100644 --- a/crates/registry-mcp-edge/src/audit.rs +++ b/crates/registry-mcp-edge/src/audit.rs @@ -102,10 +102,12 @@ impl ToolAuditLog { } } - Self::new(AuditWriter::from_line_sink(Box::new(RefusingSink { - accepted, - writes: Arc::new(Mutex::new(0)), - }))) + Self::new(AuditWriter::from_line_sink_without_posture(Box::new( + RefusingSink { + accepted, + writes: Arc::new(Mutex::new(0)), + }, + ))) } } diff --git a/crates/registry-mcp-edge/src/compatibility_tests/audit.rs b/crates/registry-mcp-edge/src/compatibility_tests/audit.rs index c253f7b607..36718e005c 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/audit.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/audit.rs @@ -26,7 +26,7 @@ impl Write for Buffer { fn fixture() -> (ToolAuditLog, AuditWriter, Buffer, AuditOptions) { let buffer = Buffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); ( ToolAuditLog::new(writer.clone()), writer, diff --git a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs index 8d21fc9124..b96548dd2b 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/inbound.rs @@ -1,10 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{ - io::{self, Write}, - sync::{Arc, Mutex}, - time::Duration, -}; +use std::{sync::Arc, time::Duration}; use axum::{ body::Body, @@ -14,12 +10,13 @@ use axum::{ Router, }; use registry_platform_audit::AuditProfile; +use registry_platform_authcommon::FailedCheck; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ access_token_typ_set, is_access_token_typ_pair, Claims, JwksFetcher, JwksFetcherConfig, OidcError, VerifiedToken, }; -use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use registry_platform_testing::{CapturedDiagnosticLogs, TestAuthorizationServer, TestClient}; use serde_json::{json, Value}; use tower::ServiceExt; use url::Url; @@ -27,8 +24,8 @@ use zeroize::Zeroizing; use crate::{ inbound::{metadata_url, require_caller, retry_after_seconds, Refusal}, - token_verifier, AccessTokenAlgorithm, RateLimitOptions, ResourceServer, ResourceServerOptions, - TokenBucketOptions, VerifiedCaller, + token_verifier, AccessTokenAlgorithm, RateLimitOptions, ResourceServer, ResourceServerError, + ResourceServerOptions, TokenBucketOptions, VerifiedCaller, }; const RESOURCE: &str = "https://gateway.example.test/mcp"; @@ -36,37 +33,6 @@ const CHAT_HOST: &str = "chat-host"; const SCOPE: &str = "address-correction:self"; const METADATA: &str = "https://gateway.example.test/.well-known/oauth-protected-resource/mcp"; -#[derive(Clone, Default)] -struct CapturedLogs(Arc>>); - -impl Write for CapturedLogs { - fn write(&mut self, bytes: &[u8]) -> io::Result { - self.0 - .lock() - .expect("log buffer lock") - .extend_from_slice(bytes); - Ok(bytes.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs { - type Writer = Self; - - fn make_writer(&'writer self) -> Self::Writer { - self.clone() - } -} - -impl CapturedLogs { - fn text(&self) -> String { - String::from_utf8(self.0.lock().expect("log buffer lock").clone()).expect("UTF-8 logs") - } -} - fn now() -> i64 { i64::try_from( std::time::SystemTime::now() @@ -116,7 +82,7 @@ fn resource_server_for( let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( authorization.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); Arc::new( ResourceServer::new( @@ -189,7 +155,7 @@ async fn the_authored_resource_is_the_exact_audience_and_metadata_identifier() { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( auth.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = token_verifier(&options, fetcher); @@ -433,9 +399,15 @@ async fn every_refusal_is_a_problem_document() { let auth = authorization_server().await; let server = resource_server_for(&auth, 10, 10); let cases = [ - (Refusal::Missing, 401, "Unauthorized", "unauthorized", true), ( - Refusal::InvalidToken, + Refusal::Missing(FailedCheck::CredentialMissing), + 401, + "Unauthorized", + "unauthorized", + true, + ), + ( + Refusal::InvalidToken(FailedCheck::TokenAudience), 401, "Unauthorized", "invalid-token", @@ -473,7 +445,7 @@ async fn every_refusal_is_a_problem_document() { ), ]; for (refusal, status, title, code, challenged) in cases { - let response = server.refusal_response(refusal); + let response = server.refuse(refusal); assert_eq!(response.status().as_u16(), status, "{code}"); assert_eq!( response.headers().get(header::CONTENT_TYPE), @@ -506,14 +478,9 @@ async fn every_refusal_is_a_problem_document() { #[tokio::test(flavor = "current_thread")] async fn an_unreachable_key_set_is_the_operators_failure() { - let logs = CapturedLogs::default(); - let subscriber = tracing_subscriber::fmt() - .json() - .without_time() - .with_max_level(tracing::Level::TRACE) - .with_writer(logs.clone()) - .finish(); - let _capture = tracing::subscriber::set_default(subscriber); + let logs = CapturedDiagnosticLogs::default(); + let _capture = + tracing::dispatcher::set_default(&logs.subscriber_with_max_level(tracing::Level::TRACE)); let auth = authorization_server().await; let token = auth.issue_access_token(CHAT_HOST, "citizen-a", RESOURCE, SCOPE, now() + 300); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -533,7 +500,7 @@ async fn an_unreachable_key_set_is_the_operators_failure() { Arc::new(JwksFetcher::new_with_fetch_url_policy( closed, JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), ), hasher(), @@ -553,13 +520,31 @@ async fn an_unreachable_key_set_is_the_operators_failure() { let router = Router::new() .route("/mcp", post(|| async { "ok" })) .layer(axum::middleware::from_fn_with_state(server, require_caller)); + // Another test thread, with no subscriber of its own, may reach the + // refusal line first. A capture that is the only registered dispatcher + // then never sees that line, so this test reaches it first on purpose + // and relies on the shared capture to keep it enabled here. + let elsewhere = resource_server_for(&auth, 10, 10); + std::thread::spawn(move || { + assert_eq!( + elsewhere.refuse(Refusal::KeySource).status(), + StatusCode::SERVICE_UNAVAILABLE + ); + }) + .join() + .expect("a thread without a subscriber refuses"); assert_eq!( call(&router, Some(&token)).await.status(), StatusCode::SERVICE_UNAVAILABLE ); let logs = logs.text(); + let refusals: Vec<&str> = logs + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(refusals.len(), 1, "{logs}"); assert!( - logs.contains("the access-token key set is unavailable"), + refusals[0].contains("\"failed_check\":\"key-source-unavailable\""), "{logs}" ); assert!(!logs.contains("citizen-a"), "{logs}"); @@ -592,6 +577,37 @@ fn retry_after_rounds_up_to_whole_seconds() { assert_eq!(retry_after_seconds(Duration::from_secs(7)), 7); } +#[tokio::test] +async fn only_the_loopback_forms_are_a_development_resource_and_issuer() { + let auth = authorization_server().await; + for host in [ + "127.0.0.1", + "127.0.0.2", + "[::1]", + "LOCALHOST", + "[::ffff:127.0.0.1]", + ] { + let mut options = options(&auth); + options.resource = format!("http://{host}:8095/mcp"); + options.issuer = format!("http://{host}:8096"); + assert_eq!(options.validate(), Ok(()), "{host}"); + } + for host in [ + "localhost.", + "app.localhost", + "10.0.0.1", + "[::ffff:10.0.0.1]", + ] { + let mut options = options(&auth); + options.resource = format!("http://{host}:8095/mcp"); + assert_eq!( + options.validate(), + Err(ResourceServerError::Resource), + "{host}" + ); + } +} + #[tokio::test] async fn localhost_is_a_development_loopback_resource_and_issuer() { let auth = authorization_server().await; @@ -608,7 +624,7 @@ async fn a_token_that_already_names_an_actor_is_refused() { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( auth.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let server = ResourceServer::new( &options, @@ -636,15 +652,53 @@ async fn a_token_that_already_names_an_actor_is_refused() { matched_client: Some(format!("client_id:{CHAT_HOST}")), scopes: vec![SCOPE.to_owned()], }; - assert!(server.caller_for_test(&delegated, "token").is_err()); + assert_eq!( + server.caller_for_test(&delegated, "token").err(), + Some(Refusal::InvalidToken(FailedCheck::Delegation)) + ); + claims + .extra + .insert("may_act".to_owned(), json!({"sub": "x"})); claims.extra.remove("act"); - claims.sub = None; - let anonymous = VerifiedToken { - claims, + let may_act = VerifiedToken { + claims: claims.clone(), matched_client: Some(format!("client_id:{CHAT_HOST}")), scopes: vec![SCOPE.to_owned()], }; - assert!(server.caller_for_test(&anonymous, "token").is_err()); + assert_eq!( + server.caller_for_test(&may_act, "token").err(), + Some(Refusal::InvalidToken(FailedCheck::Delegation)) + ); + claims.extra.remove("may_act"); + let verified = |claims: Claims, matched_client: Option| VerifiedToken { + claims, + matched_client, + scopes: vec![SCOPE.to_owned()], + }; + let matched = || Some(format!("client_id:{CHAT_HOST}")); + + let mut anonymous = claims.clone(); + anonymous.sub = None; + assert_eq!( + server + .caller_for_test(&verified(anonymous, matched()), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClaims)) + ); + assert_eq!( + server + .caller_for_test(&verified(claims.clone(), None), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClient)) + ); + let mut unbounded = claims; + unbounded.exp = None; + assert_eq!( + server + .caller_for_test(&verified(unbounded, matched()), "token") + .err(), + Some(Refusal::InvalidToken(FailedCheck::TokenClaims)) + ); } #[test] diff --git a/crates/registry-mcp-edge/src/compatibility_tests/server.rs b/crates/registry-mcp-edge/src/compatibility_tests/server.rs index 73b78e7f60..8beab704d1 100644 --- a/crates/registry-mcp-edge/src/compatibility_tests/server.rs +++ b/crates/registry-mcp-edge/src/compatibility_tests/server.rs @@ -67,7 +67,9 @@ fn gateway_core() -> Arc { ["unused".to_owned()], ) .expect("binding"); - let audit = ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(io::sink()))); + let audit = ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + io::sink(), + ))); Arc::new( GatewayCore::new( [binding], @@ -101,7 +103,7 @@ async fn application(resource: &str) -> Router { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( authorization.jwks_uri(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let profile = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![8; 32])).expect("profile"); diff --git a/crates/registry-mcp-edge/src/config.rs b/crates/registry-mcp-edge/src/config.rs index 0506bb1a07..a32e32650a 100644 --- a/crates/registry-mcp-edge/src/config.rs +++ b/crates/registry-mcp-edge/src/config.rs @@ -11,10 +11,9 @@ use registry_platform_audit::{ use registry_platform_config::{ AuditKeyConfig, ConfigBlockError, JwksSource, SecretProvidersConfig, SecretReference, }; -use registry_platform_httputil::{valid_resource_uri, valid_scope_token}; +use registry_platform_httputil::{loopback::loopback_host, valid_resource_uri, valid_scope_token}; use registry_platform_yaml::{BoundedU32, BoundedU64, ExternalId, Invalid, UniqueList, Url}; use serde::{de, Deserialize, Deserializer}; -use url::Host; pub use crate::AccessTokenAlgorithm; use crate::{ResourceServerOptions, MCP_PATH}; @@ -206,23 +205,19 @@ pub enum ResourceServerConfigError { fn protected_endpoint(url: &url::Url, development_loopback: bool) -> bool { url.host().is_some() && (url.scheme() == "https" - || development_loopback && url.scheme() == "http" && loopback_host(url)) + || development_loopback && url.scheme() == "http" && is_loopback(url)) } fn issuer_endpoint(url: &url::Url, development_loopback: bool, allow_insecure_http: bool) -> bool { url.host().is_some() && (url.scheme() == "https" || url.scheme() == "http" - && (allow_insecure_http || development_loopback && loopback_host(url))) + && (allow_insecure_http || development_loopback && is_loopback(url))) } -fn loopback_host(url: &url::Url) -> bool { - match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - None => false, - } +fn is_loopback(url: &url::Url) -> bool { + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn default_scope_claim() -> ExternalId { @@ -541,6 +536,37 @@ mod tests { assert!(config.validate(true, &secret_providers()).is_empty()); } + #[test] + fn development_loopback_admits_only_the_loopback_forms() { + for host in ["127.0.0.2", "[::1]", "LOCALHOST", "[::ffff:127.0.0.1]"] { + let mut config = resource_server(); + config.resource = Url::new(format!("http://{host}:8110/mcp")).expect("resource"); + config.issuer = Url::new(format!("http://{host}:8111")).expect("issuer"); + assert!( + config.validate(true, &secret_providers()).is_empty(), + "{host}" + ); + } + for host in ["localhost.", "app.localhost", "10.0.0.1"] { + let mut config = resource_server(); + config.resource = Url::new(format!("http://{host}:8110/mcp")).expect("resource"); + config.issuer = Url::new(format!("http://{host}:8111")).expect("issuer"); + let errors = config.validate(true, &secret_providers()); + assert!( + errors + .iter() + .any(|error| matches!(error, ResourceServerConfigError::InsecureResource)), + "{host}" + ); + assert!( + errors + .iter() + .any(|error| matches!(error, ResourceServerConfigError::InsecureIssuer)), + "{host}" + ); + } + } + #[test] fn authored_resource_validation_reports_the_mcp_path_and_static_secret() { let mut config = resource_server(); diff --git a/crates/registry-mcp-edge/src/inbound.rs b/crates/registry-mcp-edge/src/inbound.rs index 99eaaeb6c1..682185d760 100644 --- a/crates/registry-mcp-edge/src/inbound.rs +++ b/crates/registry-mcp-edge/src/inbound.rs @@ -1,6 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{collections::HashSet, fmt, sync::Arc, time::Duration}; +use std::{ + collections::HashSet, + fmt, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; use axum::{ body::Body, @@ -10,7 +15,11 @@ use axum::{ response::Response, }; use registry_platform_audit::AuditKeyHasher; -use registry_platform_authcommon::{parse_bearer_token, BearerParseError}; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, +}; +use registry_platform_httputil::loopback::loopback_host; pub use registry_platform_oidc::AccessTokenAlgorithm; use registry_platform_oidc::{ access_token_typ_set, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, VerifiedToken, @@ -19,13 +28,17 @@ use registry_platform_ratelimit::token_bucket::{ TokenBucketConfig, TokenBucketError, TokenBucketLimiter, }; use serde_json::{json, Value}; -use url::{Host, Url}; +use url::Url; use zeroize::Zeroizing; use crate::server::{problem, METADATA_PREFIX}; const MAXIMUM_TOKEN_LIFETIME: Duration = Duration::from_secs(86_400); +/// The least time between two log lines for a request the gateway could not +/// admit because of its own fault. +const ADMIT_FAULT_LOG_WINDOW: Duration = Duration::from_secs(60); + /// Complete product-neutral inbound resource-server settings. #[derive(Clone, Debug)] pub struct ResourceServerOptions { @@ -223,10 +236,12 @@ impl CallerContext<'_> { } } +/// What the edge answers, and for the answers that carry a check, the check +/// that failed. The check is operator-side only and never reaches a response. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum Refusal { - Missing, - InvalidToken, + Missing(FailedCheck), + InvalidToken(FailedCheck), InsufficientScope, KeySource, RateLimited { retry_after_seconds: u64 }, @@ -245,6 +260,18 @@ pub struct ResourceServer { challenge: String, scope_challenge: String, metadata: Value, + refusals: Arc, + /// When the gateway last logged that it could not admit a request, and + /// how many requests failed the same way since. + admit_fault_logged: Mutex, + /// The configured claim and scopes a scope refusal line names. + declared_scope: DeclaredScope, +} + +#[derive(Default)] +struct AdmitFaultLog { + logged: Option, + suppressed: u64, } #[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] @@ -257,6 +284,8 @@ pub enum ResourceServerError { Options, #[error("the {0} rate limit is not usable")] RateLimit(&'static str), + #[error("the refusal recorder is not usable")] + Recorder, } impl ResourceServer { @@ -278,6 +307,8 @@ impl ResourceServer { .map_err(|_| ResourceServerError::RateLimit("perPrincipal"))?; let per_client = limiter(limits.per_client).map_err(|_| ResourceServerError::RateLimit("perClient"))?; + let refusals = + Arc::new(RefusalRecorder::new("mcp_edge").map_err(|_| ResourceServerError::Recorder)?); let metadata = json!({ "resource": options.resource.as_str(), "authorization_servers": [options.issuer.as_str()], @@ -297,9 +328,20 @@ impl ResourceServer { challenge, scope_challenge, metadata, + refusals, + admit_fault_logged: Mutex::new(AdmitFaultLog::default()), + declared_scope: DeclaredScope::new(&options.scope_claim) + .with_required_scope(options.required_scopes.join(" ")), }) } + /// Counts every refusal by the check that failed. The edge has no metrics + /// listener, so the counter is read in tests and the log line is the + /// operator's signal. + pub(crate) const fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + #[must_use] pub const fn metadata(&self) -> &Value { &self.metadata @@ -310,19 +352,16 @@ impl ResourceServer { &self, verified: &VerifiedToken, token: &str, - ) -> Result { - self.caller(verified, token).map_err(|_| ()) + ) -> Result { + self.caller(verified, token) } async fn authenticate(&self, headers: &HeaderMap) -> Result { let token = bearer_token(headers)?; let verified = match self.verifier.verify(token).await { Ok(verified) => verified, - Err(error) if is_key_source_failure(&error) => { - tracing::warn!("the access-token key set is unavailable"); - return Err(Refusal::KeySource); - } - Err(_) => return Err(Refusal::InvalidToken), + Err(error) if is_key_source_failure(&error) => return Err(Refusal::KeySource), + Err(error) => return Err(Refusal::InvalidToken(error.failed_check())), }; let caller = self.caller(&verified, token)?; admit(&self.per_principal, caller.principal_pseudonym()).await?; @@ -333,19 +372,21 @@ impl ResourceServer { fn caller(&self, verified: &VerifiedToken, token: &str) -> Result { let claims = &verified.claims; if claims.extra.contains_key("act") || claims.extra.contains_key("may_act") { - return Err(Refusal::InvalidToken); + return Err(Refusal::InvalidToken(FailedCheck::Delegation)); } let subject = claims .sub .as_deref() .filter(|subject| !subject.is_empty()) - .ok_or(Refusal::InvalidToken)?; + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClaims))?; let client = verified .matched_client_id() .ok() .flatten() - .ok_or(Refusal::InvalidToken)?; - let expires_at = claims.exp.ok_or(Refusal::InvalidToken)?; + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClient))?; + let expires_at = claims + .exp + .ok_or(Refusal::InvalidToken(FailedCheck::TokenClaims))?; let present: HashSet<&str> = verified.scopes.iter().map(String::as_str).collect(); if !self .required_scopes @@ -370,10 +411,48 @@ impl ResourceServer { .map_err(|_| Refusal::Unavailable) } - pub(crate) fn refusal_response(&self, refusal: Refusal) -> Response { + /// Counts and logs the refusal, then builds its answer. + pub(crate) fn refuse(&self, refusal: Refusal) -> Response { + match refusal.failed_check() { + Some(check) => record_refusal!( + self.refusals, + RefusalNote::new(check), + declared = Some(&self.declared_scope) + ), + // The gateway could not derive a pseudonym or run its limiter. + // That is a fault of this service, not a check a caller failed. + None => { + if let Some(suppressed) = self.admit_fault_due(Instant::now()) { + tracing::error!(suppressed, "the gateway could not admit a request"); + } + } + } + self.refusal_response(refusal) + } + + /// `Some` at most once per `ADMIT_FAULT_LOG_WINDOW`, so a limiter that has + /// reached its capacity cannot write a line for every request. The value + /// is how many requests failed the same way since the last line. + fn admit_fault_due(&self, now: Instant) -> Option { + let mut log = self + .admit_fault_logged + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if log + .logged + .is_some_and(|logged| now.saturating_duration_since(logged) < ADMIT_FAULT_LOG_WINDOW) + { + log.suppressed = log.suppressed.saturating_add(1); + return None; + } + log.logged = Some(now); + Some(std::mem::take(&mut log.suppressed)) + } + + fn refusal_response(&self, refusal: Refusal) -> Response { let (status, challenge) = match refusal { - Refusal::Missing => (StatusCode::UNAUTHORIZED, Some(self.challenge.clone())), - Refusal::InvalidToken => ( + Refusal::Missing(_) => (StatusCode::UNAUTHORIZED, Some(self.challenge.clone())), + Refusal::InvalidToken(_) => ( StatusCode::UNAUTHORIZED, Some( self.challenge @@ -445,9 +524,8 @@ fn valid_issuer_url(url: &Url, allow_insecure_http: bool) -> bool { } fn loopback(url: &Url) -> bool { - matches!(url.host(), Some(Host::Ipv4(ip)) if ip.is_loopback()) - || matches!(url.host(), Some(Host::Ipv6(ip)) if ip.is_loopback()) - || matches!(url.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost")) + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn limiter(options: TokenBucketOptions) -> Result { @@ -458,10 +536,22 @@ fn limiter(options: TokenBucketOptions) -> Result Option { + match self { + Self::Missing(check) | Self::InvalidToken(check) => Some(check), + Self::InsufficientScope => Some(FailedCheck::Scope), + Self::KeySource => Some(FailedCheck::KeySourceUnavailable), + Self::RateLimited { .. } => Some(FailedCheck::RateLimit), + Self::Unavailable => None, + } + } + const fn code(self) -> &'static str { match self { - Self::Missing => "unauthorized", - Self::InvalidToken => "invalid-token", + Self::Missing(_) => "unauthorized", + Self::InvalidToken(_) => "invalid-token", Self::InsufficientScope => "insufficient-scope", Self::KeySource | Self::Unavailable => "temporarily-unavailable", Self::RateLimited { .. } => "rate-limited", @@ -470,8 +560,8 @@ impl Refusal { const fn detail(self) -> &'static str { match self { - Self::Missing => "A bearer access token is required.", - Self::InvalidToken => "The access token is not valid for this resource.", + Self::Missing(_) => "A bearer access token is required.", + Self::InvalidToken(_) => "The access token is not valid for this resource.", Self::InsufficientScope => "The access token lacks a required scope.", Self::KeySource | Self::Unavailable => { "The gateway cannot verify the request right now." @@ -492,7 +582,7 @@ pub(crate) async fn require_caller( request.extensions_mut().insert(Arc::new(caller)); next.run(request).await } - Err(refusal) => server.refusal_response(refusal), + Err(refusal) => server.refuse(refusal), } } @@ -516,14 +606,19 @@ pub(crate) fn retry_after_seconds(retry_after: Duration) -> u64 { fn bearer_token(headers: &HeaderMap) -> Result<&str, Refusal> { let mut values = headers.get_all(header::AUTHORIZATION).iter(); - let value = values.next().ok_or(Refusal::Missing)?; + let value = values + .next() + .ok_or(Refusal::Missing(FailedCheck::CredentialMissing))?; if values.next().is_some() { - return Err(Refusal::InvalidToken); + return Err(Refusal::InvalidToken(FailedCheck::CredentialMalformed)); } - let value = value.to_str().map_err(|_| Refusal::InvalidToken)?; + let value = value + .to_str() + .map_err(|_| Refusal::InvalidToken(FailedCheck::CredentialMalformed))?; parse_bearer_token(value).map_err(|error| match error { - BearerParseError::Malformed | BearerParseError::InvalidScheme => Refusal::Missing, - _ => Refusal::InvalidToken, + BearerParseError::InvalidScheme => Refusal::Missing(FailedCheck::CredentialMissing), + BearerParseError::Malformed => Refusal::Missing(FailedCheck::CredentialMalformed), + _ => Refusal::InvalidToken(FailedCheck::CredentialMalformed), }) } @@ -572,3 +667,6 @@ fn is_key_source_failure(error: &OidcError) -> bool { | OidcError::MissingIssuer ) } + +#[cfg(test)] +mod refusal_tests; diff --git a/crates/registry-mcp-edge/src/inbound/refusal_tests.rs b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs new file mode 100644 index 0000000000..9cd57e10d1 --- /dev/null +++ b/crates/registry-mcp-edge/src/inbound/refusal_tests.rs @@ -0,0 +1,548 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Every refusal the edge answers, driven through the real router. The golden +//! file freezes the status, the headers a client can read and the body of each +//! answer. + +use std::{collections::BTreeMap, io, sync::Arc, time::Duration}; + +use async_trait::async_trait; +use axum::{ + body::Body, + http::{header, HeaderName, HeaderValue, Request, StatusCode}, + Router, +}; +use registry_platform_audit::{AuditProfile, AuditWriter}; +use registry_platform_authcommon::FailedCheck; +use registry_platform_httputil::{client::StaticToken, FetchUrlPolicy}; +use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{TestAuthorizationServer, TestClient}; +use rmcp::model::Tool; +use serde_json::{json, Value}; +use tower::ServiceExt; +use url::Url; +use zeroize::Zeroizing; + +use crate::{ + router, token_verifier, AccessTokenAlgorithm, AuditOptions, EffectCertainty, + FixedAuthorizationFactory, GatewayCore, GatewayInfo, Invocation, Provider, + ProviderAuthorization, ProviderBinding, ProviderFailure, ProviderOutcome, RateLimitOptions, + ResolvedTool, ResourceServer, ResourceServerOptions, ServerOptions, TokenBucketOptions, + ToolAuditLog, VerifiedCaller, +}; + +const RESOURCE: &str = "https://gateway.example.test/mcp"; +const HOST: &str = "gateway.example.test"; +const CLIENT: &str = "chat-host"; +const SCOPE: &str = "test:read"; +const GOLDEN: &str = include_str!("../../tests/golden/refusals.json"); +const GOLDEN_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/golden/refusals.json"); + +struct UnusedProvider; + +#[async_trait] +impl Provider for UnusedProvider { + fn resolve_tool(&self, name: &str) -> Option { + (name == "unused") + .then(|| ResolvedTool::new("unused", "test", "unused", "v1").expect("identity")) + } + + async fn list_tools( + &self, + _: &VerifiedCaller, + _: ProviderAuthorization, + ) -> Result, ProviderFailure> { + Ok(Vec::new()) + } + + async fn invoke( + &self, + _: &VerifiedCaller, + _: ProviderAuthorization, + _: Invocation<'_>, + ) -> ProviderOutcome { + ProviderOutcome::failure(ProviderFailure::new( + "unused", + "Unused.", + EffectCertainty::NoEffect, + )) + } +} + +fn gateway_core() -> Arc { + let token = StaticToken::new("test-only-static-token").expect("token"); + let binding = ProviderBinding::new( + Arc::new(UnusedProvider), + Arc::new(FixedAuthorizationFactory::new(Arc::new(token))), + ["unused".to_owned()], + ) + .expect("binding"); + let audit = ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + io::sink(), + ))); + Arc::new( + GatewayCore::new( + [binding], + audit, + AuditOptions::new("registry-test-mcp.tool-call/v1", "test_mcp.tool_call") + .expect("audit"), + GatewayInfo::new("test-mcp", "Test", "Test").expect("info"), + ) + .expect("core"), + ) +} + +fn now() -> i64 { + i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_secs(), + ) + .expect("time fits") +} + +async fn authorization() -> TestAuthorizationServer { + TestAuthorizationServer::builder() + .client(TestClient::new(CLIENT)) + .client(TestClient::new("another-host")) + .start() + .await +} + +/// The real edge router over a verifier that reads `jwks_uri`. +pub(super) fn application( + authorization: &TestAuthorizationServer, + jwks_uri: String, + burst: u32, +) -> (Router, Arc) { + let options = ResourceServerOptions { + resource: RESOURCE.to_owned(), + issuer: authorization.issuer(), + allow_insecure_http: false, + algorithms: vec![AccessTokenAlgorithm::EdDSA], + allowed_clients: vec![CLIENT.to_owned()], + required_scopes: vec![SCOPE.to_owned()], + scope_claim: "scope".to_owned(), + maximum_token_lifetime: Duration::from_secs(300), + resource_name: "Test".to_owned(), + principal_audit_namespace: "test-principal-v1".to_owned(), + client_audit_namespace: "test-client-v1".to_owned(), + }; + let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )); + let profile = + AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![8; 32])).expect("profile"); + let bucket = TokenBucketOptions { + requests_per_minute: 1, + burst, + }; + let resource_server = Arc::new( + ResourceServer::new( + &options, + token_verifier(&options, fetcher), + profile.key_hasher(), + RateLimitOptions { + per_principal: bucket, + per_client: bucket, + }, + ) + .expect("resource server"), + ); + let app = router( + gateway_core(), + Arc::clone(&resource_server), + &ServerOptions { + resource: Url::parse(RESOURCE).expect("resource URL"), + maximum_request_bytes: 4096, + hsts: false, + }, + ); + (app, resource_server) +} + +pub(super) type Headers = Vec<(HeaderName, HeaderValue)>; + +pub(super) fn request(headers: Headers) -> Request { + let mut request = Request::post("/mcp") + .header(header::HOST, HOST) + .header(header::ACCEPT, "application/json, text/event-stream"); + for (name, value) in headers { + request = request.header(name, value); + } + request.body(Body::empty()).expect("request") +} + +pub(super) fn authorization_header(value: &str) -> (HeaderName, HeaderValue) { + ( + header::AUTHORIZATION, + HeaderValue::from_str(value).expect("header value"), + ) +} + +pub(super) fn bearer(token: &str) -> Headers { + vec![authorization_header(&format!("Bearer {token}"))] +} + +/// The answers and, per case, the checks its refusal counted. +#[derive(Default)] +struct Run { + answers: BTreeMap<&'static str, Value>, + counted: BTreeMap<&'static str, BTreeMap<&'static str, u64>>, +} + +impl Run { + /// Sends one request to a server that has served nothing else, so the + /// counter holds this request's refusal alone. + async fn observe( + &mut self, + name: &'static str, + (app, server): &(Router, Arc), + headers: Headers, + ) { + let mut answer = summarise( + app.clone() + .oneshot(request(headers)) + .await + .expect("response"), + ) + .await; + settle_retry_after(&mut answer); + self.record(name, server, answer); + } + + fn record(&mut self, name: &'static str, server: &ResourceServer, answer: Value) { + let counted = FailedCheck::ALL + .iter() + .filter_map(|check| { + let count = server + .refusal_recorder() + .counter() + .get(&[check.as_str()]) + .expect("every check is a declared series"); + (count > 0).then_some((check.as_str(), count)) + }) + .collect(); + self.answers.insert(name, answer); + self.counted.insert(name, counted); + } +} + +/// The limiter holds one request per minute, so the delay it advertises is +/// the minute less however long the fixture took between its two requests, +/// rounded up. Any delay from one to sixty seconds is recorded as sixty so a +/// slow runner does not change the frozen answer. +fn settle_retry_after(answer: &mut Value) { + let Some(header) = answer["headers"].get_mut("retry-after") else { + return; + }; + let seconds: u64 = header + .as_str() + .and_then(|text| text.parse().ok()) + .expect("retry-after is whole seconds"); + assert!((1..=60).contains(&seconds), "retry-after {seconds}"); + *header = Value::from("60"); +} + +/// One name per refusal the edge can answer, with the answer it gives. +async fn drive() -> Run { + let auth = authorization().await; + let fresh = || application(&auth, auth.jwks_uri(), 100); + let issue = |client: &str, audience: &str, scope: &str, exp: i64| { + auth.issue_access_token(client, "citizen-a", audience, scope, exp) + }; + let mut run = Run::default(); + + run.observe("no-authorization-header", &fresh(), vec![]) + .await; + run.observe( + "non-bearer-scheme", + &fresh(), + vec![authorization_header("Basic abc")], + ) + .await; + run.observe( + "bearer-without-token", + &fresh(), + vec![authorization_header("Bearer")], + ) + .await; + run.observe( + "bearer-with-two-spaces", + &fresh(), + vec![authorization_header("Bearer a")], + ) + .await; + run.observe( + "repeated-authorization-header", + &fresh(), + vec![ + authorization_header("Bearer a"), + authorization_header("Bearer b"), + ], + ) + .await; + run.observe( + "unreadable-authorization-header", + &fresh(), + vec![( + header::AUTHORIZATION, + HeaderValue::from_bytes(b"Bearer \xff").expect("opaque header"), + )], + ) + .await; + run.observe("not-a-jwt", &fresh(), bearer("not-a-compact-token")) + .await; + run.observe( + "wrong-audience", + &fresh(), + bearer(&issue(CLIENT, "urn:elsewhere", SCOPE, now() + 300)), + ) + .await; + run.observe( + "client-not-allowed", + &fresh(), + bearer(&issue("another-host", RESOURCE, SCOPE, now() + 300)), + ) + .await; + run.observe( + "empty-subject", + &fresh(), + bearer(&auth.issue_access_token(CLIENT, "", RESOURCE, SCOPE, now() + 300)), + ) + .await; + run.observe( + "expired", + &fresh(), + bearer(&issue(CLIENT, RESOURCE, SCOPE, now() - 120)), + ) + .await; + run.observe( + "scope-missing", + &fresh(), + bearer(&issue(CLIENT, RESOURCE, "openid", now() + 300)), + ) + .await; + + let (app, server) = fresh(); + let response = app + .clone() + .oneshot( + Request::post("/mcp") + .header(header::HOST, "attacker.example.test") + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + run.record("host-not-admitted", &server, summarise(response).await); + run.observe( + "origin-present", + &fresh(), + vec![( + header::ORIGIN, + HeaderValue::from_static("https://elsewhere.example.test"), + )], + ) + .await; + + let token = issue(CLIENT, RESOURCE, SCOPE, now() + 300); + let limited = application(&auth, auth.jwks_uri(), 1); + let first = limited + .0 + .clone() + .oneshot(request(bearer(&token))) + .await + .expect("response"); + assert_ne!(first.status(), StatusCode::TOO_MANY_REQUESTS); + run.observe("rate-limited", &limited, bearer(&token)).await; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let closed = format!( + "http://{}/jwks.json", + listener.local_addr().expect("address") + ); + drop(listener); + run.observe( + "key-set-unreachable", + &application(&auth, closed, 100), + bearer(&token), + ) + .await; + run +} + +async fn summarise(response: axum::response::Response) -> Value { + let status = response.status(); + let mut readable = BTreeMap::new(); + for name in [ + header::CONTENT_TYPE, + header::CACHE_CONTROL, + header::WWW_AUTHENTICATE, + header::RETRY_AFTER, + ] { + if let Some(value) = response.headers().get(&name) { + readable.insert( + name.as_str().to_owned(), + value.to_str().expect("ASCII header").to_owned(), + ); + } + } + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .expect("body"); + let body: Value = serde_json::from_slice(&bytes).expect("a problem document"); + json!({"status": status.as_u16(), "headers": readable, "body": body}) +} + +#[tokio::test(flavor = "current_thread")] +async fn every_refusal_answers_exactly_as_the_golden_file_records() { + let answers = serde_json::to_value(drive().await.answers).expect("answers serialize"); + if std::env::var_os("REGISTRY_MCP_EDGE_WRITE_GOLDEN").is_some() { + let mut text = serde_json::to_string_pretty(&answers).expect("golden text"); + text.push('\n'); + std::fs::write(GOLDEN_PATH, text).expect("the golden file is written"); + } + let golden: Value = serde_json::from_str(GOLDEN).expect("the golden file is JSON"); + assert_eq!(answers, golden); +} + +/// The check each refusal counts, one request each. +const COUNTED: [(&str, &str); 16] = [ + ("no-authorization-header", "credential-missing"), + ("non-bearer-scheme", "credential-missing"), + ("bearer-without-token", "credential-malformed"), + ("bearer-with-two-spaces", "credential-malformed"), + ("repeated-authorization-header", "credential-malformed"), + ("unreadable-authorization-header", "credential-malformed"), + ("not-a-jwt", "credential-malformed"), + ("wrong-audience", "token-audience"), + ("client-not-allowed", "token-client"), + ("empty-subject", "token-claims"), + ("expired", "token-time"), + ("scope-missing", "scope"), + ("host-not-admitted", "host-origin"), + ("origin-present", "host-origin"), + ("rate-limited", "rate-limit"), + ("key-set-unreachable", "key-source-unavailable"), +]; + +#[tokio::test(flavor = "current_thread")] +async fn each_refusal_counts_once_under_its_check() { + let run = drive().await; + assert_eq!(run.counted.len(), COUNTED.len()); + for (name, check) in COUNTED { + assert_eq!(run.counted[name], BTreeMap::from([(check, 1)]), "{name}"); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn a_refused_host_writes_one_line_with_its_check() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let logs = CapturedDiagnosticLogs::default(); + let auth = authorization().await; + let (app, _) = application(&auth, auth.jwks_uri(), 100); + let response = app + .oneshot( + Request::post("/mcp") + .header(header::HOST, "attacker.example.test") + .body(Body::empty()) + .expect("request"), + ) + .with_subscriber(logs.subscriber()) + .await + .expect("response"); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let text = logs.text(); + let lines: Vec<&str> = text + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(lines.len(), 1, "{text}"); + assert!( + lines[0].contains("\"failed_check\":\"host-origin\""), + "{text}" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn a_refusal_writes_one_line_with_its_check_and_no_caller_value() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + + let logs = CapturedDiagnosticLogs::default(); + let auth = authorization().await; + let token = auth.issue_access_token(CLIENT, "citizen-canary", RESOURCE, "openid", now() + 300); + let (app, _) = application(&auth, auth.jwks_uri(), 100); + let response = app + .oneshot(request(bearer(&token))) + .with_subscriber(logs.subscriber()) + .await + .expect("response"); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let text = logs.text(); + let lines: Vec<&str> = text + .lines() + .filter(|line| line.contains("request refused")) + .collect(); + assert_eq!(lines.len(), 1, "{text}"); + assert!(lines[0].contains("\"failed_check\":\"scope\""), "{text}"); + // The line names what the operator declared, never the token's scopes. + assert!(lines[0].contains("\"scope_claim\":\"scope\""), "{text}"); + assert!( + lines[0].contains(&format!("\"required_scope\":\"{SCOPE}\"")), + "{text}" + ); + for canary in [token.as_str(), "citizen-canary", CLIENT, "openid"] { + assert!(!text.contains(canary), "{canary} reached the log: {text}"); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn the_admit_fault_line_is_due_once_per_window() { + let auth = authorization().await; + let (_, server) = application(&auth, auth.jwks_uri(), 100); + let start = std::time::Instant::now(); + assert_eq!(server.admit_fault_due(start), Some(0)); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(30)), + None + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(59)), + None + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(61)), + Some(2) + ); + assert_eq!( + server.admit_fault_due(start + Duration::from_secs(130)), + Some(0) + ); +} + +#[test] +fn a_retry_after_from_one_to_sixty_seconds_is_frozen_as_sixty() { + for seconds in ["1", "59", "60"] { + let mut answer = json!({"headers": {"retry-after": seconds}}); + settle_retry_after(&mut answer); + assert_eq!(answer["headers"]["retry-after"], "60"); + } + let mut none = json!({"headers": {}}); + settle_retry_after(&mut none); + assert_eq!(none, json!({"headers": {}})); +} + +#[test] +#[should_panic(expected = "retry-after 61")] +fn a_retry_after_beyond_the_refill_period_is_refused() { + settle_retry_after(&mut json!({"headers": {"retry-after": "61"}})); +} diff --git a/crates/registry-mcp-edge/src/lib.rs b/crates/registry-mcp-edge/src/lib.rs index 88b5ba9fbc..440576b7e9 100644 --- a/crates/registry-mcp-edge/src/lib.rs +++ b/crates/registry-mcp-edge/src/lib.rs @@ -43,3 +43,6 @@ mod tests; #[cfg(test)] mod compatibility_tests; + +#[cfg(test)] +mod token_characterisation; diff --git a/crates/registry-mcp-edge/src/server.rs b/crates/registry-mcp-edge/src/server.rs index fc9c83e50e..ba478b8a20 100644 --- a/crates/registry-mcp-edge/src/server.rs +++ b/crates/registry-mcp-edge/src/server.rs @@ -11,7 +11,10 @@ use axum::{ routing::get, Json, Router, }; -use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder, Problem}; +use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote, RefusalRecorder}; +use registry_platform_httpsec::{ + request_body_limit, security_headers_without_posture, CspBuilder, Problem, +}; use rmcp::transport::streamable_http_server::{ session::never::NeverSessionManager, StreamableHttpServerConfig, StreamableHttpService, }; @@ -79,16 +82,23 @@ impl ResourceAuthority { } } +/// The host and origin check, with the recorder that counts its refusals. +struct HostGate { + authority: Option, + refusals: Arc, +} + async fn require_resource_host( - State(authority): State>>, + State(gate): State>, request: Request, next: Next, ) -> Response { - let admitted = authority - .as_ref() + let admitted = gate + .authority .as_ref() .is_some_and(|authority| authority.admits(request.uri(), request.headers())); if !admitted || request.headers().contains_key(header::ORIGIN) { + record_refusal!(gate.refusals, RefusalNote::new(FailedCheck::HostOrigin)); return forbidden(); } next.run(request).await @@ -118,7 +128,10 @@ pub fn router( require_caller, )) .layer(from_fn_with_state( - Arc::new(ResourceAuthority::of(&options.resource)), + Arc::new(HostGate { + authority: ResourceAuthority::of(&options.resource), + refusals: Arc::clone(resource_server.refusal_recorder()), + }), require_resource_host, )); let metadata_path = format!("{METADATA_PREFIX}{MCP_PATH}"); @@ -128,7 +141,7 @@ pub fn router( .route(METADATA_PREFIX, get(metadata)) .route(&metadata_path, get(metadata)) .with_state(resource_server); - let headers = security_headers(CspBuilder::restrictive()); + let headers = security_headers_without_posture(CspBuilder::restrictive()); let headers = if options.hsts { headers } else { diff --git a/crates/registry-mcp-edge/src/tests.rs b/crates/registry-mcp-edge/src/tests.rs index e322f12c20..83ee149a09 100644 --- a/crates/registry-mcp-edge/src/tests.rs +++ b/crates/registry-mcp-edge/src/tests.rs @@ -260,7 +260,9 @@ fn delegation() -> Delegation { fn audit() -> (ToolAuditLog, Buffer) { let buffer = Buffer::default(); ( - ToolAuditLog::new(AuditWriter::from_line_sink(Box::new(buffer.clone()))), + ToolAuditLog::new(AuditWriter::from_line_sink_without_posture(Box::new( + buffer.clone(), + ))), buffer, ) } diff --git a/crates/registry-mcp-edge/src/token_characterisation.rs b/crates/registry-mcp-edge/src/token_characterisation.rs new file mode 100644 index 0000000000..5512ac82f4 --- /dev/null +++ b/crates/registry-mcp-edge/src/token_characterisation.rs @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterises which identity-provider tokens the MCP edge's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row builds a resource server from the public options and verifier +//! constructor the product hosts use, mounts the `require_caller` layer the +//! edge router applies, and sends the fixture as a bearer credential. The +//! layer answers a refusal with a status that names no check, so the check is +//! read from a second verifier built by the same public `token_verifier` +//! constructor over the same key set. + +use std::{sync::Arc, time::Duration}; + +use axum::{ + body::Body, + http::{header, Request, StatusCode}, + routing::post, + Router, +}; +use registry_platform_audit::AuditProfile; +use registry_platform_oidc::{parse_static_jwks, JwksFetcher, JwksFetcherConfig, TokenVerifier}; +use registry_platform_testing::{ + ClaimValue, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::Value; +use tower::ServiceExt; +use zeroize::Zeroizing; + +use crate::{ + inbound::require_caller, token_verifier, AccessTokenAlgorithm, RateLimitOptions, + ResourceServer, ResourceServerError, ResourceServerOptions, TokenBucketOptions, +}; + +const ISSUER: &str = "https://issuer.example.test"; +const RESOURCE: &str = "https://gateway.example.test/mcp"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +fn first_scope(fixture: &TokenFixture) -> Option { + fixture.read_scope("scope") +} + +/// The algorithm the fixture declares, when the edge can be configured with +/// it. A symmetric or absent algorithm leaves the edge on RS256, which then +/// refuses the token at the algorithm check. +fn algorithm_of(fixture: &TokenFixture) -> AccessTokenAlgorithm { + match fixture.header.as_ref().map(|header| header.alg.as_str()) { + Some("ES256") => AccessTokenAlgorithm::ES256, + Some("EdDSA") => AccessTokenAlgorithm::EdDSA, + _ => AccessTokenAlgorithm::RS256, + } +} + +fn options_for(case: &FixtureCase) -> ResourceServerOptions { + ResourceServerOptions { + resource: case.audience.clone(), + issuer: case.issuer.clone(), + allow_insecure_http: false, + algorithms: vec![algorithm_of(&case.fixture)], + allowed_clients: vec![client_of(&case.fixture).unwrap_or_else(|| PLACEHOLDER_CLIENT.into())], + required_scopes: vec![ + first_scope(&case.fixture).unwrap_or_else(|| PLACEHOLDER_SCOPE.into()) + ], + scope_claim: "scope".to_owned(), + maximum_token_lifetime: Duration::from_secs(3600), + resource_name: "Token characterisation".to_owned(), + principal_audit_namespace: "principal-v1".to_owned(), + client_audit_namespace: "client-v1".to_owned(), + } +} + +/// A static key document admits RSA and EC keys only, so the corpus's EdDSA +/// key is left out. +fn fetcher_for(case: &FixtureCase) -> Arc { + let mut keys = case.jwks.clone(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + Arc::new(JwksFetcher::new_static( + parse_static_jwks(keys.to_string().as_bytes()).expect("the corpus key set parses"), + JwksFetcherConfig::defaults(), + )) +} + +async fn observe(case: &FixtureCase) -> Outcome { + let options = options_for(case); + let hasher = AuditProfile::production_from_secret_bytes(Zeroizing::new(vec![5; 32])) + .expect("audit profile") + .key_hasher(); + let server = match ResourceServer::new( + &options, + token_verifier(&options, fetcher_for(case)), + hasher, + RateLimitOptions { + per_principal: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, + }, + per_client: TokenBucketOptions { + requests_per_minute: 60, + burst: 1000, + }, + }, + ) { + Ok(server) => Arc::new(server), + // The edge serves one MCP path, so an audience that is not an `/mcp` + // URL cannot be configured. + Err(ResourceServerError::Resource) => return Outcome::None, + Err(error) => panic!("the resource server builds: {error:?}"), + }; + let router = Router::new() + .route("/mcp", post(|| async { "ok" })) + .layer(axum::middleware::from_fn_with_state(server, require_caller)); + let token = case.token.expose(); + let response = router + .oneshot( + Request::post("/mcp") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + let probe: TokenVerifier = token_verifier(&options, fetcher_for(case)); + let verdict = probe.verify(token).await; + match (response.status(), verdict) { + (StatusCode::OK, Ok(_)) => Outcome::Admitted(None), + (StatusCode::OK, Err(_)) => panic!("the edge admitted a token its verifier refused"), + (_, Err(error)) => Outcome::refused_by(&error), + (StatusCode::FORBIDDEN, Ok(_)) => "refused/scope".parse().expect("result value"), + (StatusCode::UNAUTHORIZED, Ok(_)) => "refused/claims".parse().expect("result value"), + (StatusCode::SERVICE_UNAVAILABLE, Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + (status, Ok(_)) => panic!("the edge answered the unexpected status {status}"), + } +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("mcp-edge", &signer, ISSUER, RESOURCE, |case| async move { + observe(&case).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-mcp-edge/tests/golden/refusals.json b/crates/registry-mcp-edge/tests/golden/refusals.json new file mode 100644 index 0000000000..08cc728546 --- /dev/null +++ b/crates/registry-mcp-edge/tests/golden/refusals.json @@ -0,0 +1,239 @@ +{ + "bearer-with-two-spaces": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "bearer-without-token": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "client-not-allowed": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "empty-subject": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "expired": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "host-not-admitted": { + "body": { + "code": "forbidden", + "detail": "The request's host or origin is not accepted.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "key-set-unreachable": { + "body": { + "code": "temporarily-unavailable", + "detail": "The gateway cannot verify the request right now.", + "status": 503, + "title": "Service Unavailable", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 503 + }, + "no-authorization-header": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "non-bearer-scheme": { + "body": { + "code": "unauthorized", + "detail": "A bearer access token is required.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "not-a-jwt": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "origin-present": { + "body": { + "code": "forbidden", + "detail": "The request's host or origin is not accepted.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "rate-limited": { + "body": { + "code": "rate-limited", + "detail": "Too many requests; retry after the indicated delay.", + "status": 429, + "title": "Too Many Requests", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "60" + }, + "status": 429 + }, + "repeated-authorization-header": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "scope-missing": { + "body": { + "code": "insufficient-scope", + "detail": "The access token lacks a required scope.", + "status": 403, + "title": "Forbidden", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"insufficient_scope\", scope=\"test:read\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 403 + }, + "unreadable-authorization-header": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + }, + "wrong-audience": { + "body": { + "code": "invalid-token", + "detail": "The access token is not valid for this resource.", + "status": 401, + "title": "Unauthorized", + "type": "about:blank" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer error=\"invalid_token\", resource_metadata=\"https://gateway.example.test/.well-known/oauth-protected-resource/mcp\"" + }, + "status": 401 + } +} diff --git a/crates/registry-mcp/src/adapter.rs b/crates/registry-mcp/src/adapter.rs index 016d3fa27e..8038d02f28 100644 --- a/crates/registry-mcp/src/adapter.rs +++ b/crates/registry-mcp/src/adapter.rs @@ -351,7 +351,7 @@ fn input_schema(operation: &Operation) -> Value { impl AdapterContract { fn loaded_bytes_checked(path: &std::path::Path) -> Result, AdapterContractLoadError> { - let loaded = registry_platform_config::RuntimeConfigLoader::new( + let loaded = registry_platform_config::RuntimeConfigLoader::new_without_posture( registry_platform_config::RuntimeEnvelope { api_version: "id.registrystack.org/formats/adapter/effective-contract/v1alpha1", kind: "AdapterEffectiveContract", @@ -1256,7 +1256,8 @@ async fn response_bytes( } else { "application/problem+json" }; - if registry_platform_httputil::validate_response_headers(response.headers()).is_err() + if registry_platform_httputil::validate_response_headers_without_peer_policy(response.headers()) + .is_err() || response .headers() .get("content-type") diff --git a/crates/registry-mcp/src/config.rs b/crates/registry-mcp/src/config.rs index dd621672ef..143765a8e3 100644 --- a/crates/registry-mcp/src/config.rs +++ b/crates/registry-mcp/src/config.rs @@ -10,13 +10,13 @@ use registry_platform_config::{ PrivateListenerConfig, RemovedKey, RuntimeConfigLoader, RuntimeEnvelope, SecretProvidersConfig, SecretReference, TlsTermination, MAX_OIDC_AUDIENCE_CHARACTERS, }; +use registry_platform_httputil::loopback::loopback_host; use registry_platform_yaml::{Diagnostic, Digest, LocalId, Report, UniqueList, Url}; use serde::Deserialize; use std::{ collections::BTreeSet, path::{Path, PathBuf}, }; -use url::Host; pub const API_VERSION: &str = "id.registrystack.org/formats/platform/mcp-runtime/v1alpha1"; pub const KIND: &str = "PlatformMcpRuntimeConfig"; @@ -149,7 +149,7 @@ pub struct DelegationConfig { impl RuntimeConfig { pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RuntimeEnvelope { + RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: API_VERSION, kind: KIND, }).removed_keys(&[RemovedKey { @@ -273,9 +273,7 @@ impl RuntimeConfig { let protected_endpoint = |url: url::Url| { registry_platform_httputil::client::ServiceBaseUrl::new(url.clone()).is_ok() && (url.scheme() == "https" - || (url.scheme() == "http" - && self.development_loopback() - && loopback_host(&url))) + || (url.scheme() == "http" && self.development_loopback() && is_loopback(&url))) }; if self .bindings @@ -602,13 +600,9 @@ impl RuntimeConfig { } } -fn loopback_host(url: &url::Url) -> bool { - match url.host() { - Some(Host::Ipv4(address)) => address.is_loopback(), - Some(Host::Ipv6(address)) => address.is_loopback(), - Some(Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"), - None => false, - } +fn is_loopback(url: &url::Url) -> bool { + url.host_str() + .is_some_and(|host| loopback_host(host).is_some()) } fn valid_digest(value: &str) -> bool { diff --git a/crates/registry-mcp/src/runtime.rs b/crates/registry-mcp/src/runtime.rs index 246a180084..af2e157323 100644 --- a/crates/registry-mcp/src/runtime.rs +++ b/crates/registry-mcp/src/runtime.rs @@ -17,7 +17,7 @@ use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::client::StaticToken; use registry_platform_oidc::{ fetch_discovery_for_issuer, parse_static_jwks, IssuerNetworkPolicy, JwksFetcher, - JwksFetcherConfig, OidcDiscoveryConfig, + JwksFetcherConfig, OidcDiscoveryConfig, OidcError, }; use std::{fmt, future::Future, io, sync::Arc, time::Duration}; use zeroize::Zeroizing; @@ -85,10 +85,33 @@ fn secret_failure(field: String, reference: &str, error: &SecretError) -> Startu ) } -fn invalid_secret_value(field: String, cause: &'static str, remedy: &'static str) -> StartupError { +fn invalid_secret_value( + field: String, + cause: impl Into, + remedy: &'static str, +) -> StartupError { startup_failure(field, cause, remedy) } +/// Reads the static key document. A refusal of the document's own contents +/// names what it refused, in words that carry no key material. +fn static_key_fetcher(bytes: &[u8], field: String) -> Result { + let keys = parse_static_jwks(bytes).map_err(|error| { + let cause = match &error { + OidcError::StaticKeySet(refused) => { + format!("the resolved secret is not a usable JWKS document: {refused}") + } + _ => "the resolved secret is not a usable JWKS document".to_owned(), + }; + invalid_secret_value( + field, + cause, + "Replace it with a bounded JSON Web Key Set containing the issuer's active verification keys.", + ) + })?; + Ok(JwksFetcher::new_static(keys, JwksFetcherConfig::defaults())) +} + fn audit_failure(error: AuditError) -> StartupError { startup_failure( "audit", @@ -172,20 +195,13 @@ pub async fn build(config: &RuntimeConfig) -> Result { JwksFetcherConfig::defaults(), policy.declared_jwks_fetch_policy(), ), - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let bytes = secret( &secrets, document_ref, "resourceServer.jwksSource.documentRef".to_owned(), )?; - let keys = parse_static_jwks(&bytes).map_err(|_| { - invalid_secret_value( - "resourceServer.jwksSource.documentRef".to_owned(), - "the resolved secret is not a usable JWKS document", - "Replace it with a bounded JSON Web Key Set containing the issuer's active verification keys.", - ) - })?; - JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) + static_key_fetcher(&bytes, "resourceServer.jwksSource.documentRef".to_owned())? } JwksSource::Discovery {} => { let (discovery, network) = fetch_discovery_for_issuer( @@ -419,7 +435,7 @@ pub async fn build(config: &RuntimeConfig) -> Result { ) })?; let audit = ToolAuditLog::new( - AuditWriter::open(destination) + AuditWriter::open_without_posture(destination) .await .map_err(audit_failure)?, ); @@ -499,6 +515,44 @@ mod tests { use super::*; + /// A public EC key as a provider publishes it, with members the verifier + /// does not read. + fn provider_key_set(extra: &str) -> Vec { + format!( + r#"{{"keys":[{{"kty":"EC","crv":"P-256","kid":"key-1","use":"sig","alg":"ES256","ext":true,"x5c":["MIIB"],"x5t":"abc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"{extra}}}]}}"# + ) + .into_bytes() + } + + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + static_key_fetcher(&provider_key_set(""), "field".to_owned()) + .expect("a provider key set with ext and x5c members loads"); + } + + #[test] + fn a_static_key_set_with_a_private_member_is_refused_with_the_validator_text() { + let Err(error) = static_key_fetcher( + &provider_key_set(r#","d":"CANARY-PRIVATE""#), + "field".to_owned(), + ) else { + panic!("a private member is refused"); + }; + let error = error.to_string(); + assert!( + error.contains("not a usable JWKS document"), + "the refusal says the key set is unusable" + ); + assert!( + error.contains("private-key member \"d\""), + "the refusal names the private-key member rule" + ); + assert!( + !error.contains("CANARY-PRIVATE"), + "the refusal holds the private member's value" + ); + } + #[test] fn missing_secret_and_malformed_key_have_distinct_value_free_guidance() { const CANARY_REFERENCE: &str = "secret:env/DO_NOT_PRINT_THIS_NAME"; diff --git a/crates/registry-messaging-client/src/client.rs b/crates/registry-messaging-client/src/client.rs index 3bf08b7110..3c174e5d45 100644 --- a/crates/registry-messaging-client/src/client.rs +++ b/crates/registry-messaging-client/src/client.rs @@ -15,7 +15,8 @@ use registry_platform_httputil::client::{ ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, retry_after_seconds, url::append_path_segments, validate_response_headers, + read_bounded, retry_after_seconds, url::append_path_segments, + validate_response_headers_without_peer_policy, }; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{Response, StatusCode, Url}; @@ -26,6 +27,8 @@ use crate::{MessagingClientConfig, MessagingClientError, MessagingProtocolFailur const JSON_MEDIA_TYPE: &str = "application/json"; const PROBLEM_MEDIA_TYPE: &str = "application/problem+json"; const MAXIMUM_PROBLEM_BYTES: u64 = 8 * 1024; +/// Longest `/health` or `/ready` body this client reads. +const MAXIMUM_PROBE_BYTES: u64 = 4096; /// Longest `Retry-After` wait, in whole seconds, this client reports on a /// 429 refusal. A daily limit clears as the profile's oldest counted @@ -82,14 +85,14 @@ impl MessagingClient { /// Whether the process answers at all. Liveness says nothing about the /// store; use `ready` for that. pub async fn health(&self) -> Result, MessagingClientError> { - self.get_empty(HEALTH_PATH).await + self.get_probe(HEALTH_PATH).await } /// Whether the runtime can serve: its store is reachable and carries /// exactly the schema this runtime expects. A runtime that is not ready /// answers the typed `ProblemCode::ServiceUnavailable`. pub async fn ready(&self) -> Result, MessagingClientError> { - self.get_empty(READY_PATH).await + self.get_probe(READY_PATH).await } /// Submit one message under `idempotency_key`. The runtime answers the @@ -265,7 +268,9 @@ impl MessagingClient { .map_err(|_| MessagingClientError::configuration("the service base URL is not usable")) } - async fn get_empty(&self, path: &str) -> Result, MessagingClientError> { + /// A probe answers 200 with an empty body or a JSON object; its + /// members are not read, the status code is the answer. + async fn get_probe(&self, path: &str) -> Result, MessagingClientError> { let url = self.url_from_constant(path)?; let response = self.send(self.http.get(url)).await?; let status = response.status(); @@ -273,18 +278,30 @@ impl MessagingClient { return Err(self.problem_or_status(response).await); } let trace_id = response_trace(status, response.headers())?; - let body = - read_bounded(response, 1) - .await - .map_err(|error| MessagingClientError::Transport { - kind: read_failure_kind(&error), - })?; + let json_media_type = exact_media_type(response.headers(), JSON_MEDIA_TYPE); + let body = read_bounded(response, MAXIMUM_PROBE_BYTES) + .await + .map_err(|error| MessagingClientError::Transport { + kind: read_failure_kind(&error), + })?; if !body.is_empty() { - return Err(protocol( - status, - MessagingProtocolFailure::Body, - Some(trace_id), - )); + if !json_media_type { + return Err(protocol( + status, + MessagingProtocolFailure::MediaType, + Some(trace_id), + )); + } + if !matches!( + serde_json::from_slice::(&body), + Ok(serde_json::Value::Object(_)) + ) { + return Err(protocol( + status, + MessagingProtocolFailure::Body, + Some(trace_id), + )); + } } Ok(MessagingComplete { value: (), @@ -373,7 +390,7 @@ impl MessagingClient { .map_err(|error| MessagingClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), MessagingProtocolFailure::HeaderBounds, diff --git a/crates/registry-messaging-client/tests/http_boundary.rs b/crates/registry-messaging-client/tests/http_boundary.rs index 78237b2408..42687123f6 100644 --- a/crates/registry-messaging-client/tests/http_boundary.rs +++ b/crates/registry-messaging-client/tests/http_boundary.rs @@ -613,13 +613,83 @@ async fn a_failure_that_is_not_a_problem_document_is_a_protocol_failure() { } #[tokio::test] -async fn a_success_with_a_body_is_a_protocol_failure() { +async fn a_success_with_a_body_that_is_not_json_is_a_protocol_failure() { let (client, server) = serve("", &Fixture::new(StatusCode::OK, None, "x")).await; assert!(matches!( client.health().await, Err(MessagingClientError::Protocol { status: 200, - failure: MessagingProtocolFailure::Body, + failure: MessagingProtocolFailure::MediaType, + .. + }) + )); + server.abort(); +} + +#[tokio::test] +async fn health_and_ready_accept_the_json_status_body() { + let health = Fixture::new( + StatusCode::OK, + Some("application/json"), + r#"{"status":"ok"}"#, + ); + let (client, server) = serve("", &health).await; + assert_eq!(client.health().await.expect("health").trace_id, TRACE_ID); + server.abort(); + + let ready = Fixture::new( + StatusCode::OK, + Some("application/json"), + r#"{"status":"ready","extra":[1,2]}"#, + ); + let (client, server) = serve("", &ready).await; + assert_eq!(client.ready().await.expect("ready").trace_id, TRACE_ID); + server.abort(); +} + +#[tokio::test] +async fn a_probe_body_over_the_bound_is_refused_as_too_large() { + let body = format!(r#"{{"status":"ok","padding":"{}"}}"#, "x".repeat(8 * 1024)); + let fixture = Fixture::new(StatusCode::OK, Some("application/json"), &body); + let (client, server) = serve("", &fixture).await; + assert!(matches!( + client.health().await, + Err(MessagingClientError::Transport { + kind: TransportKind::ResponseTooLarge, + }) + )); + server.abort(); +} + +#[tokio::test] +async fn a_probe_body_that_is_not_a_json_object_is_a_protocol_failure() { + for body in ["[]", "\"ok\"", "{"] { + let fixture = Fixture::new(StatusCode::OK, Some("application/json"), body); + let (client, server) = serve("", &fixture).await; + assert!( + matches!( + client.ready().await, + Err(MessagingClientError::Protocol { + status: 200, + failure: MessagingProtocolFailure::Body, + .. + }) + ), + "body {body}" + ); + server.abort(); + } +} + +#[tokio::test] +async fn a_probe_body_under_another_media_type_is_a_protocol_failure() { + let fixture = Fixture::new(StatusCode::OK, Some("text/plain"), r#"{"status":"ok"}"#); + let (client, server) = serve("", &fixture).await; + assert!(matches!( + client.health().await, + Err(MessagingClientError::Protocol { + status: 200, + failure: MessagingProtocolFailure::MediaType, .. }) )); diff --git a/crates/registry-messaging-core/src/access.rs b/crates/registry-messaging-core/src/access.rs index 1639ce5c7b..ac3c4616a5 100644 --- a/crates/registry-messaging-core/src/access.rs +++ b/crates/registry-messaging-core/src/access.rs @@ -370,6 +370,19 @@ impl AccessProfiles { self.profiles.values() } + /// The clients the profiles name, sorted and distinct. The runtime and + /// adopter tooling both derive the admitted clients from this one set. + #[must_use] + pub fn requester_clients(&self) -> Vec { + let mut clients: Vec = self + .iter() + .flat_map(|profile| profile.requester_clients.iter().cloned()) + .collect(); + clients.sort(); + clients.dedup(); + clients + } + #[must_use] pub fn is_empty(&self) -> bool { self.profiles.is_empty() diff --git a/crates/registry-messaging/Cargo.toml b/crates/registry-messaging/Cargo.toml index f94335976e..8b40642fbe 100644 --- a/crates/registry-messaging/Cargo.toml +++ b/crates/registry-messaging/Cargo.toml @@ -79,12 +79,12 @@ lettre.workspace = true registry-messaging-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-httputil.workspace = true registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true @@ -113,7 +113,7 @@ hex.workspace = true jsonschema.workspace = true rcgen.workspace = true registry-messaging-client.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins", "postgres-catalog"] } +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures", "postgres-catalog"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-messaging/migrations/0102_activation_posture.sql b/crates/registry-messaging/migrations/0102_activation_posture.sql new file mode 100644 index 0000000000..2d579e2254 --- /dev/null +++ b/crates/registry-messaging/migrations/0102_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE messaging_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE messaging_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-messaging/src/activation.rs b/crates/registry-messaging/src/activation.rs index c3fdebd605..82a97284bb 100644 --- a/crates/registry-messaging/src/activation.rs +++ b/crates/registry-messaging/src/activation.rs @@ -445,15 +445,15 @@ pub async fn apply( let activation = platform::append_activation( &*tx, &layout(), - &NewActivation { + &NewActivation::without_posture( activation_id, package_digest, database_id, - operator_reference_hash: operator_reference_hash.as_deref(), - backup_references: &request.backup_references, + operator_reference_hash.as_deref(), + &request.backup_references, role_mode, - runtime_role: None, - }, + None, + ), ) .await .map_err(platform_error)?; @@ -500,18 +500,24 @@ pub async fn check_runtime( ) -> Result { store.ready().await?; let client = store.client().await?; - let active = platform::check_active_package(&**client, &layout(), database_id, package_digest) - .await - .map_err(|error| match error { - platform::ActivePackageError::NotActivated => ActivationError::NotActivated, - platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, - platform::ActivePackageError::PackageNotActive { .. } => { - ActivationError::PackageNotActive - } - platform::ActivePackageError::Activation(error) => { - ActivationError::Store(platform_error(error)) - } - })?; + let active = platform::check_active_package_without_posture( + &**client, + &layout(), + database_id, + package_digest, + ) + .await + .map_err(|error| match error { + platform::ActivePackageError::NotActivated => ActivationError::NotActivated, + platform::ActivePackageError::DatabaseIdMismatch => ActivationError::DatabaseIdMismatch, + platform::ActivePackageError::PackageNotActive { .. } => ActivationError::PackageNotActive, + // Until this product declares a posture it checks as production, + // so a ledger recorded in development is not its active package. + platform::ActivePackageError::PostureMismatch { .. } => ActivationError::PackageNotActive, + platform::ActivePackageError::Activation(error) => { + ActivationError::Store(platform_error(error)) + } + })?; let role = platform::observe_role(&**client, &layout(), None, &[]) .await .map_err(platform_error)? diff --git a/crates/registry-messaging/src/audit.rs b/crates/registry-messaging/src/audit.rs index 23aec5fe39..8eae7b7159 100644 --- a/crates/registry-messaging/src/audit.rs +++ b/crates/registry-messaging/src/audit.rs @@ -187,7 +187,7 @@ pub(crate) mod tests { pub(crate) fn memory_journal() -> (Arc, MessagingAudit) { let sink = Arc::new(MemorySink::default()); - let writer = AuditWriter::from_line_sink(Box::new((*sink).clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new((*sink).clone())); ( sink, MessagingAudit::new(writer, AuditKeyHasher::unkeyed_dev_only()), @@ -201,7 +201,7 @@ pub(crate) mod tests { ) .unwrap(); let audit = MessagingAudit::new( - AuditWriter::from_line_sink(Box::new(io::sink())), + AuditWriter::from_line_sink_without_posture(Box::new(io::sink())), profile.key_hasher(), ); let identity = CallerIdentity { diff --git a/crates/registry-messaging/src/auth.rs b/crates/registry-messaging/src/auth.rs index e1d61d0d7e..ba63caea1f 100644 --- a/crates/registry-messaging/src/auth.rs +++ b/crates/registry-messaging/src/auth.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use registry_messaging_core::{ AccessProfiles, AccessRefusal, ActorKind, ActorKindClaim, Caller, VerifiedTokenFacts, }; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{validate_compact_access_token, DeclaredScope, FailedCheck}; use registry_platform_oidc::{ actor_kind, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, @@ -29,19 +29,13 @@ pub struct MessagingAuthenticator { verifier: TokenVerifier, claim_names: ClaimNames, profiles: AccessProfiles, + /// The claim the deployment reads scopes from, as configured. + scope_claim: String, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, } impl MessagingAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Messaging authentication refused" - ); - } - #[must_use] pub fn new( verifier: TokenVerifierConfig, @@ -54,6 +48,7 @@ impl MessagingAuthenticator { .validate() .expect("the default contextual claim names are valid"); Self { + scope_claim: verifier.scope_claim.clone(), verifier: TokenVerifier::new(verifier, keys), claim_names, profiles, @@ -63,18 +58,23 @@ impl MessagingAuthenticator { /// Verify one credential and resolve it to exactly one access profile. pub async fn authenticate(&self, token: &str) -> Result { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Messaging authentication refused" - ); - verifier_failure(&error) - })?; + self.authenticate_declaring(token) + .await + .map_err(|refusal| refusal.error) + } + + /// As [`Self::authenticate`], and a scope refusal also carries what the + /// deployment declared about it: the scope claim name, the scope the + /// profile requires, and the profile's id. None of it comes from the + /// token. + pub async fn authenticate_declaring(&self, token: &str) -> Result { + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, so // an empty map would trust every authority the issuer federates. @@ -83,14 +83,11 @@ impl MessagingAuthenticator { if !self.binds_assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - tracing::debug!( - "an exchanged credential arrived at a deployment that declared no assertion authority" - ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer).into()); } let client_id = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))?; let facts = VerifiedTokenFacts { issuer: verified.claims.iss.as_deref(), subject: verified.claims.sub.as_deref(), @@ -101,23 +98,52 @@ impl MessagingAuthenticator { }; self.profiles .resolve(&facts) - .map_err(|refusal| match refusal { - AccessRefusal::Profile => { - let (stage, remedy) = if self.profiles.missing_scope(&facts).is_some() { - (registry_platform_oidc::AuthenticationStage::Scope, "check authentication.oidc.scopeClaim and accessProfiles requiredScopes") - } else { - (registry_platform_oidc::AuthenticationStage::Profile, "check accessProfiles actorKind and requesterClients") + .map_err(|refusal| self.access_refusal(refusal, &facts)) + } + + /// The error a refused profile resolution answers with, and the check it + /// names. A scope refusal also carries the values configuration declared + /// for it. + fn access_refusal( + &self, + refusal: AccessRefusal, + facts: &VerifiedTokenFacts<'_>, + ) -> DeclaredRefusal { + match refusal { + AccessRefusal::Profile => { + if let Some(missing) = self.profiles.missing_scope(facts) { + return DeclaredRefusal { + error: AuthenticationError::Profile(FailedCheck::Scope), + declared: Some( + DeclaredScope::new(&self.scope_claim) + .with_required_scope(missing.scope) + .with_access_profile(missing.profile), + ), }; - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - stage, - "Messaging authentication profile refused", - remedy = remedy - ); - AuthenticationError::Profile } - AccessRefusal::Claims => AuthenticationError::Claims, - }) + let check = if self.profiles.iter().any(|profile| { + facts.client_id.is_some_and(|client| { + profile + .requester_clients + .iter() + .any(|named| named == client) + }) + }) { + FailedCheck::ActorKind + } else { + FailedCheck::AccessProfile + }; + AuthenticationError::Profile(check).into() + } + AccessRefusal::Claims => AuthenticationError::Claims( + if matches!(facts.actor_kind, ActorKindClaim::Malformed) { + FailedCheck::ActorKind + } else { + FailedCheck::TokenClaims + }, + ) + .into(), + } } } @@ -131,14 +157,31 @@ impl std::fmt::Debug for MessagingAuthenticator { } } +/// A refusal of authentication with the values the deployment declared about +/// it, when it is a scope refusal. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DeclaredRefusal { + pub error: AuthenticationError, + pub declared: Option, +} + +impl From for DeclaredRefusal { + fn from(error: AuthenticationError) -> Self { + Self { + error, + declared: None, + } + } +} + #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's access profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, @@ -168,7 +211,7 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // signal, and answering 503 there would let a caller probe the key // set. A variant the platform adds later reads as a refusal until it // is classified here, so a new outcome can never widen the door. - _ => AuthenticationError::Refused, + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -198,8 +241,6 @@ pub(crate) mod tests { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - use crate::smtp::tests::Captured; - pub(crate) const ISSUER: &str = "https://task-token.test"; pub(crate) const AUDIENCE: &str = "urn:registry-messaging:test"; pub(crate) const SENDER_CLIENT: &str = "case-system"; @@ -366,26 +407,38 @@ pub(crate) mod tests { #[tokio::test] async fn a_credential_that_is_not_a_compact_token_is_refused() { for credential in ["", "not-a-jwt", "a.b", "a b.c.d"] { - assert_eq!(refusal(credential).await, AuthenticationError::Refused); + assert_eq!( + refusal(credential).await, + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); } } #[tokio::test] async fn a_forged_signature_is_refused() { let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); - assert_eq!(refusal(&forged).await, AuthenticationError::Refused); + assert_eq!( + refusal(&forged).await, + AuthenticationError::Refused(FailedCheck::TokenSignature) + ); } #[tokio::test] async fn a_token_for_another_audience_or_issuer_is_refused() { let other_audience = token(with(sender_claims(), "aud", json!("urn:elsewhere"))); - assert_eq!(refusal(&other_audience).await, AuthenticationError::Refused); + assert_eq!( + refusal(&other_audience).await, + AuthenticationError::Refused(FailedCheck::TokenAudience) + ); let other_issuer = token(with( sender_claims(), "iss", json!("https://elsewhere.test"), )); - assert_eq!(refusal(&other_issuer).await, AuthenticationError::Refused); + assert_eq!( + refusal(&other_issuer).await, + AuthenticationError::Refused(FailedCheck::TokenIssuer) + ); } #[tokio::test] @@ -396,7 +449,10 @@ pub(crate) mod tests { "iat", json!(now - 900), )); - assert_eq!(refusal(&expired).await, AuthenticationError::Refused); + assert_eq!( + refusal(&expired).await, + AuthenticationError::Refused(FailedCheck::TokenTime) + ); } #[tokio::test] @@ -412,19 +468,28 @@ pub(crate) mod tests { header.typ = Some("JWT".to_owned()); let id_token = jsonwebtoken::encode(&header, &claims, &EncodingKey::from_secret(SECRET)).unwrap(); - assert_eq!(refusal(&id_token).await, AuthenticationError::Refused); + assert_eq!( + refusal(&id_token).await, + AuthenticationError::Refused(FailedCheck::TokenType) + ); } #[tokio::test] async fn a_client_the_deployment_does_not_admit_is_refused() { let stranger = token(with(sender_claims(), "azp", json!("unrelated-app"))); - assert_eq!(refusal(&stranger).await, AuthenticationError::Refused); + assert_eq!( + refusal(&stranger).await, + AuthenticationError::Refused(FailedCheck::TokenClient) + ); } #[tokio::test] async fn an_admitted_client_without_a_profile_is_not_authorized() { let unprofiled = token(with(sender_claims(), "azp", json!(UNPROFILED_CLIENT))); - assert_eq!(refusal(&unprofiled).await, AuthenticationError::Profile); + assert_eq!( + refusal(&unprofiled).await, + AuthenticationError::Profile(FailedCheck::AccessProfile) + ); } #[tokio::test] @@ -434,70 +499,58 @@ pub(crate) mod tests { "registry_scopes", json!("messaging:read"), )); - assert_eq!(refusal(&no_scope).await, AuthenticationError::Profile); + assert_eq!( + refusal(&no_scope).await, + AuthenticationError::Profile(FailedCheck::Scope) + ); let mut absent = sender_claims(); absent.as_object_mut().unwrap().remove("registry_scopes"); - assert_eq!(refusal(&token(absent)).await, AuthenticationError::Profile); - } - - #[tokio::test] - async fn a_scope_refusal_logs_only_a_fixed_stage_and_no_values() { - let captured = Captured::install(); - let credential = token(with( - sender_claims(), - "registry_scopes", - json!("messaging:read"), - )); - assert_eq!(refusal(&credential).await, AuthenticationError::Profile); - let logs = captured.finish(); - assert!(logs.contains("scope"), "{logs}"); - for needle in [ - credential.as_str(), - "messaging:read", - "case-system", - "registry_actor_kind", - "registry_scopes", - "messaging:send", - "case-notices", - ] { - assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); - } - } - - #[tokio::test] - async fn an_actor_kind_refusal_logs_no_scope_advice() { - let captured = Captured::install(); - let human = token(with(sender_claims(), "registry_actor_kind", json!("human"))); - assert_eq!(refusal(&human).await, AuthenticationError::Profile); - let logs = captured.finish(); - assert!(!logs.contains("scopeClaim"), "{logs}"); + assert_eq!( + refusal(&token(absent)).await, + AuthenticationError::Profile(FailedCheck::Scope) + ); } #[tokio::test] async fn an_actor_kind_the_profile_does_not_admit_is_not_authorized() { let human = token(with(sender_claims(), "registry_actor_kind", json!("human"))); - assert_eq!(refusal(&human).await, AuthenticationError::Profile); + assert_eq!( + refusal(&human).await, + AuthenticationError::Profile(FailedCheck::ActorKind) + ); let mut absent = sender_claims(); absent .as_object_mut() .unwrap() .remove("registry_actor_kind"); - assert_eq!(refusal(&token(absent)).await, AuthenticationError::Profile); + assert_eq!( + refusal(&token(absent)).await, + AuthenticationError::Profile(FailedCheck::ActorKind) + ); } #[tokio::test] async fn a_malformed_actor_kind_is_a_claims_refusal() { let malformed = token(with(sender_claims(), "registry_actor_kind", json!("robot"))); - assert_eq!(refusal(&malformed).await, AuthenticationError::Claims); + assert_eq!( + refusal(&malformed).await, + AuthenticationError::Claims(FailedCheck::ActorKind) + ); let operator = token(with(operator_claims(), "registry_actor_kind", json!(7))); - assert_eq!(refusal(&operator).await, AuthenticationError::Claims); + assert_eq!( + refusal(&operator).await, + AuthenticationError::Claims(FailedCheck::ActorKind) + ); } #[tokio::test] async fn a_token_without_a_principal_is_a_claims_refusal() { let mut claims = sender_claims(); claims.as_object_mut().unwrap().remove("sub"); - assert_eq!(refusal(&token(claims)).await, AuthenticationError::Claims); + assert_eq!( + refusal(&token(claims)).await, + AuthenticationError::Claims(FailedCheck::TokenClaims) + ); } #[tokio::test] @@ -507,7 +560,10 @@ pub(crate) mod tests { registry_platform_oidc::ASSERTION_ISSUER_CLAIM, json!("https://assertions.example.test"), )); - assert_eq!(refusal(&exchanged).await, AuthenticationError::Profile); + assert_eq!( + refusal(&exchanged).await, + AuthenticationError::Profile(FailedCheck::TokenAssertionIssuer) + ); let declaring = MessagingAuthenticator::new( verifier(&[(SENDER_CLIENT, "https://assertions.example.test")]), @@ -532,7 +588,7 @@ pub(crate) mod tests { let during_outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); assert_eq!( during_outage @@ -583,32 +639,11 @@ pub(crate) mod tests { ] { assert_eq!( verifier_failure(&refusal), - AuthenticationError::Refused, + AuthenticationError::Refused(refusal.failed_check()), "{refusal} was excused as an outage" ); } } - #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { - use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; - use tracing::instrument::WithSubscriber; - let captured = CapturedDiagnosticLogs::default(); - let subscriber = captured.subscriber(); - let tokens = malformed_access_token_fixtures(); - let auth = authenticator(); - for _ in 0..3 { - for token in &tokens { - assert!(matches!( - auth.authenticate(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - } - } - captured.assert_one_value_free_header_diagnostic(&tokens); - } - #[tokio::test] async fn separate_resource_rs256_and_es256_profiles_refuse_cross_resource_reuse() { for algorithm in [AccessTokenAlgorithm::RS256, AccessTokenAlgorithm::ES256] @@ -650,28 +685,28 @@ pub(crate) mod tests { let auth = &auth; async move { auth.authenticate(&token).await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. let token = self::token(sender_claims()); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(_)) )); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(_)) )); let mut missing = claims.clone(); missing["registry_scopes"] = json!(""); let token = sign(missing, "at+jwt"); assert!(matches!( auth.authenticate(&token).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(_)) )); } } diff --git a/crates/registry-messaging/src/callbacks.rs b/crates/registry-messaging/src/callbacks.rs index 1af963790c..8f9f18d739 100644 --- a/crates/registry-messaging/src/callbacks.rs +++ b/crates/registry-messaging/src/callbacks.rs @@ -12,7 +12,9 @@ //! that does not verify, and a token segment on a provider whose verifier is //! not `path-token` (or none on one whose verifier is) all answer //! `callback.unverified` alike, so the route reveals neither which providers -//! receive callbacks nor why a request was refused. +//! receive callbacks nor why a request was refused. The operator learns why +//! from the refusal's failed check, counted on the metrics listener and named +//! in one bounded log line that carries nothing the caller sent. //! //! A verified callback answers 204 when its receipt was applied, changed //! nothing, reported nothing this runtime records, or named no message: @@ -34,8 +36,10 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{HeaderMap, StatusCode, Uri}; use axum::response::{IntoResponse, Response}; use registry_messaging_core::{ - verify_callback, CallbackRequest, ProblemCode, Receipt, PROVIDER_CALLBACK_PATH, + verify_callback, CallbackRequest, CallbackVerificationRefusal, ProblemCode, Receipt, + PROVIDER_CALLBACK_PATH, }; +use registry_platform_authcommon::FailedCheck; use crate::http::{rate_limited_response, read_request_body, HttpError, HttpState}; use crate::http_provider::ReceiptScriptError; @@ -85,7 +89,7 @@ async fn answer( Err(LimitRefusal::Unavailable) => { tracing::error!("the Messaging callback-rate limiter could not decide"); state.metrics.record_callback(CallbackOutcome::Unavailable); - return Err(HttpError(ProblemCode::ServiceUnavailable).into_response()); + return Err(HttpError::problem(ProblemCode::ServiceUnavailable).into_response()); } } let uri = request.uri().clone(); @@ -96,22 +100,39 @@ async fn answer( let (outcome, answer) = match receive_callback(state, provider_id, token, &uri, &headers, body).await { Ok(outcome) => (outcome, Ok(StatusCode::NO_CONTENT)), - Err((outcome, problem)) => (outcome, Err(HttpError(problem).into_response())), + Err((outcome, error)) => (outcome, Err(error.into_response())), }; state.metrics.record_callback(outcome); answer } -type Refusal = (CallbackOutcome, ProblemCode); +type Refusal = (CallbackOutcome, HttpError); -const fn unverified() -> Refusal { - (CallbackOutcome::Unverified, ProblemCode::CallbackUnverified) +/// A callback that did not verify, and the check that failed. +fn unverified(check: FailedCheck) -> Refusal { + ( + CallbackOutcome::Unverified, + HttpError::refused(ProblemCode::CallbackUnverified, check), + ) +} + +/// The check a verifier's refusal names: a missing or wrong path token is a +/// shared secret that did not match, every other refusal a signature that did +/// not. +const fn verification_check(refusal: CallbackVerificationRefusal) -> FailedCheck { + match refusal { + CallbackVerificationRefusal::MissingHeader + | CallbackVerificationRefusal::MalformedSignature + | CallbackVerificationRefusal::SignatureMismatch => FailedCheck::DeliverySignature, + CallbackVerificationRefusal::MissingPathToken + | CallbackVerificationRefusal::TokenMismatch => FailedCheck::SharedSecret, + } } -const fn unavailable() -> Refusal { +fn unavailable() -> Refusal { ( CallbackOutcome::Unavailable, - ProblemCode::ServiceUnavailable, + HttpError::problem(ProblemCode::ServiceUnavailable), ) } @@ -124,15 +145,10 @@ async fn receive_callback( body: Bytes, ) -> Result { let Some(receiver) = state.callbacks.get(provider_id).map(Arc::clone) else { - tracing::warn!("a provider callback named no provider that receives callbacks"); - return Err(unverified()); + return Err(unverified(FailedCheck::DeliveryBinding)); }; if receiver.uses_path_token() != token.is_some() { - tracing::warn!( - provider = provider_id, - "a provider callback arrived on the route its verifier does not use" - ); - return Err(unverified()); + return Err(unverified(FailedCheck::DeliveryBinding)); } let path = PROVIDER_CALLBACK_PATH.replace("{provider_id}", provider_id); let callback = OwnedCallback { @@ -157,12 +173,7 @@ async fn receive_callback( if let Err(refusal) = callback.with_request(|request| verify_callback(&receiver.verifier(), request)) { - tracing::warn!( - provider = provider_id, - reason = %refusal, - "a provider callback did not verify" - ); - return Err(unverified()); + return Err(unverified(verification_check(refusal))); } let Some(service) = state.messages.as_deref() else { return Err(unavailable()); @@ -192,7 +203,10 @@ async fn receive_callback( reason = %error, "a verified provider callback could not be read" ); - return Err((CallbackOutcome::Unreadable, ProblemCode::CallbackUnreadable)); + return Err(( + CallbackOutcome::Unreadable, + HttpError::problem(ProblemCode::CallbackUnreadable), + )); } }; let recorded = service diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 5bdf8c7ac3..213aaadaa8 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -2,37 +2,39 @@ //! The operator runtime configuration document and the package it names. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Duration; use registry_messaging_core::{ - typed, ProviderKind, MESSAGING_RUNTIME_API_VERSION, MESSAGING_RUNTIME_KIND, PACKAGE_FILE, - RETIRED_MESSAGING_RUNTIME_API_VERSION, + typed, AccessProfiles, ProviderKind, MESSAGING_RUNTIME_API_VERSION, MESSAGING_RUNTIME_KIND, + PACKAGE_FILE, RETIRED_MESSAGING_RUNTIME_API_VERSION, }; use registry_platform_audit::{ AuditDestination, AuditDestinationError, AuditDestinationKind, MAX_AUDIT_RETAIN_DAYS, MIN_AUDIT_ROTATE_BYTES, }; -use registry_platform_config::{ - AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, MetricsBindError, RemovedKey, - RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretReference, SecretResolver, - DEFAULT_STAND_IN, REMOVED_OIDC_JWKS_SOURCE_KIND, REMOVED_OIDC_JWKS_URI, -}; pub use registry_platform_config::{ - DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, - JwksSource as OidcJwksSource, ListenerNetworkExposure, MetricsListenerConfig, - OidcClientsConfig, OidcIssuerConfig, PackageConfig as RuntimePackageConfig, - PrivateListenerConfig as ListenerConfig, SecretProvidersConfig, TlsTermination, + AdmittedClients, DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + JwksSource as OidcJwksSource, ListenerNetworkExposure, MetricsListenerConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, + PackageConfig as RuntimePackageConfig, PrivateListenerConfig as ListenerConfig, + SecretProvidersConfig, TlsTermination, MAX_ASSERTION_ISSUERS_PER_CLIENT as MAXIMUM_ASSERTION_ISSUERS_PER_CLIENT, MAX_ASSERTION_ISSUER_BYTES as MAXIMUM_ASSERTION_ISSUER_BYTES, MAX_ASSERTION_ISSUER_CLIENTS as MAXIMUM_ASSERTION_ISSUER_CLIENTS, MAX_ASSERTION_ISSUER_CLIENT_BYTES as MAXIMUM_ASSERTION_ISSUER_CLIENT_BYTES, UNAVAILABLE_CODE as RUNTIME_CONFIG_UNAVAILABLE_CODE, }; +use registry_platform_config::{ + AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, MetricsBindError, RemovedKey, + RuntimeConfigLoader, RuntimeEnvelope, RuntimeFileCheck, SecretReference, SecretResolver, + DEFAULT_STAND_IN, REMOVED_OIDC_JWKS_SOURCE_KIND, REMOVED_OIDC_JWKS_URI, +}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{escape_pointer_segment, Diagnostic, Report, RetiredApiVersion}; use serde::{Deserialize, Deserializer}; @@ -295,12 +297,13 @@ pub struct OidcConfig { #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] #[cfg_attr(feature = "schema", schemars(flatten))] pub provider: OidcIssuerConfig, - /// The OAuth clients this runtime admits. Every access profile resolves - /// its caller from the matched client, so the list is never empty, and - /// every client a profile names must appear here. - #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-clients"))] + /// The OAuth clients this runtime admits: `from-package` for the + /// requester clients of the package's access profiles, or a list that + /// covers every client a profile names. Every access profile resolves its + /// caller from the matched client, so the admitted set is never empty. + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-package-clients"))] #[cfg_attr(feature = "schema", schemars(flatten))] - pub clients: OidcClientsConfig, + pub clients: OidcPackageClientsConfig, #[serde(default = "default_scope_claim")] pub scope_claim: String, } @@ -484,7 +487,7 @@ impl RuntimeConfig { #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(MESSAGING_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(MESSAGING_RUNTIME_ENVELOPE) .removed_keys(MESSAGING_REMOVED_KEYS) .retired_api_versions(MESSAGING_RETIRED_API_VERSIONS) .require_trusted_ownership() @@ -674,7 +677,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { @@ -690,19 +693,34 @@ impl RuntimeConfig { // so `allowedClients: unrestricted` would admit every client the // issuer verifies while reaching no profile. Development keeps no // exception. - if oidc.clients.allowed_clients.is_empty() - || oidc.clients.allowed_clients.iter().any(String::is_empty) - { - findings.push(RuntimeConfigError::AllowedClientsRequired); + match &oidc.clients.allowed_clients { + PackageClients::Unrestricted => { + findings.push(RuntimeConfigError::AllowedClientsRequired) + } + PackageClients::Listed(clients) => { + if clients.iter().any(String::is_empty) { + findings.push(RuntimeConfigError::AllowedClientsRequired); + } + self.check_assertion_issuer_clients(clients, findings); + } + PackageClients::FromPackage => {} } - for (client, issuers) in &oidc.clients.assertion_issuers { + } + + /// Every client `assertionIssuers` names must be one the runtime admits. + fn check_assertion_issuer_clients( + &self, + admitted: &[String], + findings: &mut Vec, + ) { + for (client, issuers) in &self.authentication.oidc.clients.assertion_issuers { let pointer = pointer_to(&["authentication", "oidc", "assertionIssuers", client]); if issuers.is_empty() { findings.push(RuntimeConfigError::EmptyAssertionIssuers { pointer: pointer.clone(), }); } - if !oidc.clients.allowed_clients.contains(client) { + if !admitted.contains(client) { findings.push(RuntimeConfigError::AssertionIssuerClientNotAllowed { pointer }); } } @@ -768,27 +786,62 @@ impl RuntimeConfig { loaded: &LoadedPackage, findings: &mut Vec, ) { - let allowed: BTreeSet<&str> = self - .authentication - .oidc - .clients - .allowed_clients - .iter() - .map(String::as_str) - .collect(); - for profile in loaded.package.access_profiles().iter() { - if profile - .requester_clients - .iter() - .any(|client| !allowed.contains(client.as_str())) - { - findings.push(RuntimeConfigError::ProfileClientNotAllowed { - profile: profile.id.clone(), - }); + match self.admitted_clients(loaded.package.access_profiles()) { + Ok(admitted) => { + if self.authentication.oidc.clients.allowed_clients == PackageClients::FromPackage { + self.check_assertion_issuer_clients(admitted.as_slice(), findings); + } + } + // Each profile the list leaves out is its own finding. + Err(RuntimeConfigError::ProfileClientNotAllowed { .. }) => { + if let PackageClients::Listed(listed) = + &self.authentication.oidc.clients.allowed_clients + { + for profile in loaded.package.access_profiles().iter() { + if profile + .requester_clients + .iter() + .any(|client| !listed.contains(client)) + { + findings.push(RuntimeConfigError::ProfileClientNotAllowed { + profile: profile.id.clone(), + }); + } + } + } } + Err(error) => findings.push(error), } } + /// The clients the token verifier admits, given the access profiles of + /// the package this runtime serves. `from-package` is the sorted union of + /// the profiles' requester clients, and a list must cover every one of + /// them, or the profile naming the missing client could never be reached. + /// The verifier is never handed an empty list, which it reads as "every + /// client". + pub fn admitted_clients( + &self, + profiles: &AccessProfiles, + ) -> Result { + let allowed = &self.authentication.oidc.clients.allowed_clients; + allowed + .resolve(&profiles.requester_clients()) + .map_err(|error| match error { + PackageClientsError::Unrestricted | PackageClientsError::Empty => { + RuntimeConfigError::AllowedClientsRequired + } + PackageClientsError::Missing(client) => { + RuntimeConfigError::ProfileClientNotAllowed { + profile: profiles + .iter() + .find(|profile| profile.requester_clients.contains(&client)) + .map_or_else(String::new, |profile| profile.id.clone()), + } + } + }) + } + /// Each connection must be for a provider the package declares, of the /// declared type, and an `http` connection must satisfy the package half /// it completes. @@ -879,7 +932,8 @@ impl RuntimeConfig { policy, ) } - OidcJwksSource::Static { document_ref } => { + OidcJwksSource::Static { document_ref } + | OidcJwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", @@ -887,8 +941,19 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The document is the operator's own file, so its text names the + // rule it breaks and never a key value. + OidcError::StaticKeySet(refused) => { + RuntimeConfigError::OidcJwksSecret(format!( + "the document authentication.oidc.jwksSource.documentRef names \ + is not a usable static key set: {refused}" + )) + } + _ => RuntimeConfigError::Oidc, + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -912,7 +977,7 @@ impl RuntimeConfig { /// [`access_token_typ_set`] admits exactly that pair, so an ID token or any /// other JWT minted for this audience is refused. #[must_use] - pub fn verifier_profile(&self) -> TokenVerifierConfig { + pub fn verifier_profile(&self, admitted: &AdmittedClients) -> TokenVerifierConfig { TokenVerifierConfig::access_token_profile( self.authentication.oidc.provider.issuer.to_string(), vec![self.authentication.oidc.provider.audience.clone()], @@ -923,7 +988,7 @@ impl RuntimeConfig { access_token_typ_set(MESSAGING_ACCESS_TOKEN_TYPE), ) .with_scope_claim(self.authentication.oidc.scope_claim.clone()) - .with_allowed_clients(self.authentication.oidc.clients.allowed_clients.clone()) + .with_allowed_clients(admitted.as_slice().to_vec()) .with_assertion_issuers(self.authentication.oidc.clients.assertion_issuers.clone()) } @@ -1729,6 +1794,7 @@ pub(crate) mod tests { use super::*; use registry_platform_yaml::{Severity, MAXIMUM_DIAGNOSTICS_PER_FILE}; use serde_json::{json, Value}; + use std::collections::BTreeSet; /// The starter package's manifest, as a value a test may change. pub(crate) fn package_value() -> Value { @@ -1854,6 +1920,92 @@ pub(crate) mod tests { ); } + /// Load a runtime whose static key source names `document`, and build the + /// key source from it. + #[cfg(unix)] + async fn static_key_source(document: &str) -> Result<(), RuntimeConfigError> { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = root.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = secrets.join("issuer-jwks"); + std::fs::write(&file, document).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut runtime = runtime_value(root.path()); + runtime["authentication"]["oidc"]["jwksSource"] = + json!({"type": "static", "documentRef": "secret:file/issuer-jwks"}); + let path = write_project(root.path(), &runtime, &package_value()); + let config = RuntimeConfig::load_with_environment(path, &no_environment)?; + let resolver = config.secret_resolver()?; + config.jwks_fetcher(&resolver).await.map(|_| ()) + } + + fn static_key(extra: Value) -> Value { + let mut key = json!({ + "kty": "RSA", + "kid": "issuer-key-1", + "use": "sig", + "alg": "RS256", + "n": "sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", + "e": "AQAB", + }); + for (name, value) in extra.as_object().unwrap() { + key[name] = value.clone(); + } + key + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_with_members_it_does_not_know_loads() { + let key = static_key( + json!({"ext": true, "x5t": "abc", "x5u": "https://identity.example.test/cert"}), + ); + let document = json!({"keys": [key], "issuer": "https://identity.example.test"}); + static_key_source(&document.to_string()) + .await + .expect("a public key set with unknown members loads"); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_that_holds_a_private_member_is_refused_with_the_rule() { + for member in ["d", "p", "q", "dp", "dq", "qi", "oth", "k"] { + let key = static_key(json!({ member: "canary-private-value" })); + let document = json!({"keys": [key]}); + let error = static_key_source(&document.to_string()) + .await + .expect_err(member); + assert!( + matches!(error, RuntimeConfigError::OidcJwksSecret(_)), + "{member}: {error}" + ); + assert_eq!(error.code(), "messaging.runtime.unreadable-jwks-secret"); + let text = error.to_string(); + assert!( + text.contains(&format!("private-key member \"{member}\"")), + "{member}: {text}" + ); + assert!(!text.contains("canary-private-value"), "{text}"); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn a_static_key_set_that_repeats_a_member_name_is_refused() { + let document = r#"{"keys":[{"kty":"RSA","kid":"a","kid":"b","n":"AQAB","e":"AQAB"}]}"#; + let error = static_key_source(document) + .await + .expect_err("a repeated member"); + assert_eq!(error.code(), "messaging.runtime.unreadable-jwks-secret"); + assert!( + error.to_string().contains("repeats a member name"), + "{error}" + ); + } + fn no_environment(_: &str) -> Option { None } @@ -2524,6 +2676,143 @@ pub(crate) mod tests { ); } + fn profile_naming(id: &str, clients: &[&str]) -> registry_messaging_core::AccessProfile { + registry_messaging_core::AccessProfile { + id: id.to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec!["messaging:send".to_owned()], + requester_clients: clients.iter().map(|client| (*client).to_owned()).collect(), + actor_kind: None, + acts_as: registry_messaging_core::ActsAs::Operator, + sender_profiles: Vec::new(), + templates: Vec::new(), + allow_direct_content: false, + requests_per_minute: 60, + burst: 10, + maximum_messages_per_day: None, + } + } + + fn from_package() -> Value { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("from-package"); + value + } + + #[tokio::test] + async fn from_package_admits_exactly_the_package_clients() { + use crate::auth::tests::{keys, token}; + use registry_platform_oidc::TokenVerifier; + + let config = load(from_package()).expect("from-package loads against the starter package"); + let profiles = registry_messaging_core::AccessProfiles::new(vec![ + profile_naming("first", &["c1", "c2"]), + profile_naming("second", &["c3"]), + ]) + .unwrap(); + let admitted = config.admitted_clients(&profiles).unwrap(); + assert_eq!(admitted.as_slice(), ["c1", "c2", "c3"]); + let mut profile = config.verifier_profile(&admitted); + assert_eq!(profile.allowed_clients, ["c1", "c2", "c3"]); + profile.allowed_algorithms = vec![jsonwebtoken::Algorithm::HS256]; + let verifier = TokenVerifier::new(profile, keys()); + let signed = |client: &str| { + token(json!({ + "iss": "https://identity.example.test", + "aud": "urn:example:messaging", + "sub": "principal", + "azp": client, + "scope": "messaging:send", + })) + }; + for client in ["c1", "c2", "c3"] { + verifier + .verify(&signed(client)) + .await + .unwrap_or_else(|error| panic!("{client} is admitted: {error}")); + } + let refused = verifier.verify(&signed("c4")).await; + assert!( + matches!( + refused, + Err(registry_platform_oidc::OidcError::ClientNotAllowed) + ), + "{refused:?}" + ); + } + + #[test] + fn from_package_never_reaches_the_verifier_as_an_empty_list() { + let config = load(from_package()).unwrap(); + let none = registry_messaging_core::AccessProfiles::default(); + let error = config.admitted_clients(&none).unwrap_err(); + assert!( + matches!(error, RuntimeConfigError::AllowedClientsRequired), + "{error}" + ); + } + + #[test] + fn an_explicit_list_missing_a_package_client_is_refused_with_the_profile() { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!(["case-system"]); + let config = RuntimeConfig::parse_with_environment( + &serde_json::to_string(&value).unwrap(), + &no_environment, + ) + .unwrap(); + let profiles = registry_messaging_core::AccessProfiles::new(vec![ + profile_naming("covered", &["case-system"]), + profile_naming("left-out", &["operations-console"]), + ]) + .unwrap(); + let error = config.admitted_clients(&profiles).unwrap_err(); + assert!( + matches!(&error, RuntimeConfigError::ProfileClientNotAllowed { profile } if profile == "left-out"), + "{error}" + ); + } + + #[test] + fn assertion_issuer_client_outside_the_package_is_refused_under_from_package() { + let mut value = from_package(); + value["authentication"]["oidc"]["assertionIssuers"] = + json!({"unknown-client": ["https://assertions.example.test"]}); + let error = load(value).unwrap_err(); + assert!( + matches!( + error, + RuntimeConfigError::AssertionIssuerClientNotAllowed { .. } + ), + "{error}" + ); + assert_eq!( + error.pointer(), + "/authentication/oidc/assertionIssuers/unknown-client" + ); + let mut value = from_package(); + value["authentication"]["oidc"]["assertionIssuers"] = + json!({"case-system": ["https://assertions.example.test"]}); + assert!(load(value).unwrap().binds_assertion_issuers()); + } + + #[test] + fn the_keywords_other_than_from_package_and_unrestricted_are_refused() { + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("any"); + let error = load(value).unwrap_err(); + assert_eq!(error.code(), "config.invalid-value", "{error}"); + assert_eq!(error.pointer(), "/authentication/oidc/allowedClients"); + let mut value = base(); + value["authentication"]["oidc"]["allowedClients"] = json!("unrestricted"); + assert!(matches!( + load(value).unwrap_err(), + RuntimeConfigError::AllowedClientsRequired + )); + } + #[test] fn a_repeated_allowed_client_is_refused_at_the_repetition() { let mut value = base(); @@ -3010,7 +3299,8 @@ pub(crate) mod tests { #[test] fn the_verifier_admits_only_the_access_token_media_type() { let config = load(base()).unwrap(); - let profile = config.verifier_profile(); + let admitted = AdmittedClients::new(vec!["case-system".to_owned()]).unwrap(); + let profile = config.verifier_profile(&admitted); assert!(registry_platform_oidc::is_access_token_typ_pair( &profile.allowed_typ )); diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index b3b5657b36..f7f68674cf 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -50,11 +50,13 @@ use registry_messaging_core::{ MESSAGE_CANCEL_PATH, MESSAGE_PATH, MESSAGE_RECEIPT_PATH, METRICS_PATH, PROVIDER_CALLBACK_PATH, PROVIDER_CALLBACK_TOKEN_PATH, READY_PATH, TEMPLATE_PREVIEW_PATH, }; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, +}; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; use serde::Serialize; @@ -382,6 +384,7 @@ const CALLBACK_PROBLEMS: [ProblemCode; 7] = [ pub fn router(state: HttpState) -> Router { let metrics = Arc::clone(&state.metrics); + let refusals = Arc::clone(&state.metrics); http_edge( Router::new() .route(HEALTH_PATH, get(health)) @@ -397,6 +400,7 @@ pub fn router(state: HttpState) -> Router { post(callbacks::receive_with_token), ) .with_state(state) + .layer(middleware::from_fn_with_state(refusals, record_refusals)) .layer(middleware::from_fn_with_state(metrics, count_requests)), ) } @@ -417,7 +421,7 @@ fn http_edge(router: Router) -> Router { .method_not_allowed_fallback(method_not_allowed) .layer(request_body_limit_default()) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } async fn http_boundary(request: axum::http::Request, next: Next) -> Response { @@ -465,7 +469,7 @@ async fn ready(State(state): State) -> Result if state.readiness.is_ready().await { Ok(StatusCode::OK) } else { - Err(HttpError(ProblemCode::ServiceUnavailable)) + Err(HttpError::problem(ProblemCode::ServiceUnavailable)) } } @@ -478,17 +482,17 @@ async fn submit_message( let mut audit = state .audit .begin(serde_json::to_value(requested).map_err(|_| { - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?) .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a submission request"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let result = match admit_submission(&state, &caller, request.headers()).await { Ok(key) => match read_request_body(request).await { Ok(body) => accept_submission(&state, &caller, &key, &body).await, - Err(HttpError(problem)) => Err(problem.into()), + Err(error) => Err(error.code().into()), }, Err(refusal) => Err(refusal), }; @@ -496,9 +500,9 @@ async fn submit_message( Ok(answer) if !answer.replayed => answer .audit_record .clone() - .ok_or(HttpError(ProblemCode::ServiceUnavailable))?, + .ok_or(HttpError::problem(ProblemCode::ServiceUnavailable))?, Ok(answer) => serde_json::to_value(SubmissionRecord::replayed(&state, &caller, answer)?) - .map_err(|_| HttpError(ProblemCode::ServiceUnavailable))?, + .map_err(|_| HttpError::problem(ProblemCode::ServiceUnavailable))?, Err(refusal) if refusal.problem == ProblemCode::ServiceUnavailable => { count_limit_refusal(&state.metrics, refusal.problem); return Ok(refusal_response(*refusal)); @@ -506,12 +510,12 @@ async fn submit_message( Err(refusal) => { count_limit_refusal(&state.metrics, refusal.problem); serde_json::to_value(SubmissionRecord::refused(&state, &caller, refusal.problem)?) - .map_err(|_| HttpError(ProblemCode::ServiceUnavailable))? + .map_err(|_| HttpError::problem(ProblemCode::ServiceUnavailable))? } }; audit.respond(record).await.map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a submission response"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let answer = match result { Ok(answer) => answer, @@ -519,7 +523,7 @@ async fn submit_message( }; let status = StatusCode::from_u16(answer.status).map_err(|_| { tracing::error!("a stored Messaging receipt carries an invalid status"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok((status, Json(answer.receipt)).into_response()) } @@ -618,7 +622,7 @@ impl SubmissionRecord { .principal_pseudonym(&caller.identity) .map_err(|error| { tracing::error!(error = %error, "a Messaging principal pseudonym failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok(Self { event, @@ -662,7 +666,7 @@ async fn get_message( let message = service .visible_message(&caller, &message_id) .await - .map_err(HttpError)?; + .map_err(HttpError::problem)?; Ok(Json(message.view)) } @@ -674,25 +678,25 @@ async fn message_receipt( // Observation neither renders nor submits. Keep the original receipt // available even when the caller has spent its submission budget. if !is_json(request.headers()) { - return Err(HttpError(ProblemCode::RequestUnsupportedMediaType)); + return Err(HttpError::problem(ProblemCode::RequestUnsupportedMediaType)); } let key = request .headers() .get(IDEMPOTENCY_KEY_HEADER) .filter(|key| valid_idempotency_key(key.as_bytes())) .and_then(|key| key.to_str().ok()) - .ok_or(HttpError(ProblemCode::RequestInvalid))? + .ok_or(HttpError::problem(ProblemCode::RequestInvalid))? .to_owned(); let body = read_request_body(request).await?; let service = state .messages .as_ref() - .ok_or(HttpError(ProblemCode::ServiceUnavailable))?; + .ok_or(HttpError::problem(ProblemCode::ServiceUnavailable))?; Ok(Json( service .message_receipt(&caller, &key, &body) .await - .map_err(HttpError)?, + .map_err(HttpError::problem)?, ) .into_response()) } @@ -708,7 +712,7 @@ async fn cancel_message( let view = service .cancel(&caller, &message_id) .await - .map_err(HttpError)?; + .map_err(HttpError::problem)?; Ok(Json(view)) } @@ -719,7 +723,7 @@ async fn cancel_message( fn message_path(extracted: Result, PathRejection>) -> Result { extracted .map(|Path(message_id)| message_id) - .map_err(|_| HttpError(ProblemCode::MessageNotVisible)) + .map_err(|_| HttpError::problem(ProblemCode::MessageNotVisible)) } /// The message service for a route naming `message_id`. An identifier no @@ -729,9 +733,9 @@ fn visible_service<'a>( message_id: &str, ) -> Result<&'a MessageService, HttpError> { if uuid::Uuid::parse_str(message_id).is_err() { - return Err(HttpError(ProblemCode::MessageNotVisible)); + return Err(HttpError::problem(ProblemCode::MessageNotVisible)); } - message_service(state).map_err(HttpError) + message_service(state).map_err(HttpError::problem) } fn message_service(state: &HttpState) -> Result<&MessageService, ProblemCode> { @@ -781,7 +785,7 @@ async fn preview_template( .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a preview request"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let headers = request.headers().clone(); let outcome = match read_request_body(request).await { @@ -793,25 +797,25 @@ async fn preview_template( &headers, &body, ), - Err(HttpError(problem)) => PreviewOutcome { + Err(error) => PreviewOutcome { locale: None, - result: Err(problem), + result: Err(error.code()), }, }; let record = PreviewRecord::new(&state, &caller, &template_id, &version, &outcome)?; audit .respond(serde_json::to_value(record).map_err(|_| { - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?) .await .map_err(|error| { tracing::error!(error = %error, "the Messaging audit destination refused a preview response"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; - let preview = outcome.result.map_err(HttpError)?; + let preview = outcome.result.map_err(HttpError::problem)?; let body = preview_json(&preview).map_err(|error| { tracing::error!(error = %error, "a Messaging preview could not be serialized"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; Ok((StatusCode::OK, [(CONTENT_TYPE, "application/json")], body).into_response()) } @@ -827,7 +831,7 @@ pub(crate) async fn read_request_body(request: Request) -> Result ProblemCode::RequestBodyTooLarge, _ => ProblemCode::RequestInvalid, }; - HttpError(problem) + HttpError::problem(problem) }) } @@ -917,7 +921,7 @@ impl PreviewRecord { .principal_pseudonym(&caller.identity) .map_err(|error| { tracing::error!(error = %error, "a Messaging principal pseudonym failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::problem(ProblemCode::ServiceUnavailable) })?; let template = state @@ -950,37 +954,184 @@ impl PreviewRecord { async fn authenticate(state: &HttpState, headers: &HeaderMap) -> Result { let result = match bearer_token(headers) { - Some(token) => state.authenticator.authenticate(token).await, - None => { - state.authenticator.record_header_refusal(); - Err(AuthenticationError::Refused) - } + Ok(token) => state.authenticator.authenticate_declaring(token).await, + Err(check) => Err(AuthenticationError::Refused(check).into()), }; - result.map_err(|error| { - state.metrics.record_authentication_refusal(error); - authentication_problem(error) + result.map_err(|refusal| { + state.metrics.record_authentication_refusal(refusal.error); + authentication_problem(refusal.error).with_declared(refusal.declared) }) } -fn bearer_token(headers: &HeaderMap) -> Option<&str> { - let authorization = headers.get(AUTHORIZATION)?.to_str().ok()?; - parse_bearer_token(authorization).ok() +/// The bearer credential an `Authorization` header carries, or the check that +/// refuses it: no header, or not the Bearer scheme, is a missing credential. An +/// unreadable or misshapen header is a malformed one. +fn bearer_token(headers: &HeaderMap) -> Result<&str, FailedCheck> { + let authorization = headers + .get(AUTHORIZATION) + .ok_or(FailedCheck::CredentialMissing)? + .to_str() + .map_err(|_| FailedCheck::CredentialMalformed)?; + parse_bearer_token(authorization).map_err(|error| match error { + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) } fn authentication_problem(error: AuthenticationError) -> HttpError { match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError(ProblemCode::AuthenticationRefused) + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + HttpError::refused(ProblemCode::AuthenticationRefused, check) + } + AuthenticationError::Profile(check) => { + HttpError::refused(ProblemCode::ProfileNotAuthorized, check) } - AuthenticationError::Profile => HttpError(ProblemCode::ProfileNotAuthorized), // The verifier reached no verdict, so the credential is not what is // wrong. `service.unavailable` carries `Retry-After` instead of a - // challenge that would send the caller rotating a good token. - AuthenticationError::Unavailable => HttpError(ProblemCode::ServiceUnavailable), + // challenge that would send the caller rotating a good token. The + // answer counts under the key source it could not use. + AuthenticationError::Unavailable => HttpError::refused( + ProblemCode::ServiceUnavailable, + FailedCheck::KeySourceUnavailable, + ), + } +} + +/// A problem answer, and the check that failed when the problem refuses the +/// caller. The check travels with the answer to the one layer that records +/// it; it is never written to the response. +pub struct HttpError { + problem: ProblemCode, + check: Option, + /// What the deployment declared about a scope refusal. It rides with the + /// check to the recording layer and is never written to the response. + declared: Option, +} + +impl HttpError { + /// An answer whose check the producer names: a refusal, or an answer that + /// counts under a check although it is not one. + pub(crate) fn refused(problem: ProblemCode, check: FailedCheck) -> Self { + Self { + problem, + check: Some(check), + declared: None, + } + } + + /// Attach the values a scope refusal's log line may name. + #[must_use] + pub(crate) fn with_declared(self, declared: Option) -> Self { + Self { declared, ..self } + } + + /// An answer whose check follows from its problem code alone: the + /// problems the service answers once a caller is resolved. + /// [`attribution`] sorts every problem code, so a code added to the + /// vocabulary does not compile until it says which side it is on. + pub(crate) fn problem(problem: ProblemCode) -> Self { + let check = match attribution(problem) { + Attribution::Plain => None, + Attribution::Service(check) => Some(check), + Attribution::Named => { + tracing::error!("a refusal that names its failed check was answered without one"); + None + } + }; + Self { + problem, + check, + declared: None, + } + } + + /// The problem this answer carries. + pub(crate) fn code(&self) -> ProblemCode { + self.problem } } -pub struct HttpError(pub ProblemCode); +/// How a problem code relates to the failed-check record. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Attribution { + /// The problem does not refuse the caller. + Plain, + /// The problem refuses the caller, and every producer past + /// authentication means this one check. + Service(FailedCheck), + /// The problem refuses the caller, and its producer (authentication or + /// the callback verifier) names the check itself. + Named, +} + +/// Sort every problem code. No wildcard arm: a new code must pick a side. +#[deny(clippy::wildcard_enum_match_arm)] +const fn attribution(problem: ProblemCode) -> Attribution { + match problem { + ProblemCode::AuthenticationRefused | ProblemCode::CallbackUnverified => Attribution::Named, + // Past authentication, the sender role, the sender profile, the + // template and direct content are what the profile does not allow. + ProblemCode::OperationNotAuthorized | ProblemCode::ProfileNotAuthorized => { + Attribution::Service(FailedCheck::Operation) + } + ProblemCode::MessageNotVisible => Attribution::Service(FailedCheck::Visibility), + ProblemCode::RateLimitExceeded => Attribution::Service(FailedCheck::RateLimit), + ProblemCode::CallbackUnreadable + | ProblemCode::ContentInvalid + | ProblemCode::ContentTooLarge + | ProblemCode::ContentTooManySegments + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::MessageDispatchStarted + | ProblemCode::MessageTerminal + | ProblemCode::QuotaExceeded + | ProblemCode::ReceiptUnresolved + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ServiceUnavailable + | ProblemCode::TemplateDataInvalid + | ProblemCode::TemplateLocaleUnavailable + | ProblemCode::TemplateNotFound + | ProblemCode::TemplateRenderRefused => Attribution::Plain, + } +} + +/// The fixed advice a refusal's log line carries for the checks an operator +/// fixes in the access profiles or the issuer's scope claim. +const fn remedy(check: FailedCheck) -> Option<&'static str> { + match check { + FailedCheck::Scope => { + Some("check authentication.oidc.scopeClaim and accessProfiles requiredScopes") + } + FailedCheck::AccessProfile | FailedCheck::ActorKind => { + Some("check accessProfiles actorKind and requesterClients") + } + _ => None, + } +} + +/// Count a refused request and write its admitted log line. The note rides in +/// the answer's extensions, which no serializer reads. +async fn record_refusals( + State(metrics): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + record_refusal!( + metrics.refusal_recorder(), + note, + trace_id = current_trace().trace_id, + declared = response.extensions().get::() + ); + } + response +} /// Render a refused submission: its problem, with `Retry-After` in whole /// seconds, never below one, when a limit says how long to wait. @@ -1010,7 +1161,11 @@ fn retry_after_seconds(wait: std::time::Duration) -> u64 { impl IntoResponse for HttpError { fn into_response(self) -> Response { - problem_response(self.0) + let mut response = problem_answer(self.problem, self.check); + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } + response } } @@ -1020,9 +1175,16 @@ fn current_trace() -> TraceContext { .unwrap_or_else(|_| TraceContext::server_created()) } -/// Render one problem: the pinned code, title, status, and detail from the -/// closed vocabulary, under the answering request's trace. +/// Render one problem whose failed check, if it refuses the caller, follows +/// from its code. fn problem_response(problem: ProblemCode) -> Response { + HttpError::problem(problem).into_response() +} + +/// Render one problem: the pinned code, title, status, and detail from the +/// closed vocabulary, under the answering request's trace. The failed check +/// rides in the response extensions for [`record_refusals`]. +fn problem_answer(problem: ProblemCode, check: Option) -> Response { let trace = current_trace(); let status = problem.http_status(); let body = ProblemBody { @@ -1056,6 +1218,12 @@ fn problem_response(problem: ProblemCode) -> Response { .expect("the retry interval is a valid header value"), ); } + if let Some(check) = check { + let note = RefusalNote::new(check); + response + .extensions_mut() + .insert(remedy(check).map_or(note, |remedy| note.with_remedy(remedy))); + } response } @@ -1412,7 +1580,7 @@ mod tests { let during_outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ))); let app = router(state_with(during_outage, true)); let headers = expect_problem( @@ -2532,6 +2700,800 @@ mod tests { .await; } + /// One refusal answer reduced to what a caller can observe: the status, + /// the headers that carry a decision, and the body without its per-request + /// `traceId`. + async fn answer_snapshot(name: &str, response: Response) -> serde_json::Value { + let status = response.status().as_u16(); + let header = |response: &Response, name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().unwrap().to_owned()) + }; + let headers = json!({ + "content-type": header(&response, "content-type"), + "www-authenticate": header(&response, "www-authenticate"), + "retry-after": header(&response, "retry-after"), + "cache-control": header(&response, "cache-control"), + }); + let bytes = to_bytes(response.into_body(), 64 * 1024).await.unwrap(); + let mut body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert!(body["traceId"].is_string(), "{name}: {body}"); + body.as_object_mut().unwrap().remove("traceId"); + json!({"name": name, "status": status, "headers": headers, "body": body}) + } + + /// Every authentication, authorization, visibility and rate refusal the + /// HTTP surface answers without a database. + async fn refusal_snapshots() -> Vec { + let mut snapshots = Vec::new(); + let (app, _) = app(); + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + snapshots.push( + answer_snapshot( + "no credential", + call(app.clone(), "GET", message, None).await, + ) + .await, + ); + let basic = Request::builder() + .uri(message) + .header(AUTHORIZATION, "Basic dXNlcjpwYXNz") + .body(Body::empty()) + .unwrap(); + snapshots.push( + answer_snapshot( + "not the bearer scheme", + app.clone().oneshot(basic).await.unwrap(), + ) + .await, + ); + snapshots.push( + answer_snapshot( + "not a compact token", + call(app.clone(), "GET", message, Some("not-a-jwt")).await, + ) + .await, + ); + let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); + snapshots.push( + answer_snapshot( + "forged signature", + call(app.clone(), "GET", message, Some(&forged)).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["aud"] = json!("urn:elsewhere"); + snapshots.push( + answer_snapshot( + "other audience", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["azp"] = json!("unrelated-app"); + snapshots.push( + answer_snapshot( + "client the verifier does not admit", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["azp"] = json!(UNPROFILED_CLIENT); + snapshots.push( + answer_snapshot( + "client with no access profile", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_scopes"] = json!("messaging:read"); + snapshots.push( + answer_snapshot( + "scope the profile requires is missing", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("human"); + snapshots.push( + answer_snapshot( + "actor kind the profile does not admit", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("robot"); + snapshots.push( + answer_snapshot( + "malformed actor kind", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims.as_object_mut().unwrap().remove("sub"); + snapshots.push( + answer_snapshot( + "no principal", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + let mut claims = sender_claims(); + claims[registry_platform_oidc::ASSERTION_ISSUER_CLAIM] = + json!("https://assertions.example.test"); + snapshots.push( + answer_snapshot( + "exchanged token with no declared authority", + call(app.clone(), "GET", message, Some(&token(claims))).await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "a message id no message can carry", + call( + app.clone(), + "GET", + "/v1/messages/not-an-id", + Some(&token(sender_claims())), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "operator submits", + post_json( + app.clone(), + "/v1/messages", + Some(&token(operator_claims())), + &json!({}), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "operator previews", + post_json( + app.clone(), + PREVIEW, + Some(&token(operator_claims())), + &sample_request(), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "sender previews a template its profile does not list", + post_json( + app.clone(), + "/v1/templates/unlisted-template/versions/1/preview", + Some(&token(sender_claims())), + &sample_request(), + ) + .await, + ) + .await, + ); + snapshots.push( + answer_snapshot( + "callback for a provider that receives none", + post( + app, + "/v1/provider-callbacks/mail-relay", + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await, + ) + .await, + ); + let mut state = callback_state(path_token_verifier()); + state.callback_limits = Arc::new(CallbackLimits::new(60, 2).unwrap()); + let app = router(state); + let mut limited = None; + for _ in 0..3 { + limited = Some( + post( + app.clone(), + "/v1/provider-callbacks/sms-gateway/callback-token-000000", + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await, + ); + } + snapshots.push(answer_snapshot("callback past the rate", limited.unwrap()).await); + let issuer_keys = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/jwks.json")) + .respond_with(ResponseTemplate::new(503)) + .mount(&issuer_keys) + .await; + let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( + format!("{}/jwks.json", issuer_keys.uri()), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + ))); + let app = router(state_with(outage, true)); + snapshots.push( + answer_snapshot( + "key endpoint outage", + call(app, "GET", message, Some(&token(sender_claims()))).await, + ) + .await, + ); + snapshots + } + + /// The refusal answers are frozen in `tests/golden/refusals.json`. Set + /// `REGISTRY_UPDATE_GOLDEN=1` to rewrite the file from the current code. + #[tokio::test] + async fn refusal_answers_match_the_golden_file() { + let golden = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusals.json"); + let actual = serde_json::Value::Array(refusal_snapshots().await); + if std::env::var_os("REGISTRY_UPDATE_GOLDEN").is_some() { + std::fs::create_dir_all(golden.parent().unwrap()).unwrap(); + let mut text = serde_json::to_string_pretty(&actual).unwrap(); + text.push('\n'); + std::fs::write(&golden, text).unwrap(); + } + let expected: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&golden).expect("the golden file")) + .expect("the golden file is JSON"); + assert_eq!(actual, expected); + } + + fn request( + method: &str, + uri: &str, + authorization: Option, + body: Option<&serde_json::Value>, + ) -> Request { + let mut request = Request::builder().method(method).uri(uri); + if let Some(authorization) = authorization { + request = request.header(AUTHORIZATION, authorization); + } + match body { + Some(body) => request + .header(CONTENT_TYPE, "application/json") + .body(Body::from(serde_json::to_vec(body).unwrap())) + .unwrap(), + None => request.body(Body::empty()).unwrap(), + } + } + + fn bearer(token: &str) -> Option { + Some(format!("Bearer {token}")) + } + + /// The request counts under `check` once: the counter moved by one, and + /// the log carries one line naming it. + fn assert_counted_under(metrics: &Metrics, logs: &str, check: FailedCheck, context: &str) { + let text = metrics.render(None); + assert!( + text.contains(&format!( + "messaging_request_refusals_total{{check=\"{}\"}} 1\n", + check.as_str() + )), + "{context}: {text}" + ); + let counted: u64 = text + .lines() + .filter(|line| line.starts_with("messaging_request_refusals_total{")) + .map(|line| line.rsplit(' ').next().unwrap().parse::().unwrap()) + .sum(); + assert_eq!(counted, 1, "{context}: {text}"); + assert!( + logs.contains(&format!("failed_check=\"{}\"", check.as_str())), + "{context}: {logs}" + ); + assert_eq!( + logs.matches("request refused").count(), + 1, + "{context}: {logs}" + ); + } + + /// One request per check the service decides, each answered by the golden + /// problem and counted and logged under the check that failed. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_the_check_that_failed() { + use crate::smtp::tests::Captured; + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + let claims_with = |key: &str, value: serde_json::Value| { + let mut claims = sender_claims(); + claims[key] = value; + token(claims) + }; + let forged = token_signed_with(sender_claims(), b"another-secret-another-secret-another!"); + let mut without_principal = sender_claims(); + without_principal.as_object_mut().unwrap().remove("sub"); + let basic = Some("Basic dXNlcjpwYXNz".to_owned()); + let cases: Vec<(&str, FailedCheck, Request)> = vec![ + ( + "no credential", + FailedCheck::CredentialMissing, + request("GET", message, None, None), + ), + ( + "not the bearer scheme", + FailedCheck::CredentialMissing, + request("GET", message, basic, None), + ), + ( + "not a compact token", + FailedCheck::CredentialMalformed, + request("GET", message, bearer("not-a-jwt"), None), + ), + ( + "forged signature", + FailedCheck::TokenSignature, + request("GET", message, bearer(&forged), None), + ), + ( + "other audience", + FailedCheck::TokenAudience, + request( + "GET", + message, + bearer(&claims_with("aud", json!("urn:elsewhere"))), + None, + ), + ), + ( + "other issuer", + FailedCheck::TokenIssuer, + request( + "GET", + message, + bearer(&claims_with("iss", json!("https://elsewhere.test"))), + None, + ), + ), + ( + "client the verifier does not admit", + FailedCheck::TokenClient, + request( + "GET", + message, + bearer(&claims_with("azp", json!("unrelated-app"))), + None, + ), + ), + ( + "client with no access profile", + FailedCheck::AccessProfile, + request( + "GET", + message, + bearer(&claims_with("azp", json!(UNPROFILED_CLIENT))), + None, + ), + ), + ( + "missing scope", + FailedCheck::Scope, + request( + "GET", + message, + bearer(&claims_with("registry_scopes", json!("messaging:read"))), + None, + ), + ), + ( + "actor kind the profile does not admit", + FailedCheck::ActorKind, + request( + "GET", + message, + bearer(&claims_with("registry_actor_kind", json!("human"))), + None, + ), + ), + ( + "malformed actor kind", + FailedCheck::ActorKind, + request( + "GET", + message, + bearer(&claims_with("registry_actor_kind", json!("robot"))), + None, + ), + ), + ( + "no principal", + FailedCheck::TokenClaims, + request("GET", message, bearer(&token(without_principal)), None), + ), + ( + "exchanged token with no declared authority", + FailedCheck::TokenAssertionIssuer, + request( + "GET", + message, + bearer(&claims_with( + registry_platform_oidc::ASSERTION_ISSUER_CLAIM, + json!("https://assertions.example.test"), + )), + None, + ), + ), + ( + "a message id no message can carry", + FailedCheck::Visibility, + request( + "GET", + "/v1/messages/not-an-id", + bearer(&token(sender_claims())), + None, + ), + ), + ( + "operator submits", + FailedCheck::Operation, + request( + "POST", + "/v1/messages", + bearer(&token(operator_claims())), + Some(&json!({})), + ), + ), + ( + "operator previews", + FailedCheck::Operation, + request( + "POST", + PREVIEW, + bearer(&token(operator_claims())), + Some(&sample_request()), + ), + ), + ( + "sender previews a template its profile does not list", + FailedCheck::Operation, + request( + "POST", + "/v1/templates/unlisted-template/versions/1/preview", + bearer(&token(sender_claims())), + Some(&sample_request()), + ), + ), + ]; + for (name, check, request) in cases { + let (app, metrics) = app(); + let captured = Captured::install(); + let response = app.oneshot(request).await.unwrap(); + let logs = captured.finish(); + assert!(response.status().is_client_error(), "{name}"); + assert_counted_under(&metrics, &logs, check, name); + } + } + + /// A scope refusal's line names the values the deployment declared: the + /// scope claim it reads, the scope the profile requires and the profile. + /// The scope the token carries never reaches the line, and no other + /// refusal writes any of the three. + #[tokio::test] + async fn a_scope_refusal_line_names_the_declared_scope_and_none_of_the_tokens() { + use crate::smtp::tests::Captured; + let message = "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; + let canary = "canary:never-logged"; + let mut scoped = sender_claims(); + scoped["registry_scopes"] = json!(canary); + let (first_app, _metrics) = app(); + let captured = Captured::install(); + let response = first_app + .oneshot(request("GET", message, bearer(&token(scoped)), None)) + .await + .unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(!logs.contains(canary), "{logs}"); + assert!(logs.contains("failed_check=\"scope\""), "{logs}"); + assert!(logs.contains("scope_claim=\"registry_scopes\""), "{logs}"); + assert!(logs.contains("required_scope=\"messaging:send\""), "{logs}"); + assert!(logs.contains("access_profile=\"case-notices\""), "{logs}"); + + let mut unprofiled = sender_claims(); + unprofiled["azp"] = json!(UNPROFILED_CLIENT); + unprofiled["registry_scopes"] = json!(canary); + let (second_app, _metrics) = app(); + let captured = Captured::install(); + let response = second_app + .oneshot(request("GET", message, bearer(&token(unprofiled)), None)) + .await + .unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(logs.contains("failed_check=\"access-profile\""), "{logs}"); + for name in ["scope_claim", "required_scope", "access_profile="] { + assert!(!logs.contains(name), "{name}: {logs}"); + } + assert!(!logs.contains(canary), "{logs}"); + } + + #[tokio::test] + async fn a_key_endpoint_outage_counts_under_the_key_source() { + use crate::smtp::tests::Captured; + let issuer_keys = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/jwks.json")) + .respond_with(ResponseTemplate::new(503)) + .mount(&issuer_keys) + .await; + let outage = authenticator_over(Arc::new(JwksFetcher::new_with_fetch_url_policy( + format!("{}/jwks.json", issuer_keys.uri()), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + ))); + let state = state_with(outage, true); + let metrics = Arc::clone(&state.metrics); + let captured = Captured::install(); + let response = call( + router(state), + "GET", + "/v1/messages/0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d", + Some(&token(sender_claims())), + ) + .await; + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_counted_under(&metrics, &logs, FailedCheck::KeySourceUnavailable, "outage"); + } + + #[tokio::test] + async fn each_callback_refusal_is_counted_and_logged_under_the_check_that_failed() { + use crate::smtp::tests::Captured; + let signed_wrong = Request::builder() + .method("POST") + .uri("/v1/provider-callbacks/sms-gateway") + .header(CONTENT_TYPE, "application/json") + .header("x-gateway-signature", "00".repeat(32)) + .body(Body::from(br#"{"id":"gw-1"}"#.to_vec())) + .unwrap(); + let unsigned = Request::builder() + .method("POST") + .uri("/v1/provider-callbacks/sms-gateway") + .header(CONTENT_TYPE, "application/json") + .body(Body::from(br#"{"id":"gw-1"}"#.to_vec())) + .unwrap(); + let callback = |uri: &str| request("POST", uri, None, Some(&json!({}))); + let cases: Vec<(&str, serde_json::Value, FailedCheck, Request)> = vec![ + ( + "no provider that receives callbacks", + path_token_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/no-such-provider"), + ), + ( + "a token on a route the verifier does not use", + body_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/sms-gateway/anything"), + ), + ( + "no token on the route that needs one", + path_token_verifier(), + FailedCheck::DeliveryBinding, + callback("/v1/provider-callbacks/sms-gateway"), + ), + ( + "a wrong path token", + path_token_verifier(), + FailedCheck::SharedSecret, + callback("/v1/provider-callbacks/sms-gateway/callback-token-000000"), + ), + ( + "a wrong signature", + body_verifier(), + FailedCheck::DeliverySignature, + signed_wrong, + ), + ( + "a missing signature", + body_verifier(), + FailedCheck::DeliverySignature, + unsigned, + ), + ]; + for (name, verifier, check, request) in cases { + let (app, metrics) = callback_app(verifier); + let captured = Captured::install(); + let response = app.oneshot(request).await.unwrap(); + let logs = captured.finish(); + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{name}"); + assert_counted_under(&metrics, &logs, check, name); + for needle in ["callback-token", "sms-gateway", "no-such-provider", "gw-1"] { + assert!( + !logs.contains(needle), + "{name}: the log carries {needle:?}: {logs}" + ); + } + } + } + + #[tokio::test] + async fn a_callback_past_the_rate_and_a_caller_past_the_rate_count_as_rate_limits() { + use crate::smtp::tests::Captured; + let mut state = callback_state(path_token_verifier()); + state.callback_limits = Arc::new(CallbackLimits::new(60, 1).unwrap()); + let metrics = Arc::clone(&state.metrics); + let app = router(state); + let uri = "/v1/provider-callbacks/sms-gateway/callback-token-000000"; + let first = post( + app.clone(), + uri, + None, + Some("application/json"), + b"{}".to_vec(), + ) + .await; + assert_eq!(first.status(), StatusCode::FORBIDDEN); + let captured = Captured::install(); + let second = post(app, uri, None, Some("application/json"), b"{}".to_vec()).await; + let logs = captured.finish(); + assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS); + let text = metrics.render(None); + assert!( + text.contains("messaging_request_refusals_total{check=\"rate-limit\"} 1\n"), + "{text}" + ); + assert!(logs.contains("failed_check=\"rate-limit\""), "{logs}"); + + let package = starter_package(); + let profiles = package + .access_profiles() + .iter() + .cloned() + .map(|profile| registry_messaging_core::AccessProfile { + requests_per_minute: 60, + burst: 1, + ..profile + }) + .collect(); + let mut state = state_with(authenticator(), true); + state.limits = Arc::new( + CallerLimits::new(®istry_messaging_core::AccessProfiles::new(profiles).unwrap()) + .unwrap(), + ); + let metrics = Arc::clone(&state.metrics); + let app = router(state); + let sender = token(sender_claims()); + let submit = |app: Router| { + let sender = sender.clone(); + async move { post_json(app, "/v1/messages", Some(&sender), &json!({})).await } + }; + assert_ne!( + submit(app.clone()).await.status(), + StatusCode::TOO_MANY_REQUESTS + ); + let limited = submit(app).await; + assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS); + let text = metrics.render(None); + assert!( + text.contains("messaging_request_refusals_total{check=\"rate-limit\"} 1\n"), + "{text}" + ); + } + + #[tokio::test] + async fn a_refusal_log_carries_the_check_and_a_fixed_remedy_and_no_value() { + use crate::smtp::tests::Captured; + let (app, _) = app(); + let credential = token(sender_claims_with_scope("messaging:read")); + let captured = Captured::install(); + call(app.clone(), "GET", "/v1/messages/m-1", Some(&credential)).await; + let logs = captured.finish(); + assert!(logs.contains("failed_check=\"scope\""), "{logs}"); + assert!(logs.contains("scopeClaim"), "{logs}"); + // The scope refusal names the configured scope claim, scope and + // profile, and nothing the credential or the request carried. + for needle in [ + "scope_claim=\"registry_scopes\"", + "required_scope=\"messaging:send\"", + "access_profile=\"case-notices\"", + ] { + assert!(logs.contains(needle), "logs lack {needle:?}:\n{logs}"); + } + for needle in [ + credential.as_str(), + "messaging:read", + "case-system", + "registry_actor_kind", + "m-1", + ] { + assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); + } + let human = { + let mut claims = sender_claims(); + claims["registry_actor_kind"] = json!("human"); + token(claims) + }; + let captured = Captured::install(); + call(app, "GET", "/v1/messages/m-1", Some(&human)).await; + let logs = captured.finish(); + assert!(logs.contains("failed_check=\"actor-kind\""), "{logs}"); + assert!(!logs.contains("scopeClaim"), "{logs}"); + for needle in ["scope_claim", "required_scope", "access_profile="] { + assert!(!logs.contains(needle), "logs carry {needle:?}:\n{logs}"); + } + } + + fn sender_claims_with_scope(scope: &str) -> serde_json::Value { + let mut claims = sender_claims(); + claims["registry_scopes"] = json!(scope); + claims + } + + #[tokio::test] + async fn malformed_credentials_log_a_bounded_value_free_line() { + use crate::smtp::tests::Captured; + use registry_platform_testing::malformed_access_token_fixtures; + let tokens = malformed_access_token_fixtures(); + let (app, metrics) = app(); + let captured = Captured::install(); + for _ in 0..3 { + for token in &tokens { + let response = call(app.clone(), "GET", "/v1/messages/m-1", Some(token)).await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + } + let logs = captured.finish(); + let sent = u64::try_from(3 * tokens.len()).unwrap(); + let text = metrics.render(None); + assert!( + text.contains(&format!( + "messaging_request_refusals_total{{check=\"credential-malformed\"}} {sent}\n" + )), + "{text}" + ); + assert_eq!(logs.matches("request refused").count(), 5, "{logs}"); + for token in &tokens { + assert!(token.is_empty() || !logs.contains(token.as_str()), "{logs}"); + } + } + + #[test] + fn every_problem_that_answers_401_or_403_is_attributed() { + for problem in ProblemCode::ALL { + let refuses = matches!(problem.http_status(), 401 | 403); + assert!( + !refuses || attribution(*problem) != Attribution::Plain, + "{problem:?} refuses a caller and names no check" + ); + } + assert_eq!( + attribution(ProblemCode::MessageNotVisible), + Attribution::Service(FailedCheck::Visibility) + ); + assert_eq!( + attribution(ProblemCode::RateLimitExceeded), + Attribution::Service(FailedCheck::RateLimit) + ); + assert_eq!( + attribution(ProblemCode::OperationNotAuthorized), + Attribution::Service(FailedCheck::Operation) + ); + } + #[test] fn the_operation_table_answers_only_catalogued_problems_and_unique_ids() { let mut ids = std::collections::BTreeSet::new(); diff --git a/crates/registry-messaging/src/http_provider/mod.rs b/crates/registry-messaging/src/http_provider/mod.rs index 18d1aac3d1..ea1819c540 100644 --- a/crates/registry-messaging/src/http_provider/mod.rs +++ b/crates/registry-messaging/src/http_provider/mod.rs @@ -377,7 +377,7 @@ impl HttpProviderSettings { let resolved = self.resolve_authentication(package, connection.development, secrets)?; let origin_id = destination_origin_id(provider_id)?; let profile = if connection.development { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp } else { DestinationProfile::ProductionHttps }; @@ -649,7 +649,7 @@ fn freeze_oauth( trust_bundle_pem: Option<&[u8]>, ) -> Result { let profile = if oauth.development { - DestinationProfile::LoopbackDevelopmentHttp + DestinationProfile::LoopbackHttp } else { DestinationProfile::ProductionHttps }; diff --git a/crates/registry-messaging/src/http_provider/settings.rs b/crates/registry-messaging/src/http_provider/settings.rs index 44f9175d0e..6a5ddeb319 100644 --- a/crates/registry-messaging/src/http_provider/settings.rs +++ b/crates/registry-messaging/src/http_provider/settings.rs @@ -17,7 +17,6 @@ //! platform grammar is a later extraction. use std::fmt; -use std::net::IpAddr; use std::time::Duration; use ipnet::IpNet; @@ -1291,12 +1290,10 @@ fn split_base_url( let development = match parsed.scheme() { "https" => false, "http" => { - let loopback = match parsed.host() { - Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => IpAddr::V4(address).is_loopback(), - Some(url::Host::Ipv6(address)) => IpAddr::V6(address).is_loopback(), - None => false, - }; + let loopback = parsed + .host_str() + .and_then(registry_platform_httputil::loopback::loopback_host) + .is_some(); if !loopback { return Err(invalid( field, @@ -1412,3 +1409,38 @@ fn token_form_body( } Ok(Zeroizing::new(serializer.finish().into_bytes())) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_http_is_allowed_only_to_a_loopback_host() { + for base_url in [ + "http://127.0.0.1:9/v1/", + "http://127.4.5.6:9/v1/", + "http://[::1]:9/v1/", + "http://[::ffff:127.0.0.1]:9/v1/", + "http://localhost:9/v1/", + "http://LOCALHOST:9/v1/", + ] { + let (_, _, development) = split_base_url("baseUrl", base_url, true) + .unwrap_or_else(|error| panic!("{base_url}: {error}")); + assert!(development, "{base_url}"); + } + for base_url in [ + "http://localhost.:9/v1/", + "http://gateway.localhost:9/v1/", + "http://10.0.0.1:9/v1/", + "http://0.0.0.0:9/v1/", + "http://[::]:9/v1/", + "http://[::ffff:10.0.0.1]:9/v1/", + "http://169.254.169.254/v1/", + ] { + let error = split_base_url("baseUrl", base_url, true) + .expect_err(base_url) + .to_string(); + assert!(error.contains("loopback"), "{base_url}: {error}"); + } + } +} diff --git a/crates/registry-messaging/src/metrics.rs b/crates/registry-messaging/src/metrics.rs index 48c472e409..8a8404c387 100644 --- a/crates/registry-messaging/src/metrics.rs +++ b/crates/registry-messaging/src/metrics.rs @@ -17,7 +17,10 @@ //! //! Authentication refusals are counted here rather than written to the audit //! journal: a refused credential names no principal to hold accountable, and -//! journaling it would let an unauthenticated caller grow the journal. +//! journaling it would let an unauthenticated caller grow the journal. Every +//! request the service refuses is also counted by the check that failed, in +//! `messaging_request_refusals_total`, whose label is the closed +//! [`FailedCheck`] set and nothing a caller sent. //! //! Provider callbacks are counted by [`CallbackOutcome`] alone. The provider //! id in a callback path is caller text until it names an activated @@ -49,6 +52,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -79,6 +83,9 @@ pub struct Metrics { limits: CounterVec, retention: CounterVec, sample_failures: CounterVec, + /// Refused requests by the check that failed, and the bounded log line + /// that goes with each. + request_refusals: RefusalRecorder, } impl fmt::Debug for Metrics { @@ -133,6 +140,7 @@ impl Default for Metrics { "sample", ["dispatch-queue"], ), + request_refusals: RefusalRecorder::new("messaging").expect(DECLARATION), } } } @@ -298,12 +306,19 @@ impl Metrics { ); } + /// The recorder that counts a refused request by the check that failed + /// and decides which refusals reach the log. + #[must_use] + pub fn refusal_recorder(&self) -> &RefusalRecorder { + &self.request_refusals + } + /// Count one authentication refusal by its outcome. pub fn record_authentication_refusal(&self, error: AuthenticationError) { let reason = match error { - AuthenticationError::Refused => "refused", - AuthenticationError::Claims => "claims", - AuthenticationError::Profile => "profile", + AuthenticationError::Refused(_) => "refused", + AuthenticationError::Claims(_) => "claims", + AuthenticationError::Profile(_) => "profile", AuthenticationError::Unavailable => "unavailable", }; count(&self.refusals, &[reason]); @@ -345,6 +360,10 @@ impl Metrics { ] { counter.write(&mut out).expect(DECLARATION); } + self.request_refusals + .counter() + .write(&mut out) + .expect(DECLARATION); out.header( "messaging_dispatch_jobs", Some("Messages waiting to be sent, being sent, or held unknown, sampled at scrape."), @@ -478,6 +497,7 @@ pub async fn scrape( #[cfg(test)] mod tests { use super::*; + use registry_platform_authcommon::FailedCheck; #[test] fn labels_are_closed() { @@ -516,7 +536,8 @@ mod tests { StatusCode::OK, ); metrics.record_authentication_refusal(AuthenticationError::Unavailable); - metrics.record_authentication_refusal(AuthenticationError::Claims); + metrics + .record_authentication_refusal(AuthenticationError::Claims(FailedCheck::TokenClaims)); metrics.record_callback(CallbackOutcome::Unmatched); metrics.record_callback(CallbackOutcome::Unmatched); metrics.record_attempt(AttemptOutcome::MaybeSent); @@ -561,9 +582,11 @@ messaging_retention_runs_total{outcome=\"failed\"} 1 # HELP messaging_metrics_sample_failures_total Scrape-time database reads that failed, by which read. A failed read leaves its gauges without samples. # TYPE messaging_metrics_sample_failures_total counter messaging_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 -# HELP messaging_dispatch_jobs Messages waiting to be sent, being sent, or held unknown, sampled at scrape. -# TYPE messaging_dispatch_jobs gauge "; + let head = format!( + "{head}{}# HELP messaging_dispatch_jobs Messages waiting to be sent, being sent, or held unknown, sampled at scrape.\n# TYPE messaging_dispatch_jobs gauge\n", + refusal_series() + ); assert_eq!(metrics.render(None), head); assert_eq!( metrics.render(Some(DispatchDepth { @@ -577,6 +600,21 @@ messaging_metrics_sample_failures_total{sample=\"dispatch-queue\"} 0 ); } + /// The `messaging_request_refusals_total` exposition of a recorder that + /// counted nothing: one zero series for each member of the closed set. + fn refusal_series() -> String { + let mut text = String::from( + "# HELP messaging_request_refusals_total Requests refused, by the check that failed.\n# TYPE messaging_request_refusals_total counter\n", + ); + for check in FailedCheck::ALL { + text.push_str(&format!( + "messaging_request_refusals_total{{check=\"{}\"}} 0\n", + check.as_str() + )); + } + text + } + #[test] fn every_callback_outcome_is_exposed_from_zero() { let metrics = Metrics::default(); diff --git a/crates/registry-messaging/src/runtime.rs b/crates/registry-messaging/src/runtime.rs index 9658b4249a..f7c83e7ad6 100644 --- a/crates/registry-messaging/src/runtime.rs +++ b/crates/registry-messaging/src/runtime.rs @@ -396,8 +396,9 @@ pub async fn assemble( )?); let keys = config.jwks_fetcher(&secrets).await?; + let admitted = config.admitted_clients(loaded.package.access_profiles())?; let authenticator = Arc::new(MessagingAuthenticator::new( - config.verifier_profile(), + config.verifier_profile(&admitted), keys, loaded.package.access_profiles().clone(), config.binds_assertion_issuers(), @@ -408,7 +409,7 @@ pub async fn assemble( audit_secret.expose_secret().to_vec(), )) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; - let writer = AuditWriter::open(config.audit.destination()?) + let writer = AuditWriter::open_without_posture(config.audit.destination()?) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; let audit = Arc::new(MessagingAudit::new(writer, audit_profile.key_hasher())); @@ -637,7 +638,7 @@ async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditJournal(error.to_string()))?; Ok(MessagingAudit::new(writer, profile.key_hasher())) @@ -835,11 +836,12 @@ mod tests { let profile = AuditProfile::production_from_secret_bytes(zeroize::Zeroizing::new(vec![7u8; 32])) .unwrap(); - let writer = AuditWriter::open(registry_platform_audit::AuditDestination::File( - registry_platform_audit::FileDestination::new(&audit).unwrap(), - )) - .await - .unwrap(); + let writer = + AuditWriter::open_without_posture(registry_platform_audit::AuditDestination::File( + registry_platform_audit::FileDestination::new(&audit).unwrap(), + )) + .await + .unwrap(); let journal = MessagingAudit::new(writer, profile.key_hasher()); journal .append_background( diff --git a/crates/registry-messaging/src/schema.rs b/crates/registry-messaging/src/schema.rs index a0fb8ff5aa..07848df08f 100644 --- a/crates/registry-messaging/src/schema.rs +++ b/crates/registry-messaging/src/schema.rs @@ -681,21 +681,32 @@ fn install_runtime_constraints(schema: &mut Value) { set_definition_property(schema, definition, property, "pattern", json!("^/")); } // Every access profile resolves its caller from the matched client, so - // a Messaging deployment always lists the clients it admits. The shared + // a Messaging deployment always states the clients it admits. The shared // block requires the member and also admits the keyword `unrestricted`, // which this runtime refuses in every mode, so the member is restated - // as the list alone and the shared definition is dropped. + // as `from-package` or the list, and the shared definition is dropped. if let Some(clients) = schema.pointer_mut("/$defs/OidcConfig/properties/allowedClients") { *clients = json!({ - "description": "Client identifiers whose access tokens are admitted. Required in every\nfile; an omitted or empty list, an empty or repeated client, and\n`unrestricted` are refused.", - "type": "array", - "items": {"type": "string", "minLength": 1}, - "minItems": 1, - "uniqueItems": true, + "description": "The clients whose access tokens are admitted. Required in every\nfile: `from-package` admits the requester clients of the package's access\nprofiles, and a list of at least one distinct client must cover them. An\nomitted or empty list, an empty or repeated client, and `unrestricted` are\nrefused.", + "oneOf": [ + {"type": "string", "const": "from-package"}, + { + "type": "array", + "items": {"type": "string", "minLength": 1}, + "minItems": 1, + "uniqueItems": true, + }, + ], }); } + if let Some(issuers) = + schema.pointer_mut("/$defs/OidcConfig/properties/assertionIssuers/description") + { + *issuers = json!("Assertion authorities each client may exchange a subject token from,\nkeyed by client identifier. Omitted, no assertion-issuer rule applies;\nwritten, it lists at least one client, each with at least one\nauthority. Once a client is listed, a token it exchanged is accepted\nonly for one of that client's declared authorities, and a client that\nis not listed may exchange from no authority."); + } if let Some(definitions) = schema.pointer_mut("/$defs").and_then(Value::as_object_mut) { definitions.remove("OidcAllowedClients"); + definitions.remove("OidcPackageAllowedClients"); } if let Some(profiles) = schema .pointer_mut("/properties/tlsTrustProfiles") @@ -810,8 +821,9 @@ mod tests { document["$defs"]["RetentionConfig"]["properties"]["payloadRetentionDays"]["maximum"], MAXIMUM_PAYLOAD_RETENTION_DAYS ); - // `allowedClients` is decided in every file, and only as a list: - // the runtime refuses `unrestricted` in every mode. + // `allowedClients` is decided in every file: the keyword + // `from-package` or a non-empty list. The runtime refuses + // `unrestricted` in every mode, so the schema does not offer it. let oidc = &document["$defs"]["OidcConfig"]; assert_eq!( oidc["required"] @@ -825,11 +837,15 @@ mod tests { let clients = &oidc["properties"]["allowedClients"]; assert!(clients.get("default").is_none()); assert!(clients.get("$ref").is_none(), "{clients}"); - assert_eq!(clients["type"], "array"); - assert_eq!(clients["minItems"], 1); - assert_eq!(clients["uniqueItems"], true); - assert_eq!(clients["items"]["minLength"], 1); + let forms = clients["oneOf"].as_array().expect("two written forms"); + assert_eq!(forms.len(), 2, "{clients}"); + assert_eq!(forms[0], json!({"type": "string", "const": "from-package"})); + assert_eq!(forms[1]["type"], "array"); + assert_eq!(forms[1]["minItems"], 1); + assert_eq!(forms[1]["uniqueItems"], true); + assert_eq!(forms[1]["items"]["minLength"], 1); assert!(document["$defs"].get("OidcAllowedClients").is_none()); + assert!(document["$defs"].get("OidcPackageAllowedClients").is_none()); assert_eq!( document["$defs"]["OidcConfig"]["additionalProperties"], false, "unknown keys are refused" diff --git a/crates/registry-messaging/src/smtp/mod.rs b/crates/registry-messaging/src/smtp/mod.rs index 7bd295495c..4e7cc015bd 100644 --- a/crates/registry-messaging/src/smtp/mod.rs +++ b/crates/registry-messaging/src/smtp/mod.rs @@ -446,7 +446,9 @@ impl SmtpProvider { } for address in &answers { let allowed = match self.transport { - Transport::DevelopmentLoopback => address.to_canonical().is_loopback(), + Transport::DevelopmentLoopback => { + registry_platform_httputil::loopback::loopback_address(*address) + } Transport::Starttls(_) | Transport::Implicit(_) => { self.policy.classify(*address).is_ok() } diff --git a/crates/registry-messaging/src/smtp/settings.rs b/crates/registry-messaging/src/smtp/settings.rs index 3d45e3d40f..c9ea86aa10 100644 --- a/crates/registry-messaging/src/smtp/settings.rs +++ b/crates/registry-messaging/src/smtp/settings.rs @@ -377,8 +377,10 @@ impl SmtpProviderSettings { return Err(SmtpSettingsError::DevelopmentNotPermitted); } let loopback = match host_literal { - Some(ip) => ip.to_canonical().is_loopback(), - None => self.host.eq_ignore_ascii_case("localhost"), + Some(ip) => registry_platform_httputil::loopback::loopback_address(ip), + None => { + registry_platform_httputil::loopback::loopback_host(&self.host).is_some() + } }; if !loopback { return Err(SmtpSettingsError::DevelopmentRequiresLoopbackHost); @@ -571,6 +573,7 @@ pub(super) mod tests { "0.0.0.0", "::", "localhost.example.org", + "relay.localhost", ] { let settings = SmtpProviderSettings { host: host.to_owned(), @@ -583,6 +586,10 @@ pub(super) mod tests { "{host}" ); } + assert_eq!( + development("localhost.").check(false), + Err(SmtpSettingsError::InvalidHost) + ); for host in [ "127.0.0.1", "127.3.2.1", @@ -590,6 +597,7 @@ pub(super) mod tests { "localhost", "LOCALHOST", "::ffff:127.0.0.1", + "::ffff:127.9.8.7", ] { assert!(development(host).check(false).is_ok(), "{host}"); } diff --git a/crates/registry-messaging/src/store.rs b/crates/registry-messaging/src/store.rs index 251d8ac6de..2431d8a032 100644 --- a/crates/registry-messaging/src/store.rs +++ b/crates/registry-messaging/src/store.rs @@ -37,14 +37,17 @@ fn database_error_class(error: &tokio_postgres::Error) -> String { const MESSAGING_MIGRATION: &str = include_str!("../migrations/0100_messaging.sql"); const DISPATCH_LEASE_EXPIRY_MIGRATION: &str = include_str!("../migrations/0101_dispatch_lease_expiry.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0102_activation_posture.sql"); /// Every schema version, in the order it is applied. Readiness requires the /// applied set to be exactly this list. The 1.0 baseline is version /// [`BASELINE_SCHEMA_VERSION`], above every version a pre-1.0 release /// applied; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ +pub(crate) const MIGRATIONS: [(i64, &str); 3] = [ (100, MESSAGING_MIGRATION), (101, DISPATCH_LEASE_EXPIRY_MIGRATION), + (102, ACTIVATION_POSTURE_MIGRATION), ]; /// The 1.0 baseline schema version. A ledger holding any version below it /// was left by a pre-1.0 release, which this release refuses by name. @@ -535,6 +538,7 @@ mod tests { fn the_baseline_is_version_100_and_later_versions_increase() { assert_eq!(MIGRATIONS[0].0, 100); assert_eq!(MIGRATIONS[1].0, 101); + assert_eq!(MIGRATIONS[2].0, 102); assert!(versions_start_at_baseline_and_increase(&MIGRATIONS)); assert!(versions_start_at_baseline_and_increase(&[ (100, ""), diff --git a/crates/registry-messaging/tests/golden/refusals.json b/crates/registry-messaging/tests/golden/refusals.json new file mode 100644 index 0000000000..35a0a31ecf --- /dev/null +++ b/crates/registry-messaging/tests/golden/refusals.json @@ -0,0 +1,325 @@ +[ + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "no credential", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "not the bearer scheme", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "not a compact token", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "forged signature", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "other audience", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "client the verifier does not admit", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "client with no access profile", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "scope the profile requires is missing", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "actor kind the profile does not admit", + "status": 403 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "malformed actor kind", + "status": 401 + }, + { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-messaging/authentication/refused" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": "Bearer" + }, + "name": "no principal", + "status": 401 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "exchanged token with no declared authority", + "status": 403 + }, + { + "body": { + "code": "message.not-visible", + "detail": "No message with this identifier is visible to the caller.", + "status": 404, + "title": "Message not visible", + "type": "https://id.registrystack.org/problems/registry-messaging/message/not-visible" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "a message id no message can carry", + "status": 404 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your Messaging access profile does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "operator submits", + "status": 403 + }, + { + "body": { + "code": "operation.not-authorized", + "detail": "Your Messaging access profile does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/operation/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "operator previews", + "status": 403 + }, + { + "body": { + "code": "profile.not-authorized", + "detail": "No Messaging access profile authorizes this caller for this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-messaging/profile/not-authorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "sender previews a template its profile does not list", + "status": 403 + }, + { + "body": { + "code": "callback.unverified", + "detail": "The callback did not verify for a provider this deployment accepts callbacks from.", + "status": 403, + "title": "Callback not verified", + "type": "https://id.registrystack.org/problems/registry-messaging/callback/unverified" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": null, + "www-authenticate": null + }, + "name": "callback for a provider that receives none", + "status": 403 + }, + { + "body": { + "code": "rate-limit.exceeded", + "detail": "The request rate accepted from this caller is exceeded. Try again after the time in Retry-After.", + "status": 429, + "title": "Request rate exceeded", + "type": "https://id.registrystack.org/problems/registry-messaging/rate-limit/exceeded" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "1", + "www-authenticate": null + }, + "name": "callback past the rate", + "status": 429 + }, + { + "body": { + "code": "service.unavailable", + "detail": "Messaging is unavailable. Try again after the service recovers.", + "status": 503, + "title": "Messaging service unavailable", + "type": "https://id.registrystack.org/problems/registry-messaging/service/unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "retry-after": "5", + "www-authenticate": null + }, + "name": "key endpoint outage", + "status": 503 + } +] diff --git a/crates/registry-messaging/tests/migration_pins.rs b/crates/registry-messaging/tests/migration_pins.rs index 053714ad57..d464af39d9 100644 --- a/crates/registry-messaging/tests/migration_pins.rs +++ b/crates/registry-messaging/tests/migration_pins.rs @@ -17,6 +17,10 @@ const PINS: &[(&str, &str)] = &[ "0101_dispatch_lease_expiry.sql", "2a505e1bac1e306880409ddc67c0fb0a55a5ca65714b41875eda7ac176b9796d", ), + ( + "0102_activation_posture.sql", + "a18f643199189538139927ea61749ca829ba3868ff37cb054877deee8df1e475", + ), ]; #[test] diff --git a/crates/registry-messaging/tests/postgres_callbacks.rs b/crates/registry-messaging/tests/postgres_callbacks.rs index 8601570b69..99cd19dcd4 100644 --- a/crates/registry-messaging/tests/postgres_callbacks.rs +++ b/crates/registry-messaging/tests/postgres_callbacks.rs @@ -569,7 +569,9 @@ async fn a_post_commit_callback_audit_refusal_retries_without_duplicate_history( let id = deployment.sent().await; let reference = reference_for(id); let sink = RefusingAuditSink::after(1); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let app = deployment.harness.app_with_audit(audit).await; let (status, problem) = send_app( @@ -622,7 +624,7 @@ async fn a_receipt_audit_failure_names_whether_the_receipt_was_applied() { let unavailable = record_receipt( &deployment.harness.store, - &test_audit(AuditWriter::from_line_sink(Box::new( + &test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))), "sms-gateway", @@ -638,7 +640,7 @@ async fn a_receipt_audit_failure_names_whether_the_receipt_was_applied() { let unconfirmed = record_receipt( &deployment.harness.store, - &test_audit(AuditWriter::from_line_sink(Box::new( + &test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(1), ))), "sms-gateway", diff --git a/crates/registry-messaging/tests/postgres_messages.rs b/crates/registry-messaging/tests/postgres_messages.rs index 25b27d0efa..1ab086a939 100644 --- a/crates/registry-messaging/tests/postgres_messages.rs +++ b/crates/registry-messaging/tests/postgres_messages.rs @@ -46,6 +46,33 @@ fn assert_problem(answer: &(StatusCode, Value), status: StatusCode, code: &str) assert_eq!(answer.1["code"], code, "{}", answer.1); } +/// The runtime file of the harness says `allowedClients: from-package` and +/// lists no client. The package's two requester clients both reach their +/// profile, and a client the package does not name is refused. +#[tokio::test] +async fn a_runtime_that_admits_the_package_clients_serves_a_call_from_each() { + let harness = Harness::start().await; + let text = std::fs::read_to_string(harness.runtime_path()).unwrap(); + assert!(text.contains("allowedClients: from-package"), "{text}"); + + let accepted = harness + .submit(&sender_token(), "from-package-key", &email_submission()) + .await; + assert_eq!(accepted.0, StatusCode::ACCEPTED, "{}", accepted.1); + let uri = format!("/v1/messages/{}", accepted.1["id"].as_str().unwrap()); + let (status, view) = harness.call("GET", &uri, Some(&operator_token())).await; + assert_eq!(status, StatusCode::OK, "{view}"); + + let stranger = token(json!({ + "sub": "unlisted-principal", + "azp": "reporting-job", + "registry_scopes": "messaging:send", + "registry_actor_kind": "service", + })); + let refused = harness.call("GET", &uri, Some(&stranger)).await; + assert_eq!(refused.0, StatusCode::UNAUTHORIZED, "{}", refused.1); +} + #[tokio::test] async fn operator_reads_and_action_previews_ignore_a_refused_audit_destination() { let harness = Harness::start().await; @@ -135,7 +162,7 @@ async fn an_accepted_submission_records_its_rendered_parts_and_answers_a_receipt #[tokio::test] async fn an_audit_request_refusal_records_no_submission() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))); let app = harness.app_with_audit(audit).await; @@ -166,7 +193,7 @@ async fn an_audit_request_refusal_records_no_submission() { #[tokio::test] async fn a_post_commit_audit_refusal_replays_one_committed_submission_receipt() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(1), ))); let app = harness.app_with_audit(audit).await; @@ -214,7 +241,7 @@ async fn a_post_commit_audit_refusal_replays_one_committed_submission_receipt() #[tokio::test] async fn readiness_fails_when_the_audit_writer_loses_its_destination() { let harness = Harness::start().await; - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(0), ))); assert!(audit @@ -321,9 +348,9 @@ async fn an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_aga // caller's issuer and subject, so the rotation does not free it. let journal = RefusingAuditSink::after(usize::MAX); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - journal.clone(), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(journal.clone())), + )) .await; let (status, _, replay) = submit_to(rotated.clone(), &sender, "key-1", &email_submission()).await; @@ -1306,9 +1333,9 @@ async fn the_runtime_is_ready_only_while_the_ledger_names_its_package_active() { .execute( "INSERT INTO messaging_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, $1, package_digest, \ - database_id, 'successor', now(), role_mode \ + database_id, 'successor', now(), role_mode, posture \ FROM messaging_activations ORDER BY apply_order DESC LIMIT 1", &[&other], ) @@ -1329,9 +1356,9 @@ async fn readiness_rechecks_the_database_identity_recorded_after_startup() { .execute( "INSERT INTO messaging_activations \ (activation_id, apply_order, package_digest, predecessor_package_digest, \ - database_id, plan_kind, applied_at, role_mode) \ + database_id, plan_kind, applied_at, role_mode, posture) \ SELECT gen_random_uuid(), apply_order + 1, $1, package_digest, \ - 'another-deployment', 'successor', now(), role_mode \ + 'another-deployment', 'successor', now(), role_mode, posture \ FROM messaging_activations ORDER BY apply_order DESC LIMIT 1", &[&digest], ) @@ -1433,7 +1460,7 @@ async fn a_dispatch_core_refusal_is_reported_as_an_outcome_that_may_have_applied /// A message store over the harness's schema whose audit writer accepts /// only its first `accepted_writes` records. async fn store_with_audit(harness: &Harness, accepted_writes: usize) -> MessageStore { - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(accepted_writes), ))); let schema = harness.store.current_schema().await.unwrap(); @@ -1639,7 +1666,7 @@ async fn original_receipt_disclosure_requires_both_audit_entries() { StatusCode::ACCEPTED ); for accepted_writes in [0, 1] { - let audit = test_audit(AuditWriter::from_line_sink(Box::new( + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( RefusingAuditSink::after(accepted_writes), ))); let app = harness.app_with_audit(audit).await; diff --git a/crates/registry-messaging/tests/postgres_migrate.rs b/crates/registry-messaging/tests/postgres_migrate.rs index 93acdca8c4..aa1b1fdb3d 100644 --- a/crates/registry-messaging/tests/postgres_migrate.rs +++ b/crates/registry-messaging/tests/postgres_migrate.rs @@ -77,6 +77,7 @@ fn database(reference: &str) -> DatabaseConfig { migration_url_ref: reference.to_owned(), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, } } @@ -244,13 +245,13 @@ async fn concurrent_migrators_apply_each_version_once_and_both_succeed() { a.expect("the first concurrent migration"); b.expect("the second concurrent migration"); c.expect("the third concurrent migration"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); first .migrate() .await .expect("a repeated migration applies nothing"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let runtime = PostgresStore::connect_runtime(&config, &secrets).expect("a runtime store"); runtime.ready().await.expect("a migrated store is ready"); @@ -361,7 +362,7 @@ async fn a_version_100_database_migrates_forward_keeps_its_queue_and_refuses_a_l ); store.migrate().await.expect("version 100 migrates forward"); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let queued = isolated .admin .query_one( @@ -432,9 +433,9 @@ async fn apply_migrates_a_version_100_database_forward_and_keeps_its_queue() { let applied = apply_activation(&config, &ApplyRequest::default()) .await .expect("messagingctl apply migrates version 100 forward"); - assert_eq!(applied.schema_versions_applied, [101]); + assert_eq!(applied.schema_versions_applied, [101, 102]); assert!(applied.recorded); - assert_eq!(applied_versions(&isolated).await, [100, 101]); + assert_eq!(applied_versions(&isolated).await, [100, 101, 102]); let queued = isolated .admin .query_one( diff --git a/crates/registry-messaging/tests/postgres_package.rs b/crates/registry-messaging/tests/postgres_package.rs index 0eacb11e67..ef3e1832df 100644 --- a/crates/registry-messaging/tests/postgres_package.rs +++ b/crates/registry-messaging/tests/postgres_package.rs @@ -485,7 +485,7 @@ async fn apply_refuses_a_newer_schema_before_activation_and_audits_the_refusal() .iter() .map(|row| row.get(0)) .collect(); - assert_eq!(versions, [100, 101, 199]); + assert_eq!(versions, [100, 101, 102, 199]); let operator_audit = match config .audit @@ -624,8 +624,8 @@ async fn apply_reports_the_active_digest_it_read_under_the_ledger_lock() { .batch_execute(&format!( "BEGIN; SELECT pg_advisory_xact_lock({LEDGER_LOCK_KEY}); \ INSERT INTO {}.messaging_activations \ - (activation_id,apply_order,package_digest,database_id,plan_kind,applied_at,role_mode) \ - VALUES (gen_random_uuid(),1,'{concurrent}','messaging-test','initial',now(),'single')", + (activation_id,apply_order,package_digest,database_id,plan_kind,applied_at,role_mode,posture) \ + VALUES (gen_random_uuid(),1,'{concurrent}','messaging-test','initial',now(),'single','production')", isolated.schema )) .await @@ -812,7 +812,7 @@ async fn split_role_activation_binds_identity_and_withholds_both_ledgers() { ) .await .expect("one transactional split-role activation"); - assert_eq!(applied.schema_versions_applied, [100, 101]); + assert_eq!(applied.schema_versions_applied, [100, 101, 102]); assert!(applied.recorded); assert_eq!(applied.activation.database_id, "messaging-test"); assert_eq!(applied.activation.role_mode.as_str(), "split"); diff --git a/crates/registry-messaging/tests/postgres_retention.rs b/crates/registry-messaging/tests/postgres_retention.rs index 3cb9e40ed0..2a6070e2db 100644 --- a/crates/registry-messaging/tests/postgres_retention.rs +++ b/crates/registry-messaging/tests/postgres_retention.rs @@ -338,9 +338,11 @@ async fn a_record_is_deleted_record_days_after_a_terminal_state_with_everything_ let mut other = email_submission(); other["correlationId"] = serde_json::json!("another-body"); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - RefusingAuditSink::after(usize::MAX), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(RefusingAuditSink::after( + usize::MAX, + ))), + )) .await; for app in [harness.app.clone(), rotated] { for body in [email_submission(), other.clone()] { @@ -528,9 +530,11 @@ async fn a_spent_key_forgets_its_caller_once_its_receipt_is_erased_and_stays_spe let mut other = email_submission(); other["correlationId"] = serde_json::json!("another-body"); let rotated = harness - .app_with_audit(rotated_test_audit(AuditWriter::from_line_sink(Box::new( - RefusingAuditSink::after(usize::MAX), - )))) + .app_with_audit(rotated_test_audit( + AuditWriter::from_line_sink_without_posture(Box::new(RefusingAuditSink::after( + usize::MAX, + ))), + )) .await; for app in [harness.app.clone(), rotated] { for (body, status_code, code) in [ @@ -721,7 +725,9 @@ async fn an_audit_request_refusal_erases_nothing() { let id = harness.accepted(&email_submission()).await; settle_as(&harness, id, "delivered", 8).await; let sink = RefusingAuditSink::after(0); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let refused = erase_expired( &harness.store, @@ -745,7 +751,9 @@ async fn a_post_commit_retention_audit_refusal_leaves_erasure_committed() { let id = harness.accepted(&email_submission()).await; settle_as(&harness, id, "delivered", 8).await; let sink = RefusingAuditSink::after(1); - let audit = test_audit(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = test_audit(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); let refused = erase_expired( &harness.store, diff --git a/crates/registry-messaging/tests/support/mod.rs b/crates/registry-messaging/tests/support/mod.rs index 464d13f2ba..99325c9cfc 100644 --- a/crates/registry-messaging/tests/support/mod.rs +++ b/crates/registry-messaging/tests/support/mod.rs @@ -23,7 +23,7 @@ use jsonwebtoken::{Algorithm, EncodingKey, Header}; use registry_messaging::activation::ApplyRequest; use registry_messaging::audit::MessagingAudit; use registry_messaging::auth::MessagingAuthenticator; -use registry_messaging::config::RuntimeConfig; +use registry_messaging::config::{AdmittedClients, RuntimeConfig}; use registry_messaging::dispatch::{dispatcher, Transports}; use registry_messaging::http::{metrics_router, router, HttpState, Readiness}; use registry_messaging::limits::{ @@ -298,9 +298,11 @@ impl Harness { )) .expect("the audit profile"); let audit = Arc::new(MessagingAudit::new( - AuditWriter::open(config.audit.destination().expect("audit destination")) - .await - .expect("the audit writer"), + AuditWriter::open_without_posture( + config.audit.destination().expect("audit destination"), + ) + .await + .expect("the audit writer"), profile.key_hasher(), )); let loaded = config.load_package().expect("the package"); @@ -329,8 +331,11 @@ impl Harness { loaded.receipt_providers(), )); let metrics = Arc::new(Metrics::default()); + let admitted = config + .admitted_clients(package.access_profiles()) + .expect("the clients the runtime file admits"); let authenticator = Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&admitted), keys(), package.access_profiles().clone(), false, @@ -370,6 +375,13 @@ impl Harness { self.root.path().join("runtime.yaml") } + /// The clients the runtime file admits, derived from the package. + fn admitted(&self) -> AdmittedClients { + self.config + .admitted_clients(self.package.access_profiles()) + .expect("the clients the runtime file admits") + } + pub async fn publish(&self) {} /// Every record the journal holds, across its segments, oldest first @@ -497,7 +509,7 @@ impl Harness { )); router(HttpState { authenticator: Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&self.admitted()), keys(), profiles, false, @@ -539,7 +551,7 @@ impl Harness { )); router(HttpState { authenticator: Arc::new(MessagingAuthenticator::new( - verifier(), + verifier(&self.admitted()), keys(), self.package.access_profiles().clone(), false, @@ -693,7 +705,7 @@ fn write_runtime(root: &Path, package: &Path, database: &str, providers: Value) "issuer": ISSUER, "audience": AUDIENCE, "jwksSource": {"type": "static", "documentRef": format!("secret:env/{jwks_name}")}, - "allowedClients": ["case-system", "operations-console"] + "allowedClients": "from-package" }}, "audit": { "path": root.join("audit").join("messaging.jsonl"), @@ -711,7 +723,7 @@ fn write_runtime(root: &Path, package: &Path, database: &str, providers: Value) /// The runtime's verifier profile, with the symmetric test algorithm in /// place of the production asymmetric pair. -fn verifier() -> TokenVerifierConfig { +fn verifier(admitted: &AdmittedClients) -> TokenVerifierConfig { TokenVerifierConfig::access_token_profile( ISSUER, vec![AUDIENCE.to_owned()], @@ -719,10 +731,7 @@ fn verifier() -> TokenVerifierConfig { registry_platform_oidc::access_token_typ_set("at+jwt"), ) .with_scope_claim("registry_scopes") - .with_allowed_clients(vec![ - "case-system".to_owned(), - "operations-console".to_owned(), - ]) + .with_allowed_clients(admitted.as_slice().to_vec()) } fn keys() -> Arc { diff --git a/crates/registry-messaging/tests/token_characterisation.rs b/crates/registry-messaging/tests/token_characterisation.rs new file mode 100644 index 0000000000..55d1c23ddc --- /dev/null +++ b/crates/registry-messaging/tests/token_characterisation.rs @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of Messaging's bearer authentication against the token +//! fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `messaging` cell is run through the +//! authenticator the server builds: the verifier profile comes from a +//! `RuntimeConfig` loaded from a runtime file, the keys from that file's static +//! key source, and the credential goes through +//! `MessagingAuthenticator::authenticate`. No database is involved. +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use registry_messaging::auth::{AuthenticationError, MessagingAuthenticator}; +use registry_messaging::config::RuntimeConfig; +use registry_messaging::package::{package_inputs, write_package_inputs}; +use registry_messaging_core::{ + AccessProfile, AccessProfiles, ActorKind, ActsAs, MESSAGING_RUNTIME_API_VERSION, + MESSAGING_RUNTIME_KIND, +}; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + Against, ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:messaging"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +/// Clients the installed starter package names. The runtime refuses a +/// configuration whose allowed list omits a client of a package profile. +const PACKAGE_CLIENTS: [&str; 2] = ["case-system", "operations-console"]; +const PLACEHOLDER_SCOPE: &str = "records:get"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +fn profiles(case: &FixtureCase, scope: &str) -> AccessProfiles { + AccessProfiles::new(vec![AccessProfile { + id: "corpus".to_owned(), + label: None, + description: None, + principal_claim: "sub".to_owned(), + required_scopes: vec![scope.to_owned()], + requester_clients: vec![fixture_client(case)], + actor_kind: (case.against == Against::HumanOnlyProfile).then_some(ActorKind::Human), + acts_as: ActsAs::Operator, + sender_profiles: Vec::new(), + templates: Vec::new(), + allow_direct_content: false, + requests_per_minute: 60, + burst: 10, + maximum_messages_per_day: None, + }]) + .expect("a valid access profile") +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("issuer-jwks"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + let claim = scope_claim(&case); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); + let runtime_path = root.path().join("runtime.json"); + fs::write( + &runtime_path, + serde_json::to_vec(&json!({ + "apiVersion": MESSAGING_RUNTIME_API_VERSION, + "kind": MESSAGING_RUNTIME_KIND, + "identity": {"databaseId": "token-characterisation"}, + "package": {"root": package_root}, + "listener": {"bind": "127.0.0.1:0", "tlsTermination": "development-loopback"}, + "secretProviders": {"file": {"root": secrets}, "environment": {}}, + "database": { + "runtimeUrlRef": "secret:env/MESSAGING_RUNTIME_URL", + "migrationUrlRef": "secret:env/MESSAGING_MIGRATION_URL" + }, + "authentication": {"oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-jwks"}, + "allowedClients": [fixture_client(&case), PACKAGE_CLIENTS[0], PACKAGE_CLIENTS[1]], + "scopeClaim": claim + }}, + "audit": {"path": root.path().join("audit"), "hashKeyRef": "secret:file/audit-hash-key"} + })) + .expect("a runtime document"), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = config.secret_resolver().expect("the secret resolver"); + let keys = config + .jwks_fetcher(&resolver) + .await + .expect("the static key source"); + + let profiles = profiles(&case, &scope); + let admitted = config + .admitted_clients(&profiles) + .expect("the listed clients cover the profile"); + let authenticator = MessagingAuthenticator::new( + config.verifier_profile(&admitted), + Arc::clone(&keys), + profiles, + config.binds_assertion_issuers(), + ); + let token = case.token.expose(); + match authenticator.authenticate(token).await { + Ok(caller) => Outcome::Admitted(Some( + caller + .actor_kind + .map_or("unspecified", ActorKind::as_str) + .to_owned(), + )), + Err(AuthenticationError::Claims(_)) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { + let reference = TokenVerifier::new(config.verifier_profile(&admitted), keys); + match reference.verify(token).await { + Err(failure) => Outcome::refused_by(&failure), + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => refusal("header"), + } + } + } +} + +/// The published starter, installed as a package the runtime file can name. +fn installed_starter_package() -> tempfile::TempDir { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a package directory"); + let starter = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../products/messaging/examples/starter"); + let project = root.path().join("project"); + fs::create_dir_all(&project).expect("a project directory"); + fs::copy( + starter.join("messaging.yaml"), + project.join("messaging.yaml"), + ) + .expect("the starter manifest"); + copy_tree(&starter.join("templates"), &project.join("templates")); + copy_tree(&starter.join("providers"), &project.join("providers")); + let inputs = package_inputs(&project).expect("the starter package inputs"); + write_package_inputs(&root.path().join("package"), &inputs, None) + .expect("the installed starter package"); + root +} + +fn copy_tree(from: &Path, to: &Path) { + fs::create_dir_all(to).expect("a directory"); + for entry in fs::read_dir(from).expect("a directory to copy") { + let entry = entry.expect("a directory entry"); + let target = to.join(entry.file_name()); + if entry.file_type().expect("an entry type").is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).expect("a copied file"); + } + } +} + +#[tokio::test] +async fn messaging_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let installed = installed_starter_package(); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("messaging", &signer, ISSUER, AUDIENCE, |case| { + observe(installed.path().join("package"), case) + }) + .await + .expect("every messaging row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no messaging row ran"); + eprintln!( + "messaging: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/crates/registry-messagingctl/Cargo.toml b/crates/registry-messagingctl/Cargo.toml index 5260045d8c..2a3f50ee0a 100644 --- a/crates/registry-messagingctl/Cargo.toml +++ b/crates/registry-messagingctl/Cargo.toml @@ -17,6 +17,11 @@ name = "postgres_messages_cli" path = "tests/postgres_messages_cli.rs" required-features = ["postgres-test"] +[[test]] +name = "provision_postgres" +path = "tests/provision_postgres.rs" +required-features = ["postgres-test"] + [features] default = [] postgres-test = ["registry-messaging/postgres-test"] @@ -42,6 +47,7 @@ registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-httputil.workspace = true registry-platform-oidc.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling = { workspace = true, features = ["session"] } @@ -61,6 +67,7 @@ zeroize.workspace = true [dev-dependencies] registry-platform-audit.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } registry-platform-testing.workspace = true tokio-postgres.workspace = true tower.workspace = true diff --git a/crates/registry-messagingctl/src/dev/borrowed.rs b/crates/registry-messagingctl/src/dev/borrowed.rs index ec3287f8bb..186a489d31 100644 --- a/crates/registry-messagingctl/src/dev/borrowed.rs +++ b/crates/registry-messagingctl/src/dev/borrowed.rs @@ -18,8 +18,8 @@ use registry_messaging_core::{AccessProfile, ActorKind, Caller}; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::{PrivateKeyJwt, PrivateKeyJwtConfig, TokenProvider}; use registry_platform_oidc::{ - access_token_typ_set, parse_static_jwks, JwksFetcher, JwksFetcherConfig, TokenVerifier, - TokenVerifierConfig, + access_token_typ_set, parse_static_jwks, JwksFetcher, JwksFetcherConfig, OidcError, + TokenVerifier, TokenVerifierConfig, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -141,6 +141,17 @@ fn refusal() -> super::DevFailure { refused("the borrowed client could not authenticate with the Messaging profile; check the owner's client, resource, scopes and claims, then restart messagingctl dev".to_owned()) } +/// The refusal of the owner's key document. A document that breaks the shared +/// public-key rule says which rule, in words that carry no key value. +fn static_key_refusal(error: OidcError) -> super::DevFailure { + match error { + OidcError::StaticKeySet(rule) => refused(format!( + "the borrowed owner's secrets/jwks.json is not a usable static key set: {rule}" + )), + _ => refusal(), + } +} + fn runtime() -> DevResult { tokio::runtime::Builder::new_current_thread() .enable_all() @@ -378,7 +389,7 @@ pub(super) async fn verify( let bytes = private::read(&root.join("secrets/jwks.json"), 256 * 1024).map_err(|_| refusal())?; let keys = Arc::new(JwksFetcher::new_static( - parse_static_jwks(&bytes).map_err(|_| refusal())?, + parse_static_jwks(&bytes).map_err(static_key_refusal)?, JwksFetcherConfig::defaults(), )); let verifier = TokenVerifierConfig::access_token_profile( @@ -391,9 +402,7 @@ pub(super) async fn verify( access_token_typ_set("at+jwt"), ) .with_scope_claim("scope") - .with_allowed_clients(crate::identity_facts::requester_clients( - loaded.package.access_profiles(), - )); + .with_allowed_clients(loaded.package.access_profiles().requester_clients()); let verified = TokenVerifier::new(verifier.clone(), keys.clone()) .verify(signed) .await diff --git a/crates/registry-messagingctl/src/dev/borrowed_tests.rs b/crates/registry-messagingctl/src/dev/borrowed_tests.rs index 30118cf28e..3cb90efc2b 100644 --- a/crates/registry-messagingctl/src/dev/borrowed_tests.rs +++ b/crates/registry-messagingctl/src/dev/borrowed_tests.rs @@ -675,3 +675,27 @@ fn a_stop_request_during_the_export_stops_bregctl() { assert!(fixture.exported_files().is_empty()); assert!(!fixture.snapshot().exists()); } + +#[test] +fn a_key_document_that_breaks_the_public_key_rule_names_the_rule() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"a","n":"AQAB","e":"AQAB","d":"canary-private-value"}]}"#, + ) + .expect_err("a private member is refused"); + let failure = static_key_refusal(error); + assert_eq!(failure.code, "dev.refused"); + assert!( + failure.message.contains("private-key member \"d\""), + "{}", + failure.message + ); + assert!(!failure.message.contains("canary-private-value")); +} + +#[test] +fn any_other_key_document_refusal_keeps_the_generic_message() { + assert_eq!( + static_key_refusal(registry_platform_oidc::OidcError::Parse).message, + refusal().message + ); +} diff --git a/crates/registry-messagingctl/src/dev/config.rs b/crates/registry-messagingctl/src/dev/config.rs index 59f2f83381..f3af4b62c9 100644 --- a/crates/registry-messagingctl/src/dev/config.rs +++ b/crates/registry-messagingctl/src/dev/config.rs @@ -242,8 +242,6 @@ fn runtime_members( loaded: &LoadedPackage, endpoints: &Endpoints, ) -> Value { - let allowed_clients = - crate::identity_facts::requester_clients(loaded.package.access_profiles()); let providers: serde_json::Map = loaded .package .providers() @@ -309,7 +307,7 @@ fn runtime_members( "authentication": {"oidc": { "issuer": ISSUER, "audience": AUDIENCE, - "allowedClients": allowed_clients, + "allowedClients": "from-package", // The session's signing key is generated beside this file, so // the runtime reads its key set directly. "jwksSource": {"type": "static", "documentRef": "secret:file/jwks.json"}, diff --git a/crates/registry-messagingctl/src/identity_facts.rs b/crates/registry-messagingctl/src/identity_facts.rs index 5f556348c9..74a62c247a 100644 --- a/crates/registry-messagingctl/src/identity_facts.rs +++ b/crates/registry-messagingctl/src/identity_facts.rs @@ -15,7 +15,7 @@ use std::path::Path; use registry_messaging::config::RuntimeConfig; use registry_messaging::package::LoadedPackage; -use registry_messaging_core::{AccessProfiles, ActorKind}; +use registry_messaging_core::ActorKind; use registry_thunderid_tooling::identity_facts::{ self, AccessProfile as FactsProfile, ActorKind as FactsActorKind, Admission, ClaimType, IdentityFacts, @@ -31,17 +31,6 @@ const DEFAULT_SCOPE_CLAIM: &str = "scope"; /// one of these grants no scope without a mapping Messaging does not offer. const RESERVED_SCOPE_CLAIMS: [&str; 4] = ["sub", "client_id", "azp", "aud"]; -/// The clients the package's access profiles name, sorted and distinct. -pub(crate) fn requester_clients(profiles: &AccessProfiles) -> Vec { - let mut clients: Vec = profiles - .iter() - .flat_map(|profile| profile.requester_clients.iter().cloned()) - .collect(); - clients.sort(); - clients.dedup(); - clients -} - #[derive(Debug)] pub(crate) enum FactsError { /// A profile cannot be stated as facts; the message names no value. @@ -71,12 +60,10 @@ pub(crate) fn facts( loaded: &LoadedPackage, ) -> Result { let oidc = &config.authentication.oidc; - let admitted = &oidc.clients.allowed_clients; - let allowed = if admitted.is_empty() { - Admission::Unrestricted - } else { - Admission::Clients(admitted.clone()) - }; + let admitted = config + .admitted_clients(loaded.package.access_profiles()) + .map_err(|error| FactsError::Unstatable(error.to_string()))?; + let allowed = Admission::Clients(admitted.into_vec()); let mut facts = IdentityFacts::new( PRODUCT, oidc.provider.issuer.as_str(), @@ -103,16 +90,6 @@ pub(crate) fn facts( profile.id ))); } - if let Some(client) = profile - .requester_clients - .iter() - .find(|client| !allowed.admits(client)) - { - return Err(FactsError::Unstatable(format!( - "the access profile `{}` names the client `{client}`, which authentication.oidc.allowedClients does not admit", - profile.id - ))); - } if profile.principal_claim != "sub" { facts .claims diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index ae3a3402f0..22bd26eb93 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -12,6 +12,8 @@ //! reports the package digest and renders every template's sample. //! - `preview` renders one template version with given data, offline, and //! in JSON prints the exact bytes the runtime's preview route answers. +//! - `provision` creates the roles and the database the runtime file names, +//! or with `--print-sql` prints the SQL that does. //! - `plan` reads the configured package, activation ledger, schema, and //! runtime role without writing; `apply` performs that activation with //! migration authority; `status` reads the resulting history with the @@ -80,6 +82,7 @@ use uuid::Uuid; mod cli_contract_tests; mod dev; mod identity_facts; +mod provision; mod report; mod selected_binary; mod starter; @@ -117,6 +120,8 @@ enum Command { Check(CheckArgs), /// Render one template version with the given data, offline. Preview(PreviewArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Report what activating the configured package would change, without writing. Plan(ActivationArgs), /// Apply schema changes and record the configured package as active. @@ -742,6 +747,7 @@ where let command = command_path(&cli.command); let outcome = match cli.command { Command::Serve(args) => return serve(args, cli.format, format_requested, stdout, stderr), + Command::Provision(args) => return provision(&args, cli.format), Command::Dev(args) => return dev::run(args, cli.format, stdout, stderr), Command::RstackDev(args) => return registry_rstack_dev::run(args, stdout, stderr), Command::Api(args) => return api(*args, format_requested, stderr), @@ -773,6 +779,7 @@ fn command_path(command: &Command) -> &'static str { Command::Generate(GenerateCommand::IdentityFacts(_)) => "generate identity-facts", Command::Check(_) => "check", Command::Preview(_) => "preview", + Command::Provision(_) => "provision", Command::Plan(_) => "plan", Command::Apply(_) => "apply", Command::Status(_) => "status", @@ -789,6 +796,23 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "messagingctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn api( args: registry_cli_api::ApiArgs, format_requested: bool, diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs new file mode 100644 index 0000000000..d5ad9e28de --- /dev/null +++ b/crates/registry-messagingctl/src/provision.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision`: the shared command over Messaging's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_messaging::config::{startup_report, RuntimeConfig}; +use registry_messaging_core::MESSAGING_RUNTIME_KIND; +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use zeroize::Zeroizing; + +/// Messaging keeps its tables in `public`. `provision` gives the migration role +/// USAGE and CREATE on it and the runtime role USAGE, directly. It needs no +/// extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "messaging", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(MESSAGING_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_providers.resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs new file mode 100644 index 0000000000..dcb70b1813 --- /dev/null +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file over a built package, whose secret files name a migration +/// and a runtime login on one server that does not exist, so a connection +/// attempt could only fail. +fn write_runtime(directory: &Path) -> String { + write_runtime_for(directory, "messaging") +} + +/// [`write_runtime`] with the database name both URLs end in, written as the +/// URL path holds it (percent-encoded where a name needs it). +fn write_runtime_for(directory: &Path, database: &str) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://messaging_migration:{MIGRATION_PASSWORD}@db.invalid:5432/{database}" + ), + ), + ( + "runtime-database-url", + format!("postgresql://messaging_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/{database}"), + ), + ("audit-key", "5a".repeat(16)), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The loader verifies the package the file names, as `apply` does. + let project = directory.join("project"); + let package = directory.join("package"); + for arguments in [ + vec!["init", project.to_str().unwrap()], + vec![ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ], + ] { + let output = ctl(&arguments); + assert_eq!(output.status.code(), Some(0), "{arguments:?}"); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/messaging/runtime/v1alpha1 +kind: MessagingRuntimeConfig +identity: + databaseId: registry-messaging-ctl-test +package: + root: {package} +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:messaging + allowedClients: [case-system, operations-console] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +", + package = package.display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_messagingctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn a_database_name_that_is_a_connection_uri_is_refused_in_print_mode() { + let directory = scratch(); + let runtime = write_runtime_for(directory.path(), "postgresql%3A%2F%2Fevil.example%2Fx"); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(2), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!( + diagnostic["code"], "platform.provision.target-invalid", + "{report:#}" + ); + assert_eq!(report["executed"], false, "{report:#}"); + assert!( + !report.to_string().contains("evil.example"), + "the refused name is not repeated: {report:#}" + ); +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["messaging_migration", "messaging_runtime"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!(stdout.contains("CREATE DATABASE \"messaging\""), "{stdout}"); + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "messaging"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "messaging"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The tool's global flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for (arguments, message) in [ + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + "conflicting use of --admin-url-file", + ), + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "MESSAGING_ADMIN_URL", + ], + "conflicting use of --print-sql", + ), + ( + vec!["provision", "--runtime-config", &runtime], + "missing required argument --admin-url-file, --admin-url-env", + ), + ] { + let output = ctl(&arguments); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}"); + assert!(output.stdout.is_empty(), "{arguments:?}"); + assert!(stderr.contains(message), "{arguments:?}: {stderr}"); + } +} + +/// The refusal `provision --print-sql --format json` reports, with the exit +/// code. The reports carry no password, so neither does their text. +fn refusal(runtime: &str) -> (Option, serde_json::Value) { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!( + !stdout.contains(secret), + "stdout holds no password: {stdout}" + ); + assert!( + !stderr.contains(secret), + "stderr holds no password: {stderr}" + ); + } + let report = serde_json::from_str(&stdout) + .unwrap_or_else(|error| panic!("a JSON report: {error}: {stdout}{stderr}")); + (output.status.code(), report) +} + +fn first_diagnostic(report: &serde_json::Value) -> &serde_json::Value { + &report["diagnostics"][0] +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(1), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); + assert_eq!(diagnostic["path"], "/database/runtimeUrlRef", "{report:#}"); +} + +#[test] +fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let secret = directory.path().join("secrets/migration-database-url"); + std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(1), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); + assert_eq!( + diagnostic["path"], "/database/migrationUrlRef", + "{report:#}" + ); + assert!( + diagnostic["message"] + .as_str() + .unwrap() + .contains("not UTF-8"), + "{report:#}" + ); +} + +#[test] +fn a_runtime_file_that_does_not_load_is_refused_before_any_database_work() { + let directory = scratch(); + let missing = directory.path().join("no-such-runtime.yaml"); + let (code, report) = refusal(missing.to_str().unwrap()); + assert_eq!(code, Some(1), "{report:#}"); + assert_eq!(report["executed"], false, "{report:#}"); + assert!( + !first_diagnostic(&report)["code"] + .as_str() + .unwrap() + .is_empty(), + "{report:#}" + ); +} diff --git a/crates/registry-messagingctl/tests/provision_postgres.rs b/crates/registry-messagingctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..2b9be2835f --- /dev/null +++ b/crates/registry-messagingctl/tests/provision_postgres.rs @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `messagingctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let deployment = Self { directory, admin }; + deployment.secret("audit-key", &"5a".repeat(16)); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + deployment.secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write or replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + /// Write the runtime document over `package`, listening on `bind`, with + /// the database connections verified against the CA secret. + fn write_runtime(&self, package: &std::path::Path, bind: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/messaging/runtime/v1alpha1 +kind: MessagingRuntimeConfig +identity: + databaseId: registry-messaging-ctl-test +package: + root: {package} +listener: + bind: {bind} + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:messaging + allowedClients: [case-system, operations-console] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + destination: file + path: {audit} + hashKeyRef: secret:file/audit-key +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_messagingctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its readiness route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + let project = deployment.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project]); + assert_eq!(code, 0, "{report:#}"); + let package = deployment.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + deployment.write_runtime(&package, &bind); + let runtime = deployment.runtime(); + + let (base_url, ca) = provision_test_env(); + deployment.secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("messaging_owner_{suffix}"), + format!("messaging_mig_{suffix}"), + format!("messaging_rt_{suffix}"), + format!("messaging_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!(statement["outcome"], "created", "{statement}"); + } + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + + let server = tokio::spawn({ + let runtime = runtime.clone(); + async move { + registry_messaging::runtime::serve_from_path( + &runtime, + registry_messaging::dispatch::Transports::new(), + ) + .await + } + }); + let mut ready = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + ready = http_status(&bind, "/ready").await; + if ready == Some(200) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the service stopped instead of serving: {outcome:?}"); + } + assert_eq!(ready, Some(200), "the service never reported ready"); + server.abort(); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-payment-client/src/client.rs b/crates/registry-payment-client/src/client.rs index 37c2303fe0..a3a24934cc 100644 --- a/crates/registry-payment-client/src/client.rs +++ b/crates/registry-payment-client/src/client.rs @@ -14,7 +14,8 @@ use registry_platform_httputil::client::{ ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, retry_after_seconds, url::append_path_segments, validate_response_headers, + read_bounded, retry_after_seconds, url::append_path_segments, + validate_response_headers_without_peer_policy, }; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{Response, StatusCode, Url}; @@ -382,7 +383,7 @@ impl PaymentClient { .map_err(|error| PaymentClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), PaymentProtocolFailure::HeaderBounds, diff --git a/crates/registry-payment-simulator-connector/src/lib.rs b/crates/registry-payment-simulator-connector/src/lib.rs index 74943d22ed..2b6d1d68fb 100644 --- a/crates/registry-payment-simulator-connector/src/lib.rs +++ b/crates/registry-payment-simulator-connector/src/lib.rs @@ -3,6 +3,7 @@ use registry_payment_protocol::{CollectionState, Money, MAX_MINOR_UNITS}; use registry_platform_httputil::client::{build_client, BearerToken, OutboundOptions}; +use registry_platform_httputil::loopback::loopback_address; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use std::time::Duration; @@ -67,9 +68,10 @@ impl SimulatorConnection { registry_platform_yaml::Url::new(self.callback_url.clone()) .map_err(|_| ConnectorError::Configuration)?; let url = Url::parse(&self.base_url).map_err(|_| ConnectorError::Configuration)?; + // An address literal only: the name `localhost` is refused. let loopback = match url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback(), - Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Ipv4(ip)) => loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => loopback_address(ip.into()), _ => false, }; if !loopback diff --git a/crates/registry-payment-simulator-connector/tests/profile.rs b/crates/registry-payment-simulator-connector/tests/profile.rs index 1c9707b679..bb3fef6480 100644 --- a/crates/registry-payment-simulator-connector/tests/profile.rs +++ b/crates/registry-payment-simulator-connector/tests/profile.rs @@ -43,6 +43,23 @@ fn synthetic_transport_cannot_point_to_live_or_named_remote_hosts() { } } #[test] +fn the_synthetic_transport_takes_loopback_address_literals_and_no_name() { + for base in ["http://127.0.0.1/", "http://[::1]/"] { + let mut config = connection(); + config.base_url = base.into(); + assert!(config.validate().is_ok(), "{base}"); + } + for base in [ + "http://localhost/", + "http://10.0.0.1/", + "http://a.localhost/", + ] { + let mut config = connection(); + config.base_url = base.into(); + assert!(config.validate().is_err(), "{base}"); + } +} +#[test] fn request_amount_is_an_exact_json_number_even_near_the_portable_bound() { let mut cmd = command(); cmd.money.value = "90071992547409.91".into(); diff --git a/crates/registry-platform-activation/Cargo.toml b/crates/registry-platform-activation/Cargo.toml index a616318915..b6cbc675dd 100644 --- a/crates/registry-platform-activation/Cargo.toml +++ b/crates/registry-platform-activation/Cargo.toml @@ -19,6 +19,7 @@ schema = ["dep:schemars"] [dependencies] schemars = { workspace = true, optional = true, features = ["chrono04", "uuid1"] } chrono = { workspace = true, features = ["serde"] } +registry-platform-posture.workspace = true serde.workspace = true thiserror.workspace = true tokio-postgres.workspace = true diff --git a/crates/registry-platform-activation/README.md b/crates/registry-platform-activation/README.md index ed8a9fdab1..41c607242a 100644 --- a/crates/registry-platform-activation/README.md +++ b/crates/registry-platform-activation/README.md @@ -3,7 +3,11 @@ `registry-platform-activation` is the single PostgreSQL implementation of the package activation ledger and its runtime-role boundary for the stateful Registry Stack products. Activation and runtime checks require PostgreSQL 17 -or newer, matching the maintained database support floor. +or newer, matching the maintained database support floor. The crate exports +the floor as `MINIMUM_SERVER_VERSION_NUM` (`170_000`). The one technical +reason found for it is BReg's: its closed-catalog check expects every managed +table to grant the `MAINTAIN` privilege, which PostgreSQL introduced in +version 17 (`registry-breg/src/postgres/schema.rs`). The crate owns the product-neutral parts of activation: ledger reads and appends, deployment database identity checks, active-package startup checks, diff --git a/crates/registry-platform-activation/src/lib.rs b/crates/registry-platform-activation/src/lib.rs index 2c47cab6e3..e138a34a81 100644 --- a/crates/registry-platform-activation/src/lib.rs +++ b/crates/registry-platform-activation/src/lib.rs @@ -2,6 +2,7 @@ //! Shared PostgreSQL package activation ledger and runtime-role boundary. use chrono::{DateTime, Utc}; +use registry_platform_posture::Posture; use serde::Serialize; use tokio_postgres::GenericClient; use uuid::Uuid; @@ -12,7 +13,7 @@ pub const SINGLE_ROLE_STATEMENT: &str = const ACTIVATION_COLUMNS: &str = "activation_id,apply_order,package_digest,\ predecessor_package_digest,database_id,plan_kind,applied_at,\ - operator_reference_hash,backup_references,role_mode"; + operator_reference_hash,backup_references,role_mode,posture"; /// One trigger installed by a product migration and therefore allowed on a /// product-owned relation in split-role mode. @@ -189,6 +190,10 @@ pub struct Activation { pub operator_reference_hash: Option, pub backup_references: Vec, pub role_mode: RoleMode, + /// The posture the activating process declared. + #[serde(serialize_with = "serialize_posture")] + #[cfg_attr(feature = "schema", schemars(with = "String"))] + pub posture: Posture, /// Present for ledgers that retain the PostgreSQL runtime user. #[serde(skip_serializing_if = "Option::is_none")] pub runtime_role: Option, @@ -202,9 +207,48 @@ pub struct NewActivation<'a> { pub operator_reference_hash: Option<&'a str>, pub backup_references: &'a [String], pub role_mode: RoleMode, + pub posture: Posture, pub runtime_role: Option<&'a str>, } +impl<'a> NewActivation<'a> { + /// Builds a request that records the production posture. Callers that + /// do not yet declare a posture use this, and it is the only + /// constructor that picks one on their behalf. + #[must_use] + pub fn without_posture( + activation_id: Uuid, + package_digest: &'a str, + database_id: &'a str, + operator_reference_hash: Option<&'a str>, + backup_references: &'a [String], + role_mode: RoleMode, + runtime_role: Option<&'a str>, + ) -> Self { + Self { + activation_id, + package_digest, + database_id, + operator_reference_hash, + backup_references, + role_mode, + posture: Posture::Production, + runtime_role, + } + } +} + +fn parse_posture(value: &str) -> Result { + Posture::parse(value).ok_or(Error::Corrupt) +} + +fn serialize_posture( + posture: &Posture, + serializer: S, +) -> Result { + serializer.serialize_str(posture.as_str()) +} + /// How a configured deployment identity compares with the ledger. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -280,8 +324,18 @@ pub async fn relation_exists(client: &impl GenericClient, relation: &str) -> Res Ok(row.get(1)) } +/// Lowest `server_version_num` every Registry Stack product that uses this +/// ledger accepts (PostgreSQL 17). +/// +/// The recorded reason is the maintained database support floor +/// (`README.md`). The one technical reason found is BReg's: its closed-catalog +/// check expects every managed table to grant the MAINTAIN privilege, which +/// PostgreSQL introduced in version 17 +/// (`registry-breg/src/postgres/schema.rs`, `MIN_POSTGRES_VERSION_NUM`). +pub const MINIMUM_SERVER_VERSION_NUM: i32 = 170_000; + fn verify_postgres_version(version_num: i32) -> Result<(), Error> { - if version_num < 170_000 { + if version_num < MINIMUM_SERVER_VERSION_NUM { return Err(Error::UnsupportedPostgres); } Ok(()) @@ -295,11 +349,11 @@ pub async fn active_activation( if !relation_exists(client, layout.ledger_relation).await? { return Ok(None); } - let columns = activation_columns(layout); + let columns = read_columns(layout); client .query_opt( &format!( - "SELECT {columns} FROM {} ORDER BY apply_order DESC LIMIT 1", + "SELECT {columns} FROM {} AS ledger_row ORDER BY apply_order DESC LIMIT 1", layout.ledger_relation ), &[], @@ -318,11 +372,11 @@ pub async fn activation_history( if !relation_exists(client, layout.ledger_relation).await? { return Ok(Vec::new()); } - let columns = activation_columns(layout); + let columns = read_columns(layout); client .query( &format!( - "SELECT {columns} FROM {} ORDER BY apply_order", + "SELECT {columns} FROM {} AS ledger_row ORDER BY apply_order", layout.ledger_relation ), &[], @@ -341,6 +395,18 @@ fn activation_columns(layout: &Layout) -> String { } } +/// The columns a read selects, in the order `activation_from_row` expects, from +/// a relation aliased `ledger_row`. A ledger that predates the `posture` +/// column has no such field, and its rows read as production. +fn read_columns(layout: &Layout) -> String { + let columns = activation_columns(layout); + columns.replacen( + ",posture", + ",COALESCE(to_jsonb(ledger_row) ->> 'posture','production') AS posture", + 1, + ) +} + fn activation_from_row(row: &tokio_postgres::Row, layout: &Layout) -> Result { Ok(Activation { activation_id: row.try_get(0)?, @@ -353,8 +419,9 @@ fn activation_from_row(row: &tokio_postgres::Row, layout: &Layout) -> Result, expected: &str) -> Databas } } -/// Verify the package and database identity a runtime must serve. +/// Verify the package and database identity a runtime must serve, and that +/// the ledger recorded the posture the process declares. +/// +/// A posture mismatch is a distinct error that carries both postures, so a +/// caller that only reports (such as `doctor`) can match it and continue. pub async fn check_active_package( client: &impl GenericClient, layout: &Layout, database_id: &str, package_digest: &str, + declared: Posture, ) -> Result { let active = active_activation(client, layout) .await? @@ -474,9 +548,33 @@ pub async fn check_active_package( candidate: package_digest.to_owned(), }); } + if active.posture != declared { + return Err(ActivePackageError::PostureMismatch { + recorded: active.posture, + declared, + }); + } Ok(active) } +/// [`check_active_package`] for callers that do not yet declare a posture: +/// it checks as production. +pub async fn check_active_package_without_posture( + client: &impl GenericClient, + layout: &Layout, + database_id: &str, + package_digest: &str, +) -> Result { + check_active_package( + client, + layout, + database_id, + package_digest, + Posture::Production, + ) + .await +} + #[derive(Debug, thiserror::Error)] pub enum ActivePackageError { #[error("no package is active")] @@ -485,6 +583,15 @@ pub enum ActivePackageError { DatabaseIdMismatch, #[error("package {candidate} is not active; the database serves {active}")] PackageNotActive { active: String, candidate: String }, + #[error( + "the database was activated in the {} posture and this process declares {}", + .recorded.as_str(), + .declared.as_str() + )] + PostureMismatch { + recorded: Posture, + declared: Posture, + }, #[error(transparent)] Activation(#[from] Error), } @@ -1019,6 +1126,11 @@ mod tests { } } + #[test] + fn postgres_floor_constant_is_version_17() { + assert_eq!(MINIMUM_SERVER_VERSION_NUM, 170_000); + } + #[test] fn layouts_accept_only_unquoted_postgres_identifiers() { assert!(Layout::new( diff --git a/crates/registry-platform-activation/tests/postgres_activation.rs b/crates/registry-platform-activation/tests/postgres_activation.rs index 51450f557e..e0d6d85eda 100644 --- a/crates/registry-platform-activation/tests/postgres_activation.rs +++ b/crates/registry-platform-activation/tests/postgres_activation.rs @@ -6,6 +6,7 @@ use registry_platform_activation::{ observe_role, stray_authority, ActivePackageError, AuthorityCause, DatabaseIdCheck, Layout, NewActivation, PlanKind, RoleMode, }; +use registry_platform_posture::Posture; use tokio_postgres::NoTls; use uuid::Uuid; @@ -57,7 +58,8 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { applied_at timestamptz NOT NULL, operator_reference_hash text, backup_references text[] NOT NULL, - role_mode text NOT NULL CHECK(role_mode IN ('single','split')) + role_mode text NOT NULL CHECK(role_mode IN ('single','split')), + posture text NOT NULL CHECK(posture IN ('development','production')) );" )) .await @@ -90,6 +92,7 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { operator_reference_hash: None, backup_references: &[], role_mode: role.mode, + posture: Posture::Production, runtime_role: None, }, ) @@ -118,6 +121,7 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { &layout(), "fixture-database", "sha256:fixture", + Posture::Production, ) .await .expect("accept exact active package"); @@ -126,7 +130,8 @@ async fn ledger_identity_and_split_role_share_one_postgres_boundary() { &transaction, &layout(), "another-database", - "sha256:fixture" + "sha256:fixture", + Posture::Production ) .await, Err(ActivePackageError::DatabaseIdMismatch) @@ -612,3 +617,292 @@ async fn postgres_version_floor_precedes_missing_ledger_observation() { .expect("connection task") .expect("connection closes"); } + +const POSTURE_FIXTURE_LEDGER: &str = "CREATE TABLE fixture_schema_migrations( + version bigint PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + ); + CREATE TABLE fixture_activations( + activation_id uuid PRIMARY KEY, + apply_order bigint NOT NULL UNIQUE, + package_digest text NOT NULL, + predecessor_package_digest text, + database_id text NOT NULL, + plan_kind text NOT NULL CHECK(plan_kind IN ('initial','successor')), + applied_at timestamptz NOT NULL, + operator_reference_hash text, + backup_references text[] NOT NULL, + role_mode text NOT NULL CHECK(role_mode IN ('single','split')) + );"; + +/// The migration every product ledger applies to gain the column. +const POSTURE_MIGRATION: &str = + "ALTER TABLE fixture_activations ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); + ALTER TABLE fixture_activations ALTER COLUMN posture DROP DEFAULT;"; + +struct PostureFixture { + client: tokio_postgres::Client, + schema: String, + connection_task: tokio::task::JoinHandle>, +} + +impl PostureFixture { + async fn new(ledger_sql: &str) -> Self { + let (client, connection) = tokio_postgres::connect(&database_url(), NoTls) + .await + .expect("connect to disposable PostgreSQL"); + let connection_task = tokio::spawn(connection); + let schema = format!("posture_{}", Uuid::new_v4().simple()); + client + .batch_execute(&format!( + "CREATE SCHEMA {schema}; SET search_path TO {schema}; {ledger_sql}" + )) + .await + .expect("create posture fixture"); + Self { + client, + schema, + connection_task, + } + } + + async fn finish(self) { + self.client + .batch_execute(&format!( + "RESET search_path; DROP SCHEMA {} CASCADE;", + self.schema + )) + .await + .expect("remove posture fixture"); + drop(self.client); + self.connection_task + .await + .expect("join PostgreSQL connection") + .expect("PostgreSQL connection completes"); + } +} + +async fn append( + client: &tokio_postgres::Client, + posture: Posture, +) -> registry_platform_activation::Activation { + append_activation( + client, + &layout(), + &NewActivation { + activation_id: Uuid::new_v4(), + package_digest: "sha256:fixture", + database_id: "fixture-database", + operator_reference_hash: None, + backup_references: &[], + role_mode: RoleMode::Single, + posture, + runtime_role: None, + }, + ) + .await + .expect("append activation") +} + +#[tokio::test] +async fn append_activation_round_trips_the_posture() { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + for posture in [Posture::Development, Posture::Production] { + let fresh = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + let appended = append(&fresh.client, posture).await; + assert_eq!(appended.posture, posture); + let read = active_activation(&fresh.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, posture); + assert_eq!( + activation_history(&fresh.client, &layout()) + .await + .expect("history"), + vec![appended] + ); + fresh.finish().await; + } + fixture.finish().await; +} + +#[tokio::test] +async fn check_active_package_reports_a_posture_mismatch_in_both_directions() { + for (recorded, declared) in [ + (Posture::Production, Posture::Development), + (Posture::Development, Posture::Production), + ] { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + append(&fixture.client, recorded).await; + let result = check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + declared, + ) + .await; + match result { + Err(ActivePackageError::PostureMismatch { + recorded: seen, + declared: asked, + }) => { + assert_eq!((seen, asked), (recorded, declared)); + let message = ActivePackageError::PostureMismatch { + recorded: seen, + declared: asked, + } + .to_string(); + assert!(message.contains(recorded.as_str()) && message.contains(declared.as_str())); + } + other => panic!("expected a posture mismatch, got {other:?}"), + } + let matching = check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + recorded, + ) + .await + .expect("matching posture is accepted"); + assert_eq!(matching.posture, recorded); + fixture.finish().await; + } +} + +#[tokio::test] +async fn the_transitional_check_and_constructor_behave_as_production() { + let fixture = + PostureFixture::new(&format!("{POSTURE_FIXTURE_LEDGER}{POSTURE_MIGRATION}")).await; + let request = NewActivation::without_posture( + Uuid::new_v4(), + "sha256:fixture", + "fixture-database", + None, + &[], + RoleMode::Single, + None, + ); + assert_eq!(request.posture, Posture::Production); + append_activation(&fixture.client, &layout(), &request) + .await + .expect("append"); + registry_platform_activation::check_active_package_without_posture( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + ) + .await + .expect("production row passes the transitional check"); + fixture.finish().await; +} + +#[tokio::test] +async fn a_row_from_before_the_migration_reads_production() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single');", + ) + .await + .expect("insert a pre-migration row"); + fixture + .client + .batch_execute(POSTURE_MIGRATION) + .await + .expect("apply the posture migration"); + let read = active_activation(&fixture.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, Posture::Production); + check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + Posture::Production, + ) + .await + .expect("a legacy row serves production"); + assert!(matches!( + check_active_package( + &fixture.client, + &layout(), + "fixture-database", + "sha256:fixture", + Posture::Development, + ) + .await, + Err(ActivePackageError::PostureMismatch { + recorded: Posture::Production, + declared: Posture::Development + }) + )); + // The default is dropped, so an insert that names no posture fails. + let missing = fixture + .client + .batch_execute( + "INSERT INTO fixture_activations(activation_id, apply_order, package_digest, + database_id, plan_kind, applied_at, backup_references, role_mode) + VALUES(gen_random_uuid(), 2, 'sha256:x', 'd', 'successor', now(), '{}', 'single');", + ) + .await; + assert!(missing.is_err(), "the migration leaves no posture default"); + fixture.finish().await; +} + +#[tokio::test] +async fn an_unknown_recorded_posture_is_corrupt() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "ALTER TABLE fixture_activations ADD COLUMN posture text NOT NULL DEFAULT 'staging'; + INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single', 'staging');", + ) + .await + .expect("insert an unknown posture"); + assert!(matches!( + active_activation(&fixture.client, &layout()).await, + Err(registry_platform_activation::Error::Corrupt) + )); + fixture.finish().await; +} + +#[tokio::test] +async fn a_ledger_without_the_posture_column_reads_production() { + let fixture = PostureFixture::new(POSTURE_FIXTURE_LEDGER).await; + fixture + .client + .batch_execute( + "INSERT INTO fixture_activations VALUES( + '00000000-0000-0000-0000-000000000001', 1, 'sha256:fixture', NULL, + 'fixture-database', 'initial', now(), NULL, '{}', 'single');", + ) + .await + .expect("insert a pre-migration row"); + let read = active_activation(&fixture.client, &layout()) + .await + .expect("read active") + .expect("one row"); + assert_eq!(read.posture, Posture::Production); + let history = activation_history(&fixture.client, &layout()) + .await + .expect("read history"); + assert_eq!(history.len(), 1); + assert_eq!(history[0].posture, Posture::Production); + fixture.finish().await; +} diff --git a/crates/registry-platform-audit/Cargo.toml b/crates/registry-platform-audit/Cargo.toml index b0f28e8d03..b39ba440da 100644 --- a/crates/registry-platform-audit/Cargo.toml +++ b/crates/registry-platform-audit/Cargo.toml @@ -15,6 +15,7 @@ schema = ["dep:schemars"] [dependencies] hmac.workspace = true +registry-platform-posture.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } serde.workspace = true diff --git a/crates/registry-platform-audit/README.md b/crates/registry-platform-audit/README.md index 29e50b782f..46aa5b2c82 100644 --- a/crates/registry-platform-audit/README.md +++ b/crates/registry-platform-audit/README.md @@ -6,7 +6,7 @@ authorization event shape for Registry Stack services. ## What It Provides - `AuditWriter`, the one audit writer every product uses. It appends one JSON - object per line (`schema`, `eventId`, `time`, `phase`, `correlation`, + object per line (`schema`, `eventId`, `time`, `phase`, `posture`, `correlation`, `record`): a `request` entry before protected I/O and a `response` entry with the outcome, both carrying the same `correlation`. - `AuditDestination::File` (durable: fsync with group commit, size rotation, @@ -23,12 +23,18 @@ authorization event shape for Registry Stack services. across products, using pseudonyms from each product's existing audit profile. - `require_audit_under` to keep an audit path under a persistent root. +Every new journal line records the writer's declared `posture` as +`development` or `production`. The transitional constructors record +`production`. Readers accept a missing posture on historical lines and +refuse a present value outside those two spellings. + ## Typical Use ```rust use registry_platform_audit::{ AuditDestination, AuditEntry, AuditProfile, AuditWriter, FileDestination, }; +use registry_platform_posture::Posture; use serde_json::json; use zeroize::Zeroizing; @@ -36,7 +42,7 @@ async fn write_audit_entries() -> Result<(), Box> { let master_secret = Zeroizing::new(std::fs::read("/run/secrets/registry-audit-hash")?); let profile = AuditProfile::production_from_secret_bytes(master_secret)?; let destination = FileDestination::new("/var/lib/registry/audit/audit.jsonl")?; - let writer = AuditWriter::open(AuditDestination::File(destination)).await?; + let writer = AuditWriter::open(AuditDestination::File(destination), Posture::Production).await?; let subject_ref = profile.key_hasher().hash("did:example:123"); writer diff --git a/crates/registry-platform-audit/src/lib.rs b/crates/registry-platform-audit/src/lib.rs index d76f458f70..d598e5a189 100644 --- a/crates/registry-platform-audit/src/lib.rs +++ b/crates/registry-platform-audit/src/lib.rs @@ -29,8 +29,9 @@ mod writer; pub use writer::{ AuditDestination, AuditDestinationError, AuditDestinationKind, AuditEntry, AuditPhase, AuditRequest, AuditSegments, AuditUnavailable, AuditUnavailableReason, AuditWriter, - FileDestination, SealedSegment, ABSOLUTE_AUDIT_PATH_PATTERN, DEFAULT_AUDIT_RETAIN_DAYS, - DEFAULT_AUDIT_ROTATE_BYTES, MAX_AUDIT_RETAIN_DAYS, MIN_AUDIT_ROTATE_BYTES, + FileDestination, SealedSegment, StoredAuditEntry, ABSOLUTE_AUDIT_PATH_PATTERN, + DEFAULT_AUDIT_RETAIN_DAYS, DEFAULT_AUDIT_ROTATE_BYTES, MAX_AUDIT_RETAIN_DAYS, + MIN_AUDIT_ROTATE_BYTES, }; use std::{ diff --git a/crates/registry-platform-audit/src/writer.rs b/crates/registry-platform-audit/src/writer.rs index 2109d6d39f..d0e43926bd 100644 --- a/crates/registry-platform-audit/src/writer.rs +++ b/crates/registry-platform-audit/src/writer.rs @@ -33,6 +33,7 @@ use std::{ time::{Duration, Instant, SystemTime}, }; +use registry_platform_posture::Posture; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use thiserror::Error; @@ -188,7 +189,7 @@ impl AuditEntry { &self.record } - fn to_line(&self) -> Result { + fn to_line(&self, posture: Posture) -> Result { let schema_valid = !self.schema.is_empty() && self.schema.len() <= MAX_SCHEMA_BYTES && self @@ -213,6 +214,7 @@ impl AuditEntry { event_id: Uuid::new_v4().to_string(), time, phase: self.phase, + posture: posture.as_str(), correlation: &self.correlation, record, }; @@ -233,6 +235,7 @@ struct WireEntry<'a> { event_id: String, time: String, phase: AuditPhase, + posture: &'static str, correlation: &'a str, record: &'a Map, } @@ -656,6 +659,7 @@ impl AuditDestination { /// The audit writer. Cheap to clone; clones share one destination. #[derive(Clone)] pub struct AuditWriter { + posture: Posture, inner: Arc, open: Arc, } @@ -816,7 +820,7 @@ impl std::fmt::Debug for AuditWriter { impl AuditWriter { /// Open the destination. The file destination takes a process-lifetime /// single-writer lock beside the active file and applies retention. - pub async fn open(destination: AuditDestination) -> Result { + pub async fn open(destination: AuditDestination, posture: Posture) -> Result { let inner = match destination { AuditDestination::File(file) => { let opened = tokio::task::spawn_blocking(move || SegmentedFile::open(file)) @@ -828,11 +832,17 @@ impl AuditWriter { AuditDestination::Stderr => WriterInner::stream(Box::new(io::stderr())), }; Ok(Self { + posture, inner: Arc::new(inner), open: Arc::default(), }) } + /// Open a destination that records the production posture. + pub async fn open_without_posture(destination: AuditDestination) -> Result { + Self::open(destination, Posture::Production).await + } + /// A writer over an arbitrary line sink, with `stdout` semantics. For /// tests that need to observe emitted lines without a file. /// @@ -840,13 +850,20 @@ impl AuditWriter { /// append waits for it on the Tokio timer: the runtime that appends needs /// its time driver. #[must_use] - pub fn from_line_sink(sink: Box) -> Self { + pub fn from_line_sink(sink: Box, posture: Posture) -> Self { Self { + posture, inner: Arc::new(WriterInner::stream(sink)), open: Arc::default(), } } + /// Create a line-sink writer that records the production posture. + #[must_use] + pub fn from_line_sink_without_posture(sink: Box) -> Self { + Self::from_line_sink(sink, Posture::Production) + } + /// Append one entry. For the file destination this returns only after the /// entry's bytes are durable. Canceling the caller does not cancel an /// enqueued file write or the other entries in its group commit. @@ -891,7 +908,7 @@ impl AuditWriter { } async fn write(&self, entry: &AuditEntry) -> Result<(), AuditUnavailable> { - let line = entry.to_line()?; + let line = entry.to_line(self.posture)?; match self.inner.as_ref() { WriterInner::File(file) => { let file = Arc::clone(file); @@ -934,7 +951,8 @@ impl AuditWriter { // The unfinished response must be writable before the request is: // a request accepted with a response it could never write would stay // unpaired. - AuditEntry::response(schema.clone(), correlation.clone(), unfinished.clone()).to_line()?; + AuditEntry::response(schema.clone(), correlation.clone(), unfinished.clone()) + .to_line(self.posture)?; // The request is written and its handle registered in one task that // outlives a canceled caller. A caller that stops waiting drops the // finished handle with the task's output, which writes the @@ -989,7 +1007,7 @@ impl AuditWriter { /// Write `entry` without waiting for the destination to accept it. fn append_detached(&self, entry: &AuditEntry) { - let line = match entry.to_line() { + let line = match entry.to_line(self.posture) { Ok(line) => line, Err(_) => { tracing::error!("an unfinished response entry is malformed and was not written"); @@ -2260,7 +2278,48 @@ pub struct SealedSegment { pub path: PathBuf, } +/// A decoded journal line. Historical lines can omit posture. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StoredAuditEntry { + /// The product's audit record schema. + pub schema: String, + /// The writer-generated identifier for this entry. + pub event_id: String, + /// The writer-generated timestamp. + pub time: String, + /// Whether the entry records a request or response. + pub phase: AuditPhase, + /// The writer's declared posture, if the line records it. + #[serde(default, deserialize_with = "deserialize_posture")] + pub posture: Option, + /// The product's request and response correlation. + pub correlation: String, + /// The product-owned record. + pub record: Value, +} + +fn deserialize_posture<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let value = String::deserialize(deserializer)?; + Posture::parse(&value) + .map(Some) + .ok_or_else(|| serde::de::Error::custom("invalid audit posture")) +} + impl AuditSegments { + /// Decode a journal line from the active file or a sealed segment. + /// A present posture must be a recognized declaration. + pub fn parse_line(line: &[u8]) -> Result { + serde_json::from_slice(line).map_err(|_| { + AuditError::Io(io::Error::new( + ErrorKind::InvalidData, + "audit record is invalid", + )) + }) + } + /// The namespace of the active file at `path`. pub fn new(path: impl Into) -> Self { Self { path: path.into() } @@ -2634,10 +2693,9 @@ static TORN_RECOVERIES: StdMutex> = StdMutex::new(V /// Refuse an active file whose first entry was not produced by this writer, /// such as a leftover journal from the pre-simplification hash-chained /// writer. Every entry this writer appends carries `eventId`, `schema`, -/// `time`, `phase`, and `correlation`; an old-format entry carries none of -/// them. Only the first line is read, bounded to the largest entry this -/// writer accepts, since a file this writer manages never mixes formats. A -/// torn final line is not part of the first entry the check reads. +/// `time`, `phase`, and `correlation`. Historical entries can omit posture. +/// Only the first line is read, bounded to the largest entry this writer +/// accepts. A torn final line is outside the check. fn require_current_entry_format(active: &File, torn: Option<&TornTail>) -> Result<(), AuditError> { let length = match torn { Some(torn) => torn.complete, @@ -2653,20 +2711,25 @@ fn require_current_entry_format(active: &File, torn: Option<&TornTail>) -> Resul .read_exact_at(&mut buffer, 0) .map_err(AuditError::Io)?; let first_line = buffer.split(|&byte| byte == b'\n').next().unwrap_or(&[]); - let is_current_format = serde_json::from_slice::(first_line) - .ok() - .and_then(|value| value.as_object().cloned()) - .is_some_and(|entry| { - entry.get("eventId").is_some_and(Value::is_string) - && entry.get("schema").is_some_and(Value::is_string) - && entry.get("time").is_some_and(Value::is_string) - && entry.get("correlation").is_some_and(Value::is_string) - && matches!( - entry.get("phase").and_then(Value::as_str), - Some("request" | "response") - ) - }); - if !is_current_format { + #[derive(Deserialize)] + struct CurrentEntryFormat { + #[serde(rename = "schema")] + _schema: String, + #[serde(rename = "eventId")] + _event_id: String, + #[serde(rename = "time")] + _time: String, + #[serde(rename = "phase")] + _phase: AuditPhase, + #[serde(rename = "correlation")] + _correlation: String, + #[serde(rename = "posture", default, deserialize_with = "deserialize_posture")] + _posture: Option, + } + + if !first_line.trim_ascii_start().starts_with(b"{") + || serde_json::from_slice::(first_line).is_err() + { return Err(AuditError::Io(io::Error::new( ErrorKind::InvalidData, "audit file's first entry is not in the format this writer produces; archive it and restart with a fresh path", @@ -2971,6 +3034,7 @@ mod tests { .expect("open"); file.sync_hook = Some(hook); AuditWriter { + posture: Posture::Production, inner: Arc::new(WriterInner::File(Arc::new(GroupCommitFile::new(file)))), open: Arc::default(), } @@ -2985,7 +3049,9 @@ mod tests { } fn current_format_line(correlation: &str) -> String { - request(correlation).to_line().expect("line") + request(correlation) + .to_line(Posture::Production) + .expect("line") } /// Every name shaped like a sealed segment of `path`, oldest first. @@ -3037,12 +3103,116 @@ mod tests { } } + #[tokio::test] + async fn explicit_writers_record_their_posture() { + let directory = directory(); + let destination = file_destination(&directory); + let path = destination.path().to_owned(); + let writer = AuditWriter::open(AuditDestination::File(destination), Posture::Development) + .await + .expect("open"); + writer.append(request("explicit")).await.expect("write"); + assert_eq!(lines(&path)[0]["posture"], "development"); + + let buffer = SharedBuffer::default(); + let writer = AuditWriter::from_line_sink(Box::new(buffer.clone()), Posture::Production); + writer.append(request("explicit")).await.expect("write"); + let bytes = buffer.0.lock().expect("buffer"); + let entry: Value = serde_json::from_slice(&bytes).expect("json line"); + assert_eq!(entry["posture"], "production"); + } + + #[test] + fn startup_refuses_a_malformed_posture_in_the_first_line() { + let directory = directory(); + let destination = file_destination(&directory); + let path = destination.path(); + fs::DirBuilder::new() + .mode(0o700) + .create(path.parent().expect("parent")) + .expect("audit directory"); + let line = current_format_line("request"); + let duplicate = line.replace( + r#""posture":"production""#, + r#""posture":"staging","posture":"production""#, + ); + let invalid = line.replace(r#""posture":"production""#, r#""posture":"staging""#); + fs::write(path, &invalid).expect("write malformed line"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("mode"); + for content in [invalid, duplicate] { + fs::write(path, content).expect("write malformed line"); + let error = destination.check_writable().expect_err("malformed posture"); + assert!( + matches!(error, AuditError::Io(error) if error.kind() == ErrorKind::InvalidData) + ); + } + + let legacy = line.replace(r#""posture":"production","#, ""); + fs::write(path, legacy).expect("write historical line"); + destination + .check_writable() + .expect("historical line accepted"); + } + + #[test] + fn segment_lines_accept_declared_and_missing_posture() { + let directory = directory(); + let active = directory.path().join("audit.jsonl"); + let segments = AuditSegments::new(&active); + let mut entry = json!({ + "schema": "registry.test.audit/v2", + "eventId": "event", + "time": "2024-01-01T00:00:00Z", + "phase": "request", + "correlation": "request", + "record": {} + }); + let legacy = entry.to_string(); + entry["posture"] = json!("development"); + fs::write( + active.with_extension("jsonl.00000001"), + format!("{entry}\n{legacy}\n"), + ) + .expect("write segment"); + + let sealed = segments.sealed(1).expect("list segment"); + let contents = fs::read_to_string(&sealed[0].path).expect("read segment"); + let postures: Vec<_> = contents + .lines() + .map(|line| { + AuditSegments::parse_line(line.as_bytes()) + .expect("parse line") + .posture + }) + .collect(); + assert_eq!(postures, [Some(Posture::Development), None]); + + for invalid in [json!("staging"), Value::Null, json!(1)] { + entry["posture"] = invalid; + let error = + AuditSegments::parse_line(entry.to_string().as_bytes()).expect_err("malformed"); + assert!( + matches!(error, AuditError::Io(error) if error.kind() == ErrorKind::InvalidData) + ); + } + } + + #[tokio::test] + async fn transitional_sink_writes_production_posture() { + let buffer = SharedBuffer::default(); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); + writer.append(request("transitional")).await.expect("write"); + let bytes = buffer.0.lock().expect("buffer"); + let entry: Value = serde_json::from_slice(&bytes).expect("json line"); + assert_eq!(entry["posture"], "production"); + } + #[tokio::test] async fn file_entries_carry_only_the_envelope_fields() { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("request"); @@ -3067,6 +3237,7 @@ mod tests { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" @@ -3100,7 +3271,7 @@ mod tests { /// later entry an interrupted write left, and return the accepted bytes. async fn seed_torn_tail(destination: &FileDestination, torn: &[u8]) -> Vec { let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("accepted")).await.expect("append"); @@ -3124,7 +3295,7 @@ mod tests { let torn = b"{\"schema\":\"registry.test.audit/v2\",\"corr"; let accepted = seed_torn_tail(&destination, torn).await; - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("a torn final line is recovered at open"); let side = AuditSegments::new(&path).torn_line(); @@ -3161,7 +3332,7 @@ mod tests { fs::write(&path, torn).expect("torn file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("a torn first line is recovered at open"); assert_eq!( @@ -3176,14 +3347,14 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("before")).await.expect("append"); drop(writer); let before = fs::read(&path).expect("read before restart"); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen complete stream"); assert_eq!(fs::read(&path).expect("read after restart"), before); @@ -3205,7 +3376,7 @@ mod tests { destination .check_writable() .expect_err("check refuses a side file holding other bytes"); - let error = AuditWriter::open(AuditDestination::File(destination)) + let error = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses a side file holding other bytes"); assert!( @@ -3238,7 +3409,7 @@ mod tests { destination .check_writable() .expect("check accepts the copy"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open finishes the recovery"); assert_eq!(fs::read(&side).expect("side file"), torn); @@ -3256,7 +3427,7 @@ mod tests { destination .check_writable() .expect_err("check refuses a tail no write of this writer left"); - let error = AuditWriter::open(AuditDestination::File(destination)) + let error = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses a tail no write of this writer left"); assert_eq!( @@ -3273,13 +3444,13 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer.append(request("before")).await.expect("append"); drop(writer); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen complete stream"); writer @@ -3368,7 +3539,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let WriterInner::File(file) = writer.inner.as_ref() else { @@ -3502,7 +3673,7 @@ mod tests { .build() .expect("runtime") .block_on(async { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3594,7 +3765,7 @@ mod tests { let destination = FileDestination::new(unlistable.join("audit").join("audit.jsonl")).expect("absolute"); let refused = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = AuditWriter::open_without_posture(AuditDestination::File(destination)).await; fs::set_permissions(&unlistable, fs::Permissions::from_mode(0o700)).expect("restore"); opened.expect_err("the writer cannot sync the ancestor"); refused.expect_err("ancestor cannot be listed"); @@ -3632,7 +3803,7 @@ mod tests { .build() .expect("runtime") .block_on(async { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3678,7 +3849,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -3699,10 +3870,10 @@ mod tests { async fn a_second_writer_on_the_same_path_is_refused() { let directory = directory(); let destination = file_destination(&directory); - let _first = AuditWriter::open(AuditDestination::File(destination.clone())) + let _first = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("first"); - let second = AuditWriter::open(AuditDestination::File(destination)) + let second = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("second writer"); // `role` is `None` for the service's own destination: whoever holds @@ -3719,10 +3890,10 @@ mod tests { let destination = AuditDestination::File(file_destination(&directory)) .for_process("caseworkctl") .expect("companion destination"); - let _first = AuditWriter::open(destination.clone()) + let _first = AuditWriter::open_without_posture(destination.clone()) .await .expect("first companion writer"); - let second = AuditWriter::open(destination) + let second = AuditWriter::open_without_posture(destination) .await .expect_err("second companion writer"); // The lock is on the companion sibling file, so only another @@ -3739,9 +3910,10 @@ mod tests { #[tokio::test] async fn invalid_entries_are_refused_without_stopping_the_writer() { let directory = directory(); - let writer = AuditWriter::open(AuditDestination::File(file_destination(&directory))) - .await - .expect("open"); + let writer = + AuditWriter::open_without_posture(AuditDestination::File(file_destination(&directory))) + .await + .expect("open"); for entry in [ AuditEntry::request("", "req", json!({})), AuditEntry::request("schema/v2", "", json!({})), @@ -3769,7 +3941,7 @@ mod tests { .with_rotate_bytes(MIN_AUDIT_ROTATE_BYTES) .expect("rotation"); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let padding = "x".repeat(4096); @@ -3861,7 +4033,7 @@ mod tests { .expect("age file"); } - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); assert!(!expired.exists(), "expired sealed segment kept"); @@ -3909,7 +4081,7 @@ mod tests { }) .expect("age active file"); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer @@ -3945,7 +4117,7 @@ mod tests { fs::write(&existing, "{}\n").expect("seed"); fs::set_permissions(&existing, fs::Permissions::from_mode(0o600)).expect("mode"); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let padding = "x".repeat(4096); @@ -3970,7 +4142,7 @@ mod tests { #[tokio::test] async fn stream_destination_emits_one_json_line_per_entry() { let buffer = SharedBuffer::default(); - let writer = AuditWriter::from_line_sink(Box::new(buffer.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())); assert_eq!(writer.kind(), AuditDestinationKind::Stdout); writer.append(request("req-1")).await.expect("request"); writer @@ -3996,7 +4168,7 @@ mod tests { #[tokio::test] async fn a_failing_stream_refuses_the_append_and_every_later_one() { - let writer = AuditWriter::from_line_sink(Box::new(FailingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)); let first = writer.append(request("req-1")).await.expect_err("refused"); assert_eq!(first.reason(), AuditUnavailableReason::WriteFailed); let second = writer.append(request("req-2")).await.expect_err("refused"); @@ -4032,7 +4204,7 @@ mod tests { let (entered, first_write) = std::sync::mpsc::channel(); let (release, failure_gate) = std::sync::mpsc::channel(); let writes = Arc::new(AtomicU64::new(0)); - let writer = AuditWriter::from_line_sink(Box::new(FailOnce { + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailOnce { entered, release: failure_gate, writes: writes.clone(), @@ -4115,7 +4287,7 @@ mod tests { .build() .expect("current-thread runtime"); runtime.block_on(async move { - let writer = AuditWriter::from_line_sink(Box::new(BlockingSink { + let writer = AuditWriter::from_line_sink_without_posture(Box::new(BlockingSink { entered, release: write_released, })); @@ -4190,7 +4362,7 @@ mod tests { unreachable!() }; let path = file.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File( + let writer = AuditWriter::open_without_posture(AuditDestination::File( file.with_rotate_bytes(MIN_AUDIT_ROTATE_BYTES) .expect("rotation"), )) @@ -4353,7 +4525,9 @@ mod tests { companion.for_process("schedulingctl"), Ok(AuditDestination::Stderr) ); - let companion_writer = AuditWriter::open(companion).await.expect("stderr"); + let companion_writer = AuditWriter::open_without_posture(companion) + .await + .expect("stderr"); assert_eq!(companion_writer.kind(), AuditDestinationKind::Stdout); for role in ["", "-x", "Bregctl", "a/b", "a.b", &"x".repeat(33)] { assert_eq!( @@ -4363,10 +4537,13 @@ mod tests { ); } - let _service_writer = AuditWriter::open(service.clone()).await.expect("service"); - let tool_writer = AuditWriter::open(service.for_process("bregctl").expect("role")) + let _service_writer = AuditWriter::open_without_posture(service.clone()) .await - .expect("a companion process opens its own file beside a running service"); + .expect("service"); + let tool_writer = + AuditWriter::open_without_posture(service.for_process("bregctl").expect("role")) + .await + .expect("a companion process opens its own file beside a running service"); tool_writer .append(AuditEntry::response( "test/v1", @@ -4459,7 +4636,7 @@ mod tests { // Opening applies retention, which lists the directory. fs::set_permissions(&parent, fs::Permissions::from_mode(0o300)).expect("mode"); let refused = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = AuditWriter::open_without_posture(AuditDestination::File(destination)).await; fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).expect("restore"); opened.expect_err("the writer cannot list the directory"); refused.expect_err("unlistable audit directory"); @@ -4528,7 +4705,7 @@ mod tests { let content = "{\"envelope_id\":\"01J000000000000000000000\"}\n{\"envelope_id\""; fs::write(&path, content).expect("old-format file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("leftover journal with a torn tail"); assert_eq!(fs::read_to_string(&path).expect("active file"), content); @@ -4644,7 +4821,8 @@ mod tests { let destination = FileDestination::new(shared.join("audit").join("audit.jsonl")).expect("absolute"); let checked = destination.check_writable(); - let opened = AuditWriter::open(AuditDestination::File(destination)).await; + let opened = + AuditWriter::open_without_posture(AuditDestination::File(destination)).await; if accepted { checked.expect("sticky or group-writable ancestor"); opened.expect("sticky or group-writable ancestor"); @@ -4696,14 +4874,14 @@ mod tests { .and_then(|handle| handle.set_modified(old)) .expect("age file"); } - let first = AuditWriter::open(AuditDestination::File(destination.clone())) + let first = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); assert!(sealed_segments(&path).expect("sealed").is_empty()); drop(first); // A second restart finds no sealed segment at all. - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); let padding = "x".repeat(4096); @@ -4741,7 +4919,7 @@ mod tests { destination .check_writable() .expect_err("check refuses the sequence file"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("open refuses the sequence file"); } @@ -4782,7 +4960,7 @@ mod tests { let third = seed_segment(&path, 3, 3); let fourth = seed_segment(&path, 4, 0); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); @@ -4814,7 +4992,7 @@ mod tests { fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); refuse_retention(&path); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("a retention failure does not refuse open"); assert!(expired.exists()); @@ -4835,7 +5013,7 @@ mod tests { drop(writer); allow_retention(&path); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); assert!( @@ -4877,7 +5055,7 @@ mod tests { .create(path.parent().expect("parent")) .expect("audit directory"); seed_nearly_full_active(&path); - let writer = AuditWriter::open(AuditDestination::File(destination.clone())) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("open"); writer @@ -4889,7 +5067,7 @@ mod tests { fs::remove_file(segment_path(&path, 1)).expect("ship the sealed segment"); seed_nearly_full_active(&path); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); writer @@ -4920,7 +5098,7 @@ mod tests { .expect("audit directory"); seed_nearly_full_active(&path); ship_on_seal(&path); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); @@ -4943,13 +5121,13 @@ mod tests { let path = destination.path().to_path_buf(); let parent = path.parent().expect("parent").to_path_buf(); drop( - AuditWriter::open(AuditDestination::File(destination.clone())) + AuditWriter::open_without_posture(AuditDestination::File(destination.clone())) .await .expect("first open creates the lock and active file"), ); forget_directory_syncs(&parent); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("reopen"); // A crash after creating the names but before the directory sync @@ -4962,7 +5140,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -4982,7 +5160,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -5004,7 +5182,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); writer.append(request("req-1")).await.expect("append"); @@ -5051,7 +5229,7 @@ mod tests { }) .expect("age other stream"); - let _writer = AuditWriter::open(AuditDestination::File(destination)) + let _writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); assert!(other.exists(), "another stream's active file deleted"); @@ -5277,7 +5455,7 @@ mod tests { let target = directory.path().join("elsewhere.jsonl"); fs::write(&target, "").expect("target"); std::os::unix::fs::symlink(&target, &path).expect("symlink"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("symlinked active file"); } @@ -5296,7 +5474,7 @@ mod tests { // Every append reopens the lock for read to check it is still pinned, // so a write-only lock would stop the writer on its first entry. fs::set_permissions(&lock, fs::Permissions::from_mode(0o200)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("write-only lock"); } @@ -5320,7 +5498,7 @@ mod tests { ) .expect("old-format file"); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("mode"); - AuditWriter::open(AuditDestination::File(destination)) + AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect_err("leftover hash-chained journal"); } @@ -5334,7 +5512,7 @@ mod tests { fn buffered() -> (AuditWriter, SharedBuffer) { let buffer = SharedBuffer::default(); ( - AuditWriter::from_line_sink(Box::new(buffer.clone())), + AuditWriter::from_line_sink_without_posture(Box::new(buffer.clone())), buffer, ) } @@ -5549,7 +5727,7 @@ mod tests { let directory = directory(); let destination = file_destination(&directory); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let (started, begun) = tokio::sync::oneshot::channel(); @@ -5616,7 +5794,7 @@ mod tests { .build() .expect("runtime"); let result: Result<(), &str> = runtime.block_on(async move { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let _request = writer @@ -5645,7 +5823,7 @@ mod tests { .build() .expect("runtime"); let (writer, request) = runtime.block_on(async move { - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("open"); let request = writer @@ -5681,7 +5859,7 @@ mod tests { #[tokio::test] async fn a_stopped_writer_refuses_the_request_and_writes_nothing() { - let writer = AuditWriter::from_line_sink(Box::new(FailingSink)); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(FailingSink)); assert!(writer .begin( SCHEMA, @@ -5762,7 +5940,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_request_canceled_while_its_entry_is_written_is_still_paired() { let sink = GatedSink::new(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let begun = tokio::spawn({ let writer = writer.clone(); async move { @@ -5787,7 +5965,7 @@ mod tests { async fn a_response_accepted_after_its_caller_left_is_the_only_answer() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5817,7 +5995,7 @@ mod tests { async fn a_response_appended_after_its_caller_left_still_answers_the_request() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5860,7 +6038,7 @@ mod tests { async fn a_request_dropped_while_an_appended_response_is_written_is_answered_once() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -5902,7 +6080,7 @@ mod tests { async fn an_appended_response_skips_a_request_whose_own_response_is_in_flight() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let first = writer .begin(SCHEMA, "shared", json!({"n": 1}), unfinished()) .await @@ -5982,7 +6160,7 @@ mod tests { fn dropping_a_request_never_waits_on_a_stalled_stream() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -6008,7 +6186,7 @@ mod tests { async fn a_response_claimed_while_its_request_is_dropped_is_the_only_answer() { let sink = GatedSink::new(); sink.release(); - let writer = AuditWriter::from_line_sink(Box::new(sink.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(sink.clone())); let request = writer .begin( SCHEMA, @@ -6135,6 +6313,7 @@ mod tests { queue_lines: usize, ) -> AuditWriter { AuditWriter { + posture: Posture::Production, inner: Arc::new(WriterInner::Stream(LineStream::with_limits( Box::new(sink), deadline, diff --git a/crates/registry-platform-authcommon/Cargo.toml b/crates/registry-platform-authcommon/Cargo.toml index 77de1d9064..566fd55bc4 100644 --- a/crates/registry-platform-authcommon/Cargo.toml +++ b/crates/registry-platform-authcommon/Cargo.toml @@ -10,18 +10,29 @@ publish = false [lints] workspace = true +[features] +# The refusal recorder: the counter, the bounded log line and `record_refusal!`. +# Off by default so client crates that reach this crate through +# `registry-platform-httputil` do not gain the metrics crate. +# This crate never depends on `registry-platform-httpsec`: httpsec implements +# `RefusalTraceId` for its `TraceId`, so the dependency runs the other way. +refusal-recorder = ["dep:registry-platform-metrics", "dep:tracing"] + [dependencies] base64.workspace = true futures.workspace = true registry-platform-crypto.workspace = true +registry-platform-metrics = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true sha2.workspace = true subtle.workspace = true thiserror.workspace = true +tracing = { workspace = true, optional = true } ulid.workspace = true zeroize.workspace = true [dev-dependencies] proptest.workspace = true tempfile.workspace = true +tracing-subscriber.workspace = true diff --git a/crates/registry-platform-authcommon/README.md b/crates/registry-platform-authcommon/README.md index 988a717d77..7025ea40be 100644 --- a/crates/registry-platform-authcommon/README.md +++ b/crates/registry-platform-authcommon/README.md @@ -10,6 +10,17 @@ Provider-independent authentication helpers shared by registry services. - Canonical API-key fingerprints in `sha256:<64 lowercase hex>` format. - Constant-time API-key fingerprint comparison through `subtle`. - A 32-byte minimum raw API-key entropy floor for generated keys. +- `FailedCheck`, the closed set of checks a request can fail, each with a + stable kebab-case label (`as_str`). It is operator-side only and is never + written to a response. +- `RefusalTraceId`, the trace id a refusal line may carry. It is sealed by + convention, and `registry_platform_httpsec::TraceId` implements it under + httpsec's `server` feature. This crate does not depend on httpsec. +- Behind the `refusal-recorder` feature: `RefusalRecorder`, which counts + every refusal in `_request_refusals_total{check}` and admits at + most five log lines per check per minute, and `record_refusal!`, which + writes the admitted line with `failed_check`, `suppressed`, an optional + code-defined `remedy` and an optional `trace_id` (a `RefusalTraceId`). ## Typical Use @@ -43,11 +54,18 @@ Ok(()) generation still belongs to a cryptographically secure generator. - Store and compare fingerprints, not plaintext API keys. - Treat returned Bearer tokens as secrets and avoid logging them. +- Alert and diagnose on the refusal counter, not on the log line. The log + budget is process-wide, so unauthenticated traffic can spend a check's + lines; `suppressed` on the next admitted line shows how many were dropped. +- Call `record_refusal!` outside any span that records request values (a + URI, query, header, client id or subject). Formatters print the enclosing + span's fields on the refusal line. ## Testing ```sh cargo test -p registry-platform-authcommon +cargo test -p registry-platform-authcommon --features refusal-recorder ``` ## License diff --git a/crates/registry-platform-authcommon/src/lib.rs b/crates/registry-platform-authcommon/src/lib.rs index 825f367bad..ec05f4df45 100644 --- a/crates/registry-platform-authcommon/src/lib.rs +++ b/crates/registry-platform-authcommon/src/lib.rs @@ -2,6 +2,18 @@ //! provider. pub mod client_assertion; +pub mod refusal; + +#[doc(hidden)] +pub use refusal::__refusal_trace_id_seal; +#[cfg(feature = "refusal-recorder")] +pub use refusal::{ + DeclaredScope, RefusalLine, RefusalNote, RefusalRecorder, DECLARED_VALUE_MAX_BYTES, + REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, +}; +pub use refusal::{FailedCheck, RefusalTraceId}; +#[cfg(feature = "refusal-recorder")] +pub use tracing as __tracing; use std::env; use std::fs; diff --git a/crates/registry-platform-authcommon/src/refusal.rs b/crates/registry-platform-authcommon/src/refusal.rs new file mode 100644 index 0000000000..2320909947 --- /dev/null +++ b/crates/registry-platform-authcommon/src/refusal.rs @@ -0,0 +1,874 @@ +//! The closed set of checks a request can fail, and the recorder that counts +//! and logs a refusal by its check. +//! +//! The check is operator-side only. It is never written to a response body. + +/// Declares [`FailedCheck`], [`FailedCheck::ALL`] and [`FailedCheck::as_str`] +/// from one list, so a member cannot exist without its label and its place in +/// `ALL`. +macro_rules! failed_checks { + ($($(#[$doc:meta])* $member:ident => $label:literal,)+) => { + /// The check a request failed. Closed. Operator-side only: never written to a + /// response. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum FailedCheck { + $($(#[$doc])* $member,)+ + } + + impl FailedCheck { + /// Every member, in declaration order. + pub const ALL: [Self; [$($label),+].len()] = [$(Self::$member),+]; + + /// The number of members. + pub const COUNT: usize = Self::ALL.len(); + + /// Stable kebab-case label for the counter and the log line. + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$member => $label,)+ + } + } + } + }; +} + +failed_checks! { + /// No credential, or not the scheme the route takes. + CredentialMissing => "credential-missing", + /// Credential header repeated or unreadable, or the credential is not in the expected shape. + CredentialMalformed => "credential-malformed", + /// Signing algorithm not allowed. + TokenAlgorithm => "token-algorithm", + /// Token type not allowed. + TokenType => "token-type", + /// Key id missing, too long or unknown. + TokenKey => "token-key", + /// Signature does not verify. + TokenSignature => "token-signature", + /// Issuer is not the configured one. + TokenIssuer => "token-issuer", + /// Audience does not include this service. + TokenAudience => "token-audience", + /// Expired, not yet valid, or time claims unusable. + TokenTime => "token-time", + /// Client not on the verifier's allow list, or the matched client is unusable. + TokenClient => "token-client", + /// An exchanged token whose assertion issuer is not allowed or not declared. + TokenAssertionIssuer => "token-assertion-issuer", + /// A required identity claim is missing or malformed (principal, subject, issuer, expiry). + TokenClaims => "token-claims", + /// Actor kind claim missing, malformed, or not the kind the route or profile takes. + ActorKind => "actor-kind", + /// A delegated actor is present where none is allowed, or is not the trusted one. + Delegation => "delegation", + /// The token is sender-constrained and the service does not accept that. + SenderConstraint => "sender-constraint", + /// The verifier could not reach or use its key source. + KeySourceUnavailable => "key-source-unavailable", + /// A static secret, API key, Basic pair or path token does not match. + SharedSecret => "shared-secret", + /// A single-use code or token is unknown, expired, already used or locked out. + OneTimeCredential => "one-time-credential", + /// A signed delivery or provider callback has a missing, malformed, unsupported or wrong signature. + DeliverySignature => "delivery-signature", + /// A signed delivery time is outside the receiver's window. + DeliveryFreshness => "delivery-freshness", + /// A signed delivery's source, type, schema, route or target is not what the receiver expects. + DeliveryBinding => "delivery-binding", + /// The request's host or origin is not accepted. + HostOrigin => "host-origin", + /// A required scope is missing. + Scope => "scope", + /// No access profile, policy or authority entry admits this caller on this surface. + AccessProfile => "access-profile", + /// The profile or resource does not admit this requester client. + RequesterClient => "requester-client", + /// The declared purpose is missing or not admitted. + Purpose => "purpose", + /// The caller's profile or policy does not allow this operation, action, workflow, template or record type. + Operation => "operation", + /// The request asks for fields or a response format beyond what the caller's profile discloses. + Disclosure => "disclosure", + /// The subject selector is not one the caller's grant or authority covers. + SubjectSelector => "subject-selector", + /// The caller pinned a configuration revision that is not the deployed one. + RevisionPin => "revision-pin", + /// The acquisition channel is not open to the resolved profile. + AcquisitionChannel => "acquisition-channel", + /// The source or target authority refused the access. + SourceAuthority => "source-authority", + /// The caller already acted in a role that excludes this one. + SeparationOfDuties => "separation-of-duties", + /// The operation needs a task grant and none was presented. + TaskGrantMissing => "task-grant-missing", + /// The task grant is partial or malformed. + TaskGrantClaims => "task-grant-claims", + /// The task grant has expired. + TaskGrantExpired => "task-grant-expired", + /// The task grant is bound to another client, audience, principal, issuer or task. + TaskGrantBinding => "task-grant-binding", + /// The task grant does not cover this service, location, action or operation. + TaskGrantScope => "task-grant-scope", + /// The task grant has more lifetime, or more lifetime left, than the receiver accepts. + TaskGrantLifetime => "task-grant-lifetime", + /// The status authority says the grant is inactive, or its source is not listed. + TaskGrantStatus => "task-grant-status", + /// The target row is outside the caller's row boundary. + RowBoundary => "row-boundary", + /// The target exists and belongs to another caller. + Ownership => "ownership", + /// The target is absent or not visible to the caller, and the product does not tell which. + Visibility => "visibility", + /// A BReg Action guard refused. Operator-side only, so an answer never tells a guard from a boundary. + ActionGuard => "action-guard", + /// An identity-keyed or route-keyed request budget is spent. + RateLimit => "rate-limit", +} + +/// A trace id that `record_refusal!` may write on a refusal line. +/// +/// `registry_platform_httpsec::TraceId` implements it when httpsec's `server` +/// feature is on. That type holds only a validated W3C trace id, 32 lowercase +/// hexadecimal digits, so no other request value (a header, client id or +/// subject) can reach the line through this field. The trait is sealed by +/// convention: its supertrait is a hidden item, and that `TraceId`, with a +/// reference to one, is its only implementation outside this crate's tests. +pub trait RefusalTraceId: core::fmt::Display + __refusal_trace_id_seal::Sealed {} + +impl __refusal_trace_id_seal::Sealed for &T {} +impl RefusalTraceId for &T {} + +/// The hidden supertrait of [`RefusalTraceId`]. Implemented only beside a +/// `RefusalTraceId` implementation. +#[doc(hidden)] +pub mod __refusal_trace_id_seal { + pub trait Sealed {} +} + +#[cfg(feature = "refusal-recorder")] +pub use recorder::{ + DeclaredScope, RefusalLine, RefusalNote, RefusalRecorder, DECLARED_VALUE_MAX_BYTES, + REFUSAL_LOG_LINES_PER_WINDOW, REFUSAL_LOG_WINDOW, +}; + +#[cfg(feature = "refusal-recorder")] +mod recorder { + use std::sync::{Arc, Mutex, PoisonError}; + use std::time::{Duration, Instant}; + + use registry_platform_metrics::{CounterVec, LabelSpace, MetricsError}; + + use super::FailedCheck; + + /// The most bytes one declared value contributes to a refusal line. + pub const DECLARED_VALUE_MAX_BYTES: usize = 128; + + /// Values the operator declared that a scope refusal line may name: the + /// name of the claim that carries scopes, the scope the operation needs, + /// and the access profile that was applied. + /// + /// Each value comes from the runtime configuration or the reviewed + /// package, never from the caller's token. The recording layer passes it + /// to [`record_refusal!`](crate::record_refusal) beside the note, and the + /// line carries it only when the failed check is + /// [`FailedCheck::Scope`]. A product attaches it to the refusal answer's + /// extensions, which are never written to the response. + #[derive(Clone, Debug, PartialEq, Eq)] + pub struct DeclaredScope { + scope_claim: Arc, + required_scope: Option>, + access_profile: Option>, + } + + impl DeclaredScope { + /// `scope_claim` is the claim name the deployment configured, for + /// example `authentication.oidc.scopeClaim`. + pub fn new(scope_claim: impl AsRef) -> Self { + Self { + scope_claim: bounded(scope_claim.as_ref()), + required_scope: None, + access_profile: None, + } + } + + /// The scope the operation needs, as the configuration or package + /// declares it. + #[must_use] + pub fn with_required_scope(self, scope: impl AsRef) -> Self { + Self { + required_scope: Some(bounded(scope.as_ref())), + ..self + } + } + + /// The identifier of the access profile the configuration applied. + #[must_use] + pub fn with_access_profile(self, profile: impl AsRef) -> Self { + Self { + access_profile: Some(bounded(profile.as_ref())), + ..self + } + } + + pub fn scope_claim(&self) -> &str { + &self.scope_claim + } + + pub fn required_scope(&self) -> Option<&str> { + self.required_scope.as_deref() + } + + pub fn access_profile(&self) -> Option<&str> { + self.access_profile.as_deref() + } + } + + /// Cut a value to [`DECLARED_VALUE_MAX_BYTES`] on a character boundary. + /// The log formatter escapes what remains, so a value stays on one line. + fn bounded(value: &str) -> Arc { + let mut end = value.len().min(DECLARED_VALUE_MAX_BYTES); + while !value.is_char_boundary(end) { + end -= 1; + } + Arc::from(&value[..end]) + } + + /// The length of one log window for one check. + pub const REFUSAL_LOG_WINDOW: Duration = Duration::from_secs(60); + /// The most lines one check may write in one window. + pub const REFUSAL_LOG_LINES_PER_WINDOW: u32 = 5; + + /// What the refusal answer carries to the recording layer, in the response + /// extensions. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct RefusalNote { + pub check: FailedCheck, + pub remedy: Option<&'static str>, + } + + impl RefusalNote { + pub const fn new(check: FailedCheck) -> Self { + Self { + check, + remedy: None, + } + } + + /// Attach a fixed operator hint. It is code-defined text, never a + /// caller value. + #[must_use] + pub const fn with_remedy(self, remedy: &'static str) -> Self { + Self { + remedy: Some(remedy), + ..self + } + } + } + + /// One admitted log line. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct RefusalLine { + pub failed_check: &'static str, + /// Refusals of this check counted but not logged since the last line. + pub suppressed: u64, + } + + #[derive(Clone, Copy, Default)] + pub(super) struct Slot { + window_start: Option, + written: u32, + suppressed: u64, + } + + /// Counts refusals by check and admits a bounded number of log lines. + /// + /// State is one counter family and a fixed array of slots, one per + /// [`FailedCheck`]. Nothing is keyed by a value a caller sends. + /// + /// The counter, not the log line, is the alert and diagnosis signal. Every + /// refusal is counted. The log admits at most + /// [`REFUSAL_LOG_LINES_PER_WINDOW`] lines per check per + /// [`REFUSAL_LOG_WINDOW`], process-wide, so unauthenticated traffic can + /// spend a check's lines before an honest client's refusal arrives. The + /// `suppressed` field on the first line of the next window shows how many + /// refusals of that check the window counted but did not log. + pub struct RefusalRecorder { + counter: CounterVec, + pub(super) slots: Mutex<[Slot; FailedCheck::COUNT]>, + } + + impl RefusalRecorder { + /// `product` is the metric prefix, for example "breg" or + /// "evidence_oid4vci". + pub fn new(product: &'static str) -> Result { + let labels: Vec<[&str; 1]> = FailedCheck::ALL + .iter() + .map(|check| [check.as_str()]) + .collect(); + let declared: Vec<&[&str]> = labels.iter().map(<[&str; 1]>::as_slice).collect(); + Ok(Self { + counter: CounterVec::new( + format!("{product}_request_refusals_total"), + "Requests refused, by the check that failed.", + LabelSpace::closed_zero_filled(&["check"], &declared)?, + )?, + slots: Mutex::new([Slot::default(); FailedCheck::COUNT]), + }) + } + + /// Count the refusal. Returns the line to write when the limiter + /// admits one. + #[must_use] + pub fn record(&self, check: FailedCheck) -> Option { + self.record_at(check, Instant::now()) + } + + pub(super) fn record_at(&self, check: FailedCheck, now: Instant) -> Option { + let label = check.as_str(); + let counted = self.counter.inc(&[label]); + // The slot state is plain counters, so a poisoned lock is safe to reuse. + let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner); + let slot = &mut slots[check as usize]; + if counted.is_err() { + // Labels come from the closed enum, so this is a defect. It is + // reported once per window, not swallowed. + if slot + .window_start + .is_none_or(|start| now.saturating_duration_since(start) >= REFUSAL_LOG_WINDOW) + { + tracing::error!( + failed_check = label, + "a refusal was rejected by its closed label space" + ); + } + } + let expired = slot + .window_start + .is_none_or(|start| now.saturating_duration_since(start) >= REFUSAL_LOG_WINDOW); + if expired { + let suppressed = slot.suppressed; + *slot = Slot { + window_start: Some(now), + written: 1, + suppressed: 0, + }; + return Some(RefusalLine { + failed_check: label, + suppressed, + }); + } + if slot.written < REFUSAL_LOG_LINES_PER_WINDOW { + slot.written += 1; + return Some(RefusalLine { + failed_check: label, + suppressed: 0, + }); + } + slot.suppressed = slot.suppressed.saturating_add(1); + None + } + + /// For the product's exposition. + pub fn counter(&self) -> &CounterVec { + &self.counter + } + } + + /// Count a refusal and write the admitted line at the call site's own + /// tracing target. + /// + /// The line carries `decision`, `failed_check`, `suppressed`, the note's + /// code-defined `remedy` when it has one, and `trace_id` when one is + /// given. The macro takes no other value. `trace_id` must be a + /// [`RefusalTraceId`](crate::RefusalTraceId) or a reference to one, in + /// practice the request's `registry_platform_httpsec::TraceId`, as in + /// `record_refusal!(recorder, note, trace_id = &trace.trace_id)`. A raw + /// header, client id or subject does not compile: + /// + /// ```compile_fail + /// # use registry_platform_authcommon::{record_refusal, FailedCheck, RefusalNote, RefusalRecorder}; + /// let recorder = RefusalRecorder::new("doc").unwrap(); + /// let client_id = String::from("a value the caller sent"); + /// record_refusal!(recorder, RefusalNote::new(FailedCheck::Scope), trace_id = client_id); + /// ``` + /// + /// The caller's obligation: tracing formatters also print the fields of + /// every span that encloses the event. Do not call this macro inside a + /// span that records request values (a URI, query, header, client id or + /// subject), or those values reach the refusal line through the span. + /// + /// A scope refusal may also pass `declared = Some(&scope)`, a + /// [`DeclaredScope`](crate::DeclaredScope) built from configuration. The + /// line then carries `scope_claim`, and `required_scope` and + /// `access_profile` when they were declared. They are written only when + /// the note's check is [`FailedCheck::Scope`](crate::FailedCheck::Scope). + #[macro_export] + macro_rules! record_refusal { + (@write $recorder:expr, $note:expr, $trace_id:expr, $declared:expr) => {{ + let note: $crate::RefusalNote = $note; + let trace_id: ::core::option::Option<&dyn $crate::RefusalTraceId> = $trace_id; + let declared: ::core::option::Option<&$crate::DeclaredScope> = $declared; + if let Some(line) = $recorder.record(note.check) { + let trace_id = trace_id.map($crate::__tracing::field::display); + let declared = declared.filter(|_| note.check == $crate::FailedCheck::Scope); + let scope_claim = declared.map($crate::DeclaredScope::scope_claim); + let required_scope = declared.and_then($crate::DeclaredScope::required_scope); + let access_profile = declared.and_then($crate::DeclaredScope::access_profile); + match note.remedy { + Some(remedy) => $crate::__tracing::info!( + decision = "refused", + failed_check = line.failed_check, + suppressed = line.suppressed, + remedy, + scope_claim, + required_scope, + access_profile, + trace_id, + "request refused" + ), + None => $crate::__tracing::info!( + decision = "refused", + failed_check = line.failed_check, + suppressed = line.suppressed, + scope_claim, + required_scope, + access_profile, + trace_id, + "request refused" + ), + } + } + }}; + ($recorder:expr, $note:expr) => { + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::None, ::core::option::Option::None + ) + }; + ($recorder:expr, $note:expr, declared = $declared:expr) => { + $crate::record_refusal!(@write $recorder, $note, ::core::option::Option::None, $declared) + }; + ($recorder:expr, $note:expr, trace_id = $trace_id:expr) => {{ + let typed: &dyn $crate::RefusalTraceId = &$trace_id; + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::Some(typed), ::core::option::Option::None + ) + }}; + ($recorder:expr, $note:expr, trace_id = $trace_id:expr, declared = $declared:expr) => {{ + let typed: &dyn $crate::RefusalTraceId = &$trace_id; + $crate::record_refusal!( + @write $recorder, $note, ::core::option::Option::Some(typed), $declared + ) + }}; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_set_is_closed_unique_and_in_declaration_order() { + assert_eq!(FailedCheck::ALL.len(), 45); + assert_eq!(FailedCheck::COUNT, 45); + let mut seen = std::collections::HashSet::new(); + for (index, check) in FailedCheck::ALL.iter().enumerate() { + assert_eq!(*check as usize, index); + let label = check.as_str(); + assert!(seen.insert(label), "duplicate label {label}"); + assert!( + !label.is_empty() + && !label.starts_with('-') + && !label.ends_with('-') + && !label.contains("--") + && label.bytes().all(|b| b.is_ascii_lowercase() || b == b'-'), + "label {label} is not kebab-case" + ); + } + } + + #[test] + fn the_members_labels_and_order_are_the_published_ones() { + let published = [ + ("CredentialMissing", "credential-missing"), + ("CredentialMalformed", "credential-malformed"), + ("TokenAlgorithm", "token-algorithm"), + ("TokenType", "token-type"), + ("TokenKey", "token-key"), + ("TokenSignature", "token-signature"), + ("TokenIssuer", "token-issuer"), + ("TokenAudience", "token-audience"), + ("TokenTime", "token-time"), + ("TokenClient", "token-client"), + ("TokenAssertionIssuer", "token-assertion-issuer"), + ("TokenClaims", "token-claims"), + ("ActorKind", "actor-kind"), + ("Delegation", "delegation"), + ("SenderConstraint", "sender-constraint"), + ("KeySourceUnavailable", "key-source-unavailable"), + ("SharedSecret", "shared-secret"), + ("OneTimeCredential", "one-time-credential"), + ("DeliverySignature", "delivery-signature"), + ("DeliveryFreshness", "delivery-freshness"), + ("DeliveryBinding", "delivery-binding"), + ("HostOrigin", "host-origin"), + ("Scope", "scope"), + ("AccessProfile", "access-profile"), + ("RequesterClient", "requester-client"), + ("Purpose", "purpose"), + ("Operation", "operation"), + ("Disclosure", "disclosure"), + ("SubjectSelector", "subject-selector"), + ("RevisionPin", "revision-pin"), + ("AcquisitionChannel", "acquisition-channel"), + ("SourceAuthority", "source-authority"), + ("SeparationOfDuties", "separation-of-duties"), + ("TaskGrantMissing", "task-grant-missing"), + ("TaskGrantClaims", "task-grant-claims"), + ("TaskGrantExpired", "task-grant-expired"), + ("TaskGrantBinding", "task-grant-binding"), + ("TaskGrantScope", "task-grant-scope"), + ("TaskGrantLifetime", "task-grant-lifetime"), + ("TaskGrantStatus", "task-grant-status"), + ("RowBoundary", "row-boundary"), + ("Ownership", "ownership"), + ("Visibility", "visibility"), + ("ActionGuard", "action-guard"), + ("RateLimit", "rate-limit"), + ]; + let actual: Vec<(String, &str)> = FailedCheck::ALL + .iter() + .map(|check| (format!("{check:?}"), check.as_str())) + .collect(); + let expected: Vec<(String, &str)> = published + .iter() + .map(|(member, label)| ((*member).to_string(), *label)) + .collect(); + assert_eq!(actual, expected); + } +} + +#[cfg(all(test, feature = "refusal-recorder"))] +mod recorder_tests { + use super::*; + use std::sync::{Arc, Mutex}; + use std::time::{Duration, Instant}; + + use crate::record_refusal; + use registry_platform_metrics::Exposition; + + /// A stand-in for `registry_platform_httpsec::TraceId`, which this crate + /// does not depend on. httpsec's own tests pass its `TraceId` to the macro. + struct ServerTraceId(&'static str); + + impl std::fmt::Display for ServerTraceId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.0) + } + } + + impl crate::__refusal_trace_id_seal::Sealed for ServerTraceId {} + impl crate::RefusalTraceId for ServerTraceId {} + + #[test] + fn a_new_recorder_exposes_every_check_at_zero() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let mut out = Exposition::new(); + recorder.counter().write(&mut out).unwrap(); + let text = out.finish(); + assert!(text.contains("# TYPE breg_request_refusals_total counter")); + for check in FailedCheck::ALL { + let line = format!( + "breg_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + ); + assert!(text.contains(&line), "missing {line}"); + } + assert_eq!( + text.lines().filter(|l| l.starts_with("breg_")).count(), + FailedCheck::COUNT + ); + } + + #[test] + fn record_counts_the_right_series() { + let recorder = RefusalRecorder::new("scheduling").unwrap(); + let _ = recorder.record(FailedCheck::Scope); + let _ = recorder.record(FailedCheck::Scope); + let _ = recorder.record(FailedCheck::TokenSignature); + assert_eq!(recorder.counter().get(&["scope"]), Some(2)); + assert_eq!(recorder.counter().get(&["token-signature"]), Some(1)); + assert_eq!(recorder.counter().get(&["purpose"]), Some(0)); + assert_eq!(recorder.counter().refused(), 0); + } + + #[test] + fn a_flood_writes_five_lines_then_reports_the_rest() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let start = Instant::now(); + let mut lines = Vec::new(); + for _ in 0..10_000 { + if let Some(line) = recorder.record_at(FailedCheck::TokenSignature, start) { + lines.push(line); + } + } + assert_eq!(lines.len(), 5); + assert!(lines.iter().all(|l| l.suppressed == 0)); + assert_eq!(lines[0].failed_check, "token-signature"); + assert_eq!(recorder.counter().get(&["token-signature"]), Some(10_000)); + let next = recorder + .record_at(FailedCheck::TokenSignature, start + REFUSAL_LOG_WINDOW) + .expect("the next window admits a line"); + assert_eq!(next.suppressed, 9_995); + let after = recorder + .record_at(FailedCheck::TokenSignature, start + REFUSAL_LOG_WINDOW) + .expect("the new window admits more lines"); + assert_eq!(after.suppressed, 0); + } + + #[test] + fn members_do_not_share_a_budget() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let now = Instant::now(); + for _ in 0..1_000 { + let _ = recorder.record_at(FailedCheck::TokenSignature, now); + } + for _ in 0..5 { + assert!(recorder.record_at(FailedCheck::Scope, now).is_some()); + } + assert!(recorder.record_at(FailedCheck::Scope, now).is_none()); + } + + #[test] + fn a_poisoned_lock_still_counts_and_logs() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _guard = recorder.slots.lock().unwrap(); + panic!("poison the lock"); + })); + assert!(poisoned.is_err()); + assert!(recorder.record(FailedCheck::Scope).is_some()); + assert_eq!(recorder.counter().get(&["scope"]), Some(1)); + } + + #[derive(Clone, Default)] + struct Capture(Arc>>); + + impl std::io::Write for Capture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture { + type Writer = Capture; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + + fn captured(run: impl FnOnce()) -> String { + let capture = Capture::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(capture.clone()) + .with_ansi(false) + .finish(); + tracing::subscriber::with_default(subscriber, run); + let bytes = capture.0.lock().unwrap().clone(); + String::from_utf8(bytes).unwrap() + } + + #[test] + fn every_member_is_counted_and_logged_under_its_own_label() { + let recorder = RefusalRecorder::new("breg").unwrap(); + for check in FailedCheck::ALL { + let label = check.as_str(); + let output = captured(|| { + record_refusal!(recorder, RefusalNote::new(check)); + }); + assert_eq!(output.lines().count(), 1, "{label}: {output}"); + assert!( + output.contains(&format!("failed_check=\"{label}\"")), + "{label}: {output}" + ); + assert!(!output.contains("ERROR"), "{label}: {output}"); + assert_eq!(recorder.counter().get(&[label]), Some(1), "{label}"); + } + assert_eq!(recorder.counter().refused(), 0); + } + + #[test] + fn a_caller_value_reaches_the_line_only_through_an_enclosing_span() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let canary = "canary-request-value-7f3a"; + + // Outside a request span the line holds the fixed fields only. + let output = captured(|| { + record_refusal!(recorder, RefusalNote::new(FailedCheck::TokenAudience)); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("request refused")); + assert!(output.contains("decision=\"refused\"")); + assert!(output.contains("failed_check=\"token-audience\"")); + assert!(output.contains("suppressed=0")); + assert!(!output.contains("remedy")); + assert!(!output.contains("trace_id")); + assert!(!output.contains("canary"), "{output}"); + + // The trace id is the only value the macro takes from a request. It + // must be a `RefusalTraceId`, so a `&str` or `String` does not compile + // (see the macro's `compile_fail` example). httpsec's tests show that + // caller text cannot become its `TraceId`. + let from_traceparent = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::TokenAudience), + trace_id = from_traceparent + ); + }); + assert!(output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736")); + assert!(!output.contains("canary"), "{output}"); + + // The documented rule: a span that records a request value prints it + // on every event inside it, the refusal line included. The macro + // cannot prevent this, so call sites must not record refusals there. + let output = captured(|| { + let span = tracing::info_span!("request", uri = canary); + let _entered = span.enter(); + record_refusal!(recorder, RefusalNote::new(FailedCheck::TokenAudience)); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains(canary), "{output}"); + } + + #[test] + fn the_macro_carries_a_remedy_and_a_trace_id_when_given() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let trace_id = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"); + let output = captured(|| { + let note = RefusalNote::new(FailedCheck::Scope).with_remedy("check readsScope"); + record_refusal!(recorder, note, trace_id = trace_id); + }); + assert!(output.contains("remedy=\"check readsScope\""), "{output}"); + assert!( + output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736"), + "{output}" + ); + + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = &trace_id + ); + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = ServerTraceId("0af7651916cd43dd8448eb211c80319c") + ); + }); + assert_eq!(output.lines().count(), 2, "{output}"); + assert!(!output.contains("remedy"), "{output}"); + assert!(output.contains("trace_id=0af7651916cd43dd8448eb211c80319c")); + } + + #[test] + fn a_scope_refusal_names_the_declared_scope_and_no_token_value() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let token_scope = "canary-token-scope-9c1e"; + let declared = DeclaredScope::new("scope") + .with_required_scope("registry.read") + .with_access_profile("caseworker"); + let output = captured(|| { + let _ = token_scope; + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + trace_id = ServerTraceId("4bf92f3577b34da6a3ce929d0e0e4736"), + declared = Some(&declared) + ); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("failed_check=\"scope\""), "{output}"); + assert!(output.contains("scope_claim=\"scope\""), "{output}"); + assert!( + output.contains("required_scope=\"registry.read\""), + "{output}" + ); + assert!(output.contains("access_profile=\"caseworker\""), "{output}"); + assert!(output.contains("trace_id=4bf92f3577b34da6a3ce929d0e0e4736")); + assert!(!output.contains("canary"), "{output}"); + + // Only the members that were declared are written. + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope).with_remedy("check scopeClaim"), + declared = Some(&DeclaredScope::new("scp")) + ); + }); + assert!(output.contains("scope_claim=\"scp\""), "{output}"); + assert!(output.contains("remedy=\"check scopeClaim\""), "{output}"); + assert!(!output.contains("required_scope"), "{output}"); + assert!(!output.contains("access_profile"), "{output}"); + } + + #[test] + fn declared_scope_values_are_written_only_for_a_scope_refusal() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let declared = DeclaredScope::new("scope").with_required_scope("registry.read"); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::TokenAudience), + declared = Some(&declared) + ); + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + declared = None + ); + }); + assert_eq!(output.lines().count(), 2, "{output}"); + assert!(!output.contains("scope_claim"), "{output}"); + assert!(!output.contains("required_scope"), "{output}"); + } + + #[test] + fn a_declared_value_is_bounded_and_kept_on_one_line() { + let long = "s".repeat(DECLARED_VALUE_MAX_BYTES + 50); + let declared = DeclaredScope::new(long.as_str()) + .with_required_scope("é".repeat(DECLARED_VALUE_MAX_BYTES)) + .with_access_profile("line\nbreak"); + assert_eq!(declared.scope_claim().len(), DECLARED_VALUE_MAX_BYTES); + let required = declared.required_scope().unwrap(); + assert!(required.len() <= DECLARED_VALUE_MAX_BYTES); + assert!(required.chars().all(|c| c == 'é')); + + let recorder = RefusalRecorder::new("breg").unwrap(); + let output = captured(|| { + record_refusal!( + recorder, + RefusalNote::new(FailedCheck::Scope), + declared = Some(&declared) + ); + }); + assert_eq!(output.lines().count(), 1, "{output}"); + } + + #[test] + fn the_macro_is_bounded() { + let recorder = RefusalRecorder::new("breg").unwrap(); + let output = captured(|| { + for _ in 0..100 { + record_refusal!(recorder, RefusalNote::new(FailedCheck::Scope)); + } + }); + assert_eq!(output.lines().count(), 5); + let _ = Duration::ZERO; + } +} diff --git a/crates/registry-platform-config/Cargo.toml b/crates/registry-platform-config/Cargo.toml index 3a1df14a0c..53c29331aa 100644 --- a/crates/registry-platform-config/Cargo.toml +++ b/crates/registry-platform-config/Cargo.toml @@ -11,10 +11,13 @@ publish = false workspace = true [features] +test-support = [] schema = ["dep:schemars", "registry-platform-yaml/schema"] [dependencies] registry-platform-canonical-json = { workspace = true } +registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true registry-platform-yaml.workspace = true rustix.workspace = true schemars = { workspace = true, optional = true } @@ -22,6 +25,7 @@ serde.workspace = true serde_json.workspace = true sha2.workspace = true thiserror.workspace = true +tracing.workspace = true url.workspace = true zeroize.workspace = true diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index b477d3dc9f..93f1d2c200 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -8,10 +8,23 @@ owns and validates the rest of its configuration contract. Secret consumers use `SecretResolver::resolve_reference` for bounded values without NUL bytes. Cryptographic consumers use `resolve_binary_reference` for opaque key files, which preserves every byte, including zero bytes. Both paths -apply the same provider allowlist, owner-only regular-file checks, size bounds, -redacted diagnostics, and zeroization. The consumer validates its key format and +apply the same provider allowlist, regular-file checks, size bounds, redacted +diagnostics, and zeroization. The consumer validates its key format and length; the resolver does not decode, trim, or reinterpret file contents. +A secret file is read through one rule. The name may be a relative link that +stays below `secretProviders.file.root` (downward steps only, at most 8 links, +no `..`, no absolute target). The file it reaches must be a regular file with +one hard link and no write access for others, and either owned by the runtime +user with mode 0400 or 0600, or owned by root with no bit outside 0640 when the +runtime is not root. A process that declared development loads a file whose +read or mode bits are too loose and logs one warning per check. Every other +refusal holds in both postures. A refusal is a `SecretError::UnsafeFile` +carrying a `SecretFileCheck`, whose `code()` is `platform.secret-file.`, +and `SecretError::suggested_action()` gives the fix for any failure. +`SecretResolver::inspect_reference` runs the same checks without reading the +bytes. + ## Loader `RuntimeConfigLoader` reads one runtime configuration file named by an @@ -129,11 +142,16 @@ accepted reference through the explicitly enabled environment or file provider. has no default; a product that makes verification optional states its own disabled form beside it. - `UrlHookDestinationConfig`: one signed URL hook destination: a checked - `url`, `hmacSha256KeyRef`, `attemptTimeoutMilliseconds` (default 5000, from + `url`, `hmacSha256KeyRef`, optional `previousHmacSha256KeyRef` for rotation, + `attemptTimeoutMilliseconds` (default 5000, from 100 to 10000), and `maximumAttempts` (default 8, from 1 to 20). A product holds them as a map of at most 128 entries keyed by a local identifier through `url_hook_destinations`. `registry-platform-hooks` activates the block under a fixed outbound policy: https, or http on a loopback host. + Keep `hmacSha256KeyRef` stable during rotation because the binding digest + includes it. The digest excludes `previousHmacSha256KeyRef`. Omit that + member when there is no previous key. Activation resolves both references + as exact binary keys when both are configured and refuses reused key bytes. ## Project check acceptances diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 6b656da136..26c416e5d9 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -17,7 +17,10 @@ use std::str::FromStr; use registry_platform_yaml::{BoundedU32, ExternalId, Invalid, LocalId, Url}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::{SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES}; +use crate::{ + DevelopmentClass, DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, Gated, + SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES, +}; /// The schema pattern of a field that must name an enabled secret provider. pub const SECRET_PROVIDER_PATTERN: &str = "^secret:(?:env|file)/"; @@ -128,9 +131,13 @@ pub struct SecretProvidersConfig { #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FileSecretProviderConfig { - /// Absolute directory holding one file per secret. Each file must be a - /// regular file owned by the runtime user, mode 0400 or 0600, with exactly - /// one hard link. + /// Absolute directory holding one file per secret. A name may be a + /// relative link that stays below this directory, through at most 8 links. + /// The file it reaches must be a regular file with one hard link, owned by + /// the runtime user with mode 0400 or 0600, or owned by root with no + /// access beyond group read (0440 or 0640) when the runtime is not root. + /// A process that declared development loads a file with looser read or + /// mode bits and logs a warning. #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] pub root: PathBuf, } @@ -227,11 +234,12 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro SecretError::Unavailable => { "no readable secret of that name exists under the configured provider".to_owned() } - SecretError::UnsafeFile => concat!( - "the secret file must be a regular file owned by the runtime user, ", - "with mode 0400 or 0600, and exactly one hard link" - ) - .to_owned(), + SecretError::UnsafeFile(check) => format!( + "{} ({}). {}", + check.message(), + check.code(), + check.suggested_action() + ), SecretError::Read => "the secret could not be read".to_owned(), SecretError::InvalidValue => format!( "the secret value must be non-empty text of at most {MAX_SECRET_BYTES} bytes \ @@ -261,6 +269,12 @@ pub struct DatabaseConfig { /// Allow a plaintext connection. Refused outside test builds. #[serde(default)] pub test_only_plaintext: bool, + /// How the connection is protected. Absent means `verified-tls`. A + /// plaintext transport must match the database hosts, and cannot be + /// written beside `testOnlyPlaintext`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "Gated"))] + pub transport: Option>, } impl fmt::Debug for DatabaseConfig { @@ -274,6 +288,7 @@ impl fmt::Debug for DatabaseConfig { &self.ca_bundle_ref.as_ref().map(|_| ""), ) .field("test_only_plaintext", &self.test_only_plaintext) + .field("transport", &self.transport) .finish() } } @@ -293,6 +308,207 @@ impl DatabaseConfig { } } +/// How a PostgreSQL connection is protected. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum DatabaseTransport { + /// TLS with verification. `caBundleRef` is optional. + #[default] + VerifiedTls, + /// No TLS. Every host must be a Unix socket, a numeric loopback address + /// or `localhost`. + LoopbackPlaintext, + /// No TLS, in development only. Every host must also be loopback, a + /// socket, a private IPv4 address (RFC 1918), an IPv6 unique local + /// address (`fc00::/7`), or a name that resolves only to such addresses. + PrivateNetworkPlaintext, +} + +static DATABASE_PRIVATE_PLAINTEXT: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.database-private-plaintext", + key: "transport", + summary: "The database connection is not encrypted and reaches a private network", + production: "Write database.transport: verified-tls, and give the database a certificate the runtime trusts.", +}; + +impl DevelopmentClass for DatabaseTransport { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&DATABASE_PRIVATE_PLAINTEXT]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::VerifiedTls | Self::LoopbackPlaintext => None, + Self::PrivateNetworkPlaintext => Some(&DATABASE_PRIVATE_PLAINTEXT), + } + } +} + +/// A host a PostgreSQL URL names, once the secret is resolved and the URL +/// parsed by the product's driver. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DatabaseHost { + /// A host name or address, with no brackets required around an IPv6 + /// literal. + Tcp(String), + /// A Unix socket directory. + Unix, +} + +/// Why a database transport was refused. No variant repeats a configured +/// value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseTransportError { + /// A host is not one the plaintext transport permits. + HostMismatch(DatabaseTransport), + /// The transport is development-only and the caller holds no witness. + DevelopmentOnly(DevelopmentOnlyRefused), + /// `transport` and `testOnlyPlaintext` are both written. + Conflict, + /// `testOnlyPlaintext` in a build that is not a test build. + TestOnlyPlaintext, +} + +impl DatabaseTransportError { + /// The stable code of the refusal (CFG-DIAG-3). + #[must_use] + pub const fn code(&self) -> &'static str { + match self { + Self::HostMismatch(_) => "platform.database.transport-host-mismatch", + Self::DevelopmentOnly(refused) => refused.setting.code, + Self::Conflict => "platform.database.transport-conflict", + Self::TestOnlyPlaintext => "platform.database.test-only-plaintext", + } + } + + /// What to write instead. + #[must_use] + pub const fn suggested_action(&self) -> &'static str { + match self { + Self::HostMismatch(DatabaseTransport::PrivateNetworkPlaintext) => { + "Name a Unix socket, a loopback address, a private-network address or a name that resolves only to such addresses, or write database.transport: verified-tls." + } + Self::HostMismatch(_) => { + "Name a Unix socket, a loopback address or localhost, or write database.transport: verified-tls." + } + Self::DevelopmentOnly(refused) => refused.setting.production, + Self::Conflict => "Remove database.testOnlyPlaintext, and keep database.transport.", + Self::TestOnlyPlaintext => { + "Remove it, and set database.transport for a plaintext connection on the same host." + } + } + } +} + +impl fmt::Display for DatabaseTransportError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::HostMismatch(_) => { + "a database host is not one the configured plaintext transport permits" + } + Self::DevelopmentOnly(_) => { + "the database transport is accepted only when the process declares development" + } + Self::Conflict => "database.transport and database.testOnlyPlaintext are both set", + Self::TestOnlyPlaintext => "database.testOnlyPlaintext is accepted only by test builds", + }) + } +} + +impl std::error::Error for DatabaseTransportError {} + +impl DatabaseConfig { + /// The checks every posture applies to the transport: `transport` is not + /// written beside `testOnlyPlaintext`, and `testOnlyPlaintext` is + /// written only in a test build, which the product states with + /// `test_build`. + pub fn check(&self, test_build: bool) -> Result<(), DatabaseTransportError> { + if self.test_only_plaintext && self.transport.is_some() { + return Err(DatabaseTransportError::Conflict); + } + if self.test_only_plaintext && !test_build { + return Err(DatabaseTransportError::TestOnlyPlaintext); + } + Ok(()) + } + + /// The transport the connection uses, once `hosts` are known: a plaintext + /// transport is returned only when every host is one it permits. A + /// development-only transport is readable with `witness` alone. A name is + /// resolved here, once, so a later re-resolution by the driver is outside + /// the check; a name that does not resolve is refused. + pub fn plaintext_permitted( + &self, + hosts: &[DatabaseHost], + witness: Option<&DevelopmentWitness>, + ) -> Result { + plaintext_permitted_with(self, hosts, witness, &resolve_host) + } +} + +fn resolve_host(name: &str) -> std::io::Result> { + use std::net::ToSocketAddrs; + (name, 0) + .to_socket_addrs() + .map(|addresses| addresses.map(|address| address.ip()).collect()) +} + +pub(crate) fn plaintext_permitted_with( + config: &DatabaseConfig, + hosts: &[DatabaseHost], + witness: Option<&DevelopmentWitness>, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> Result { + let transport = match &config.transport { + None => DatabaseTransport::VerifiedTls, + Some(gated) => *gated + .get(witness) + .map_err(DatabaseTransportError::DevelopmentOnly)?, + }; + let permitted = |host: &DatabaseHost| match (transport, host) { + (DatabaseTransport::VerifiedTls, _) | (_, DatabaseHost::Unix) => true, + (DatabaseTransport::LoopbackPlaintext, DatabaseHost::Tcp(name)) => { + registry_platform_loopback::loopback_host(name).is_some() + } + (DatabaseTransport::PrivateNetworkPlaintext, DatabaseHost::Tcp(name)) => { + private_network_host(name, resolve) + } + }; + if hosts.iter().all(permitted) { + Ok(transport) + } else { + Err(DatabaseTransportError::HostMismatch(transport)) + } +} + +/// Whether `name` is loopback, a private IPv4 address, an IPv6 unique local +/// address, or a name that resolves, and resolves only, to such addresses. +fn private_network_host( + name: &str, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> bool { + if registry_platform_loopback::loopback_host(name).is_some() { + return true; + } + let literal = name + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or(name); + if let Ok(address) = literal.parse::() { + return private_address(address); + } + match resolve(name) { + Ok(addresses) => !addresses.is_empty() && addresses.into_iter().all(private_address), + Err(_) => false, + } +} + +fn private_address(address: IpAddr) -> bool { + match address { + IpAddr::V4(address) => address.is_loopback() || address.is_private(), + IpAddr::V6(address) => address.is_loopback() || is_unique_local(address), + } +} + /// Where a runtime obtains the OIDC issuer's signing keys. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] @@ -321,10 +537,36 @@ pub enum JwksSource { #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] document_ref: String, }, + /// Read the key set from a secret, as `static` does, for a test issuer a + /// development run supervises. Development only: production refuses it. + TestIssuer { + #[serde(rename = "documentRef")] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + document_ref: String, + }, } registry_platform_yaml::tagged_union!(JwksSource); +static TEST_ISSUER: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.test-issuer", + key: "type", + summary: "The issuer's signing keys come from a test issuer", + production: + "Write jwksSource: {type: discovery}, or a static or uri source for the real issuer.", +}; + +impl DevelopmentClass for JwksSource { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&TEST_ISSUER]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::Discovery {} | Self::Uri { .. } | Self::Static { .. } => None, + Self::TestIssuer { .. } => Some(&TEST_ISSUER), + } + } +} + impl Serialize for JwksSource { fn serialize(&self, serializer: S) -> Result { use serde::ser::SerializeMap; @@ -334,6 +576,9 @@ impl Serialize for JwksSource { Self::Static { document_ref } => { ("static", Some(("documentRef", document_ref.as_str()))) } + Self::TestIssuer { document_ref } => { + ("test-issuer", Some(("documentRef", document_ref.as_str()))) + } }; let mut map = serializer.serialize_map(Some(1 + usize::from(member.is_some())))?; map.serialize_entry("type", tag)?; @@ -382,7 +627,7 @@ impl JwksSource { )) } } - Self::Static { document_ref } => { + Self::Static { document_ref } | Self::TestIssuer { document_ref } => { if document_ref.is_empty() { let field = format!("{field}.documentRef"); Err(ConfigBlockError::new( @@ -406,11 +651,11 @@ impl JwksSource { } } - /// The secret reference a `static` source reads. + /// The secret reference a `static` or `test-issuer` source reads. #[must_use] pub fn document_ref(&self) -> Option<&str> { match self { - Self::Static { document_ref } => Some(document_ref), + Self::Static { document_ref } | Self::TestIssuer { document_ref } => Some(document_ref), _ => None, } } @@ -426,12 +671,10 @@ fn valid_jwks_uri(value: &Url, allow_loopback_http: bool, allow_insecure_http: b "http" => { allow_insecure_http || (allow_loopback_http - && match parsed.host() { - Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(address)) => address.is_loopback(), - Some(url::Host::Ipv6(address)) => address.is_loopback(), - None => false, - }) + && parsed + .host_str() + .and_then(registry_platform_loopback::loopback_host) + .is_some()) } _ => false, } @@ -451,6 +694,51 @@ fn valid_jwks_uri(value: &Url, allow_loopback_http: bool, allow_insecure_http: b pub struct AuditKeyConfig { /// Secret reference to the audit hash key. pub hash_key_ref: SecretReference, + /// Who provisioned the key. Absent means `operator-provisioned`. + /// `development-generated` marks a key a development tool made. + #[serde( + default = "operator_provisioned", + skip_serializing_if = "is_operator_provisioned" + )] + pub hash_key_custody: Gated, +} + +/// Who provisioned the audit hash key. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum AuditKeyCustody { + /// The operator provisioned the key. + #[default] + OperatorProvisioned, + /// A development tool generated the key. + DevelopmentGenerated, +} + +static GENERATED_AUDIT_KEY: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.generated-audit-key", + key: "hashKeyCustody", + summary: "The audit hash key was generated by a development tool", + production: "Provision an audit hash key, reference it in audit.hashKeyRef, and write audit.hashKeyCustody: operator-provisioned.", +}; + +impl DevelopmentClass for AuditKeyCustody { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&GENERATED_AUDIT_KEY]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Self::OperatorProvisioned => None, + Self::DevelopmentGenerated => Some(&GENERATED_AUDIT_KEY), + } + } +} + +fn operator_provisioned() -> Gated { + Gated::wrap(AuditKeyCustody::OperatorProvisioned) +} + +fn is_operator_provisioned(custody: &Gated) -> bool { + custody.development_setting().is_none() } impl AuditKeyConfig { @@ -484,25 +772,82 @@ pub struct OidcIssuerConfig { pub audience: String, /// Where the issuer's signing keys come from. Absent reads the issuer's /// OpenID Connect discovery document. - #[serde(default)] + #[serde(default, deserialize_with = "deserialize_jwks_source")] + #[cfg_attr( + feature = "schema", + schemars(extend("x-registry-development-only" = ["platform.posture.test-issuer"])) + )] pub jwks_source: JwksSource, /// Permit plain HTTP beyond loopback to the configured issuer and to a - /// JWKS URI declared in configuration. TLS remains required unless the - /// operator explicitly accepts this transport risk. - #[serde(default)] + /// JWKS URI declared in configuration. Loopback needs no setting. The + /// value `true` is a development-only setting: the loader records it, and + /// production refuses it. + #[serde(default, deserialize_with = "deserialize_insecure_http")] + #[cfg_attr( + feature = "schema", + schemars(extend("x-registry-development-only" = ["platform.posture.insecure-issuer-http"])) + )] pub allow_insecure_http: bool, } +/// The value of `allowInsecureHttp`. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(transparent)] +pub struct InsecureHttp(pub bool); + +static INSECURE_ISSUER_HTTP: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.insecure-issuer-http", + key: "allowInsecureHttp", + summary: "Plain http is permitted to an issuer beyond loopback", + production: "Delete allowInsecureHttp and use an https issuer.", +}; + +impl DevelopmentClass for InsecureHttp { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&INSECURE_ISSUER_HTTP]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.then_some(&INSECURE_ISSUER_HTTP) + } +} + +/// Read `allowInsecureHttp` through [`Gated`], so a loader that collects +/// development-only settings records `true` with its pointer. +fn deserialize_insecure_http<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Gated::::deserialize(deserializer) + .map(|value| value.development_setting().is_some()) +} + +/// Read `jwksSource` through [`Gated`], so a loader that collects +/// development-only settings records a test issuer with its pointer. +fn deserialize_jwks_source<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + Gated::::deserialize(deserializer).map(Gated::into_inner) +} + impl OidcIssuerConfig { /// The issuer is an absolute `https` URL without credentials, query, or - /// fragment, or a plain `http` one when `allow_insecure_http` is set, the - /// audience is non-empty bounded text without control characters, and - /// the key source passes [`JwksSource::check`]. Without - /// `allow_insecure_http`, a loopback `http` issuer or key URI is accepted - /// only when `allow_loopback_http` is set, for supervised local - /// development. `field` is the dotted path of the block, - /// such as `authentication.oidc`. - pub fn check(&self, field: &str, allow_loopback_http: bool) -> Result<(), ConfigBlockError> { + /// fragment, a loopback `http` one, or a plain `http` one when + /// `allow_insecure_http` is set, the audience is non-empty bounded text + /// without control characters, and the key source passes + /// [`JwksSource::check`]. Loopback needs no setting in any posture. A + /// plain `http` issuer beyond loopback is accepted here when + /// `allow_insecure_http` is set, and the posture decision refuses it in + /// production. `field` is the dotted path of the block, such as + /// `authentication.oidc`. + pub fn check(&self, field: &str) -> Result<(), ConfigBlockError> { + self.check_without_posture(field, true) + } + + /// [`OidcIssuerConfig::check`] for a runtime that has not adopted the + /// posture: a loopback `http` issuer or key URI is accepted only when + /// `allow_loopback_http` is set. + pub fn check_without_posture( + &self, + field: &str, + allow_loopback_http: bool, + ) -> Result<(), ConfigBlockError> { let issuer = self.issuer.to_url(); let issuer_ok = valid_jwks_uri(&self.issuer, allow_loopback_http, self.allow_insecure_http) && issuer.query().is_none() @@ -789,6 +1134,235 @@ impl OidcClientsConfig { } } +const FROM_PACKAGE: &str = "from-package"; + +/// How `allowedClients` is written where the governed package names the +/// clients (CFG-EMPTY-2): the keyword `from-package`, the keyword +/// `unrestricted`, or a list of at least one client. The member stays +/// required and an empty list is refused. A runtime resolves the value with +/// [`PackageClients::resolve`] before it builds a token verifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum PackageClients { + /// Admit exactly the clients the package's access profiles name. + FromPackage, + /// Admit a token from every client the issuer verifies. A runtime decides + /// whether that is acceptable in production. + Unrestricted, + /// Admit the listed clients, which must cover every package client. + Listed(Vec), +} + +/// The keywords `allowedClients` takes beside a list. +enum PackageClientsKeyword { + FromPackage, + Unrestricted, +} + +fn package_clients_refused() -> E { + registry_platform_yaml::Invalid::expected( + "from-package, unrestricted, or a list of at least one OAuth client", + "Write from-package to admit the package's requester clients, list the OAuth clients whose access tokens are admitted, or write unrestricted to admit every client the issuer verifies.", + ) + .into_error() +} + +impl<'de> Deserialize<'de> for PackageClientsKeyword { + fn deserialize>(deserializer: D) -> Result { + match String::deserialize(deserializer)?.as_str() { + FROM_PACKAGE => Ok(Self::FromPackage), + UNRESTRICTED => Ok(Self::Unrestricted), + _ => Err(package_clients_refused()), + } + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for PackageClientsKeyword { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "PackageClientsKeyword".into() + } + + fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({"type": "string", "enum": [FROM_PACKAGE, UNRESTRICTED]}) + } +} + +/// The authored shape of [`PackageClients`], so the schema and the reader +/// agree on the two forms. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "schema", schemars(untagged))] +enum OidcPackageAllowedClients { + /// A keyword. + Keyword(PackageClientsKeyword), + /// Admit a token only from a listed client. + Listed(ListedClients), +} + +registry_platform_yaml::shape_union!(OidcPackageAllowedClients { scalar => Keyword, list => Listed }); + +impl<'de> Deserialize<'de> for PackageClients { + fn deserialize>(deserializer: D) -> Result { + Ok( + match OidcPackageAllowedClients::deserialize(deserializer)? { + OidcPackageAllowedClients::Keyword(PackageClientsKeyword::FromPackage) => { + Self::FromPackage + } + OidcPackageAllowedClients::Keyword(PackageClientsKeyword::Unrestricted) => { + Self::Unrestricted + } + OidcPackageAllowedClients::Listed(ListedClients(clients)) => Self::Listed(clients), + }, + ) + } +} + +impl Serialize for PackageClients { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::FromPackage => serializer.serialize_str(FROM_PACKAGE), + Self::Unrestricted => serializer.serialize_str(UNRESTRICTED), + Self::Listed(clients) => clients.serialize(serializer), + } + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for PackageClients { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + "OidcPackageAllowedClients".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + OidcPackageAllowedClients::json_schema(generator) + } +} + +/// The OAuth clients a runtime admits access tokens for when the governed +/// package names its requester clients, and the assertion authorities each +/// client may exchange a subject token from, written under +/// `authentication.oidc` beside the issuer. Runtimes whose package does not +/// name clients keep [`OidcClientsConfig`]. +// A product's `authentication.oidc` block embeds this with +// `#[serde(flatten)]`, as it does `OidcClientsConfig`. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "schema", schemars(deny_unknown_fields))] +pub struct OidcPackageClientsConfig { + /// The OAuth clients whose access tokens are admitted: `from-package` for + /// the package's requester clients, `unrestricted` for every client the + /// issuer verifies, or a list of at least one distinct client that covers + /// the package's requester clients. + pub allowed_clients: PackageClients, + /// Assertion authorities each client may exchange a subject token from, + /// with the meaning and bounds of `OidcClientsConfig::assertion_issuers`. + #[serde( + default, + skip_serializing_if = "BTreeMap::is_empty", + deserialize_with = "non_empty_assertion_issuers" + )] + #[cfg_attr(feature = "schema", schemars(schema_with = "assertion_issuers_schema"))] + pub assertion_issuers: BTreeMap>, +} + +impl OidcPackageClientsConfig { + /// The bounds of [`OidcClientsConfig::check`] on `assertionIssuers`. + pub fn check(&self, field: &str) -> Result<(), ConfigBlockError> { + OidcClientsConfig { + allowed_clients: Vec::new(), + assertion_issuers: self.assertion_issuers.clone(), + } + .check(field) + } +} + +/// A non-empty, sorted list of the clients a token verifier admits. It is the +/// only value a runtime passes to a verifier built from [`PackageClients`], so +/// an unresolved keyword cannot reach it as the empty list, which a verifier +/// reads as "every client". +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AdmittedClients(Vec); + +impl AdmittedClients { + /// The sorted, de-duplicated clients, or `None` when there are none. + #[must_use] + pub fn new(clients: Vec) -> Option { + let clients: BTreeSet = clients.into_iter().collect(); + if clients.is_empty() { + None + } else { + Some(Self(clients.into_iter().collect())) + } + } + + #[must_use] + pub fn as_slice(&self) -> &[String] { + &self.0 + } + + #[must_use] + pub fn into_vec(self) -> Vec { + self.0 + } +} + +/// Why [`PackageClients::resolve`] produced no admitted clients. Client +/// identifiers are not secrets. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +pub enum PackageClientsError { + /// `allowedClients` is `unrestricted`, which this resolution never turns + /// into a list. + #[error("allowedClients is unrestricted and admits no resolved list of clients")] + Unrestricted, + /// The resolved list has no client: the package names none, or the list + /// is empty. + #[error("allowedClients resolves to no client")] + Empty, + /// The explicit list leaves out a client the package names. + #[error("allowedClients does not list the package client {0}")] + Missing(String), +} + +impl PackageClients { + /// The clients to admit, given the requester clients of every access + /// profile of the loaded package. `FromPackage` is the sorted union of + /// `package_clients`. `Listed` is returned when it covers every package + /// client, and refused naming the first missing one otherwise. Extra + /// clients in a list stay admitted. `Unrestricted` and an empty result are + /// errors: the runtime decides what `Unrestricted` means for it. + pub fn resolve( + &self, + package_clients: &[String], + ) -> Result { + match self { + Self::Unrestricted => Err(PackageClientsError::Unrestricted), + Self::FromPackage => { + AdmittedClients::new(package_clients.to_vec()).ok_or(PackageClientsError::Empty) + } + Self::Listed(listed) => { + let admitted = + AdmittedClients::new(listed.clone()).ok_or(PackageClientsError::Empty)?; + let missing = package_clients + .iter() + .filter(|client| !admitted.0.contains(client)) + .min(); + match missing { + Some(client) => Err(PackageClientsError::Missing(client.clone())), + None => Ok(admitted), + } + } + } + } +} + /// The package a runtime serves: `root` is the absolute package directory, /// and `expectedDigest`, when set, pins the package digest the runtime must /// find there. The package digest is the digest of the package's @@ -958,6 +1532,10 @@ pub struct MetricsListenerConfig { pub enum TlsTermination { OperatorControlledUpstream, DevelopmentLoopback, + /// Plaintext on a loopback bind, behind a proxy on the same host. Valid + /// in every posture. It is placement only: it relaxes nothing a product + /// relaxes under `development-loopback`. + LoopbackPlaintext, } /// The operator-declared private network placement of an HTTP listener. @@ -993,9 +1571,16 @@ impl PrivateListenerConfig { if address.is_multicast() { return false; } - if self.tls_termination == TlsTermination::DevelopmentLoopback { - return self.network_exposure == ListenerNetworkExposure::PrivateAddress - && address.is_loopback(); + match self.tls_termination { + TlsTermination::DevelopmentLoopback => { + return self.network_exposure == ListenerNetworkExposure::PrivateAddress + && address.is_loopback(); + } + TlsTermination::LoopbackPlaintext => { + return self.network_exposure == ListenerNetworkExposure::PrivateAddress + && registry_platform_loopback::loopback_address(address); + } + TlsTermination::OperatorControlledUpstream => {} } match (address, self.network_exposure) { (IpAddr::V4(address), ListenerNetworkExposure::PrivateAddress) => { @@ -1192,7 +1777,7 @@ pub const MAX_HOOK_ATTEMPTS: u8 = 20; pub const DEFAULT_HOOK_MAXIMUM_ATTEMPTS: u8 = 8; /// One URL hook destination a runtime signs and sends hook deliveries to: -/// the URL, the HMAC-SHA256 key reference, and the delivery budget. The +/// the URL, the HMAC-SHA256 key references, and the delivery budget. The /// outbound policy is fixed: `registry-platform-hooks` activates it with no /// private address range and no client certificate. A runtime whose /// destinations need either configures its own full outbound policy instead. @@ -1204,6 +1789,15 @@ pub struct UrlHookDestinationConfig { /// query or fragment. pub url: Url, pub hmac_sha256_key_ref: SecretReference, + /// Optional previous signing key for rotation, excluded from the + /// destination binding digest. + #[serde( + default, + deserialize_with = "present_hook_key_reference", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, /// How long one delivery attempt may take, from 100 through 10000 /// milliseconds. #[serde( @@ -1227,6 +1821,13 @@ pub struct UrlHookDestinationConfig { pub maximum_attempts: u8, } +fn present_hook_key_reference<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + SecretReference::deserialize(deserializer).map(Some) +} + impl UrlHookDestinationConfig { /// Whether the attempt timeout and attempt count stay inside the /// delivery budget: the bound the reader enforces at load and hook diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 212de6a5fb..f33f1c8661 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -174,6 +174,34 @@ fn jwks_source_has_three_types_and_defaults_to_discovery() { } } +#[test] +fn jwks_uri_loopback_follows_the_shared_definition() { + let check = |uri: &str| { + JwksSource::Uri { + uri: Url::new(uri).unwrap(), + } + .check("authentication.oidc.jwksSource", true) + }; + for uri in [ + "http://127.0.0.1:1/jwks", + "http://127.0.0.2:1/jwks", + "http://[::1]:1/jwks", + "http://[::ffff:127.0.0.1]:1/jwks", + "http://localhost:1/jwks", + "http://LOCALHOST:1/jwks", + ] { + check(uri).unwrap_or_else(|error| panic!("{uri}: {error:?}")); + } + for uri in [ + "http://localhost.:1/jwks", + "http://issuer.localhost:1/jwks", + "http://0.0.0.0:1/jwks", + "http://[::ffff:10.0.0.1]:1/jwks", + ] { + assert!(check(uri).is_err(), "{uri}"); + } +} + #[test] fn issuer_and_jwks_uri_are_checked_urls_when_read() { for text in [ @@ -209,7 +237,9 @@ fn issuer_and_jwks_uri_are_checked_urls_when_read() { let issuer: OidcIssuerConfig = read_block(&serde_json::json!({"issuer": text, "audience": "api"}).to_string()) .expect("ordinary issuer URL"); - issuer.check("authentication.oidc", false).unwrap(); + issuer + .check_without_posture("authentication.oidc", false) + .unwrap(); assert_eq!(issuer.issuer.as_str(), text); } } @@ -340,6 +370,97 @@ fn private_listener_follows_the_declared_boundary() { )); } +#[test] +fn loopback_plaintext_is_placement_only_and_follows_the_loopback_rule() { + use ListenerNetworkExposure::{ContainerPrivate, PrivateAddress}; + use TlsTermination::{DevelopmentLoopback, LoopbackPlaintext}; + let listener: PrivateListenerConfig = + read_block("bind: 127.0.0.1:8080\ntlsTermination: loopback-plaintext") + .expect("loopback-plaintext decodes"); + assert_eq!(listener.tls_termination, LoopbackPlaintext); + assert!(listener.is_valid()); + let unknown = read_block::( + "bind: 127.0.0.1:8080\ntlsTermination: loopback-plaintxt", + ); + assert!(unknown.is_err(), "a misspelt value is refused"); + + let valid = |bind: &str, tls, exposure| { + PrivateListenerConfig { + bind: bind.parse().unwrap(), + tls_termination: tls, + network_exposure: exposure, + } + .is_valid() + }; + for bind in ["127.0.0.1:1", "[::1]:1", "127.0.0.2:1"] { + assert!(valid(bind, LoopbackPlaintext, PrivateAddress), "{bind}"); + } + // The refusals match `development-loopback` for every bind and exposure. + for bind in [ + "127.0.0.1:1", + "[::1]:1", + "127.0.0.2:1", + "10.0.0.1:1", + "[fd00::1]:1", + "0.0.0.0:1", + "[::]:1", + "8.8.8.8:1", + "224.0.0.1:1", + ] { + for exposure in [PrivateAddress, ContainerPrivate] { + assert_eq!( + valid(bind, LoopbackPlaintext, exposure), + valid(bind, DevelopmentLoopback, exposure), + "{bind} {exposure:?}" + ); + } + } + assert!(!valid("10.0.0.1:1", LoopbackPlaintext, PrivateAddress)); + assert!(!valid("127.0.0.1:1", LoopbackPlaintext, ContainerPrivate)); + assert_eq!( + serde_json::to_value(LoopbackPlaintext).unwrap(), + "loopback-plaintext" + ); +} + +#[test] +fn test_issuer_reads_a_secret_reference_like_static_and_nothing_else() { + let source: JwksSource = + read_block("type: test-issuer\ndocumentRef: secret:env/TEST_JWKS").expect("decodes"); + assert_eq!( + source, + JwksSource::TestIssuer { + document_ref: "secret:env/TEST_JWKS".to_owned() + } + ); + assert_eq!(source.document_ref(), Some("secret:env/TEST_JWKS")); + source + .check("authentication.oidc", false) + .expect("a reference passes"); + let empty = JwksSource::TestIssuer { + document_ref: String::new(), + }; + assert_eq!( + empty + .check("authentication.oidc", false) + .expect_err("empty reference") + .field(), + "authentication.oidc.documentRef" + ); + assert_eq!( + serde_json::to_value(&source).unwrap(), + serde_json::json!({"type": "test-issuer", "documentRef": "secret:env/TEST_JWKS"}) + ); + for text in [ + "type: test-issuer", + "type: test-issuer\ndocumentRef: secret:env/X\nuri: https://x.example.test", + "type: test-issuer\ndocumentRef: secret:env/X\nunknown: 1", + "type: test-issuer\ndocumentRf: secret:env/X", + ] { + assert!(read_block::(text).is_err(), "{text}"); + } +} + #[test] fn sha256_label_shape() { assert!(is_sha256_label(&crate::sha256_uri(b"x"))); @@ -513,14 +634,14 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { "urn:example:api", JwksSource::default(), ) - .check(field, false) + .check_without_posture(field, false) .expect("https issuer"); issuer("http://127.0.0.1:8082", "api", JwksSource::default()) - .check(field, true) + .check_without_posture(field, true) .expect("supervised loopback issuer"); for loopback in ["http://localhost:8082", "http://[::1]:8082"] { issuer(loopback, "api", JwksSource::default()) - .check(field, true) + .check_without_posture(field, true) .expect("every loopback spelling is admitted"); } @@ -532,7 +653,7 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { assert!(opted_in.issuer.allow_insecure_http); opted_in .issuer - .check(field, false) + .check_without_posture(field, false) .expect("explicit HTTP issuer opt-in validates"); for (candidate, loopback, expected_field) in [ @@ -587,7 +708,7 @@ fn the_oidc_issuer_is_an_https_url_and_the_audience_is_bounded_text() { ), ] { let error = candidate - .check(field, loopback) + .check_without_posture(field, loopback) .expect_err("refused issuer"); assert_eq!(error.field(), expected_field, "{error}"); assert!(!error.to_string().contains("user:pass"), "{error}"); @@ -616,7 +737,7 @@ fn the_insecure_http_opt_in_also_admits_a_declared_http_jwks_uri() { }, ); let error = candidate - .check(field, false) + .check_without_posture(field, false) .expect_err("a plain HTTP key URI needs the opt-in"); assert_eq!(error.field(), "authentication.oidc.jwksSource.uri"); assert!(error.to_string().contains("allowInsecureHttp: true")); @@ -624,7 +745,7 @@ fn the_insecure_http_opt_in_also_admits_a_declared_http_jwks_uri() { candidate.allow_insecure_http = true; candidate - .check(field, false) + .check_without_posture(field, false) .expect("the opt-in admits a declared HTTP key URI under an HTTPS issuer"); } @@ -636,14 +757,14 @@ fn an_oidc_issuer_with_a_query_is_refused_without_echoing_it() { "api", JwksSource::default(), ) - .check(field, false) + .check_without_posture(field, false) .expect("an issuer with a path"); for candidate in [ "https://issuer.example.test/realms/pilot?tenant=query-canary", "https://issuer.example.test/?", ] { let error = issuer(candidate, "api", JwksSource::default()) - .check(field, false) + .check_without_posture(field, false) .expect_err("an issuer with a query is refused"); assert_eq!(error.field(), "authentication.oidc.issuer", "{error}"); assert!(error.to_string().contains("query"), "{error}"); @@ -840,7 +961,7 @@ fn a_secret_failure_names_the_member_and_never_the_reference() { SecretError::ProviderDisabled, SecretError::InvalidProviderConfiguration, SecretError::Unavailable, - SecretError::UnsafeFile, + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable), SecretError::Read, SecretError::InvalidValue, ] { @@ -1066,6 +1187,48 @@ fn storage_and_verifier_secret_members_are_references_never_values() { const URL_HOOK_DESTINATION: &str = "url: https://events.example.test/hooks\n\ hmacSha256KeyRef: secret:file/hook-key\n"; +#[test] +fn a_present_previous_hook_key_reference_cannot_be_null() { + let input = format!("{URL_HOOK_DESTINATION}previousHmacSha256KeyRef: null\n"); + assert!(read_block::(&input).is_err()); +} + +#[test] +fn a_url_hook_destination_accepts_a_previous_key_reference() { + let yaml = + format!("{URL_HOOK_DESTINATION}previousHmacSha256KeyRef: secret:file/old-hook-key\n"); + let destination: UrlHookDestinationConfig = read_block(&yaml).unwrap(); + assert_eq!( + destination + .previous_hmac_sha256_key_ref + .as_ref() + .unwrap() + .as_str(), + "secret:file/old-hook-key" + ); + let serialized = serde_json::to_string(&destination).unwrap(); + assert_eq!( + read_block::(&serialized).unwrap(), + destination + ); +} + +#[test] +fn a_url_hook_destination_refuses_an_unknown_member_beside_the_previous_key_reference() { + let yaml = format!( + "{URL_HOOK_DESTINATION}previousHmacSha256KeyRef: secret:file/old-hook-key\nunknown: true\n" + ); + assert!(read_block::(&yaml).is_err()); +} + +#[test] +fn a_url_hook_destination_can_omit_the_previous_key_reference() { + let destination: UrlHookDestinationConfig = read_block(URL_HOOK_DESTINATION).unwrap(); + assert!(destination.previous_hmac_sha256_key_ref.is_none()); + let serialized = serde_json::to_value(&destination).unwrap(); + assert!(serialized.get("previousHmacSha256KeyRef").is_none()); +} + #[test] fn url_hook_destination_defaults_its_delivery_budget_and_never_prints_its_binding() { let defaults: UrlHookDestinationConfig = read_block(URL_HOOK_DESTINATION).unwrap(); @@ -1174,3 +1337,139 @@ fn url_hook_destinations_are_keyed_by_local_identifiers_and_bounded() { ); } } + +fn package_clients(yaml: &str) -> OidcPackageClientsConfig { + read_block(yaml).expect("package clients parse") +} + +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +#[test] +fn from_package_keyword_parses() { + let block = package_clients("allowedClients: from-package"); + assert_eq!(block.allowed_clients, PackageClients::FromPackage); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({"allowedClients": "from-package"}) + ); +} + +#[test] +fn unrestricted_parses() { + let block = package_clients("allowedClients: unrestricted"); + assert_eq!(block.allowed_clients, PackageClients::Unrestricted); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({"allowedClients": "unrestricted"}) + ); +} + +#[test] +fn list_parses() { + let block = package_clients( + "allowedClients: [portal, kiosk]\nassertionIssuers: {portal: [https://assert.example.test]}", + ); + assert_eq!( + block.allowed_clients, + PackageClients::Listed(strings(&["portal", "kiosk"])) + ); + assert_eq!( + block.assertion_issuers["portal"], + ["https://assert.example.test"] + ); + block.check("authentication.oidc").expect("within bounds"); + assert_eq!( + serde_json::to_value(&block).expect("serialize"), + serde_json::json!({ + "allowedClients": ["portal", "kiosk"], + "assertionIssuers": {"portal": ["https://assert.example.test"]}, + }) + ); +} + +#[test] +fn empty_list_is_refused() { + let report = read_block::("allowedClients: []") + .expect_err("an empty list is refused"); + assert_eq!(report.diagnostics()[0].path, "/allowedClients"); +} + +#[test] +fn unknown_keyword_is_refused() { + for refused in [ + "allowedClients: portal", + "allowedClients: From-Package", + "allowedClients: from_package", + "allowedClients: 7", + ] { + let report = read_block::(refused).expect_err(refused); + assert_eq!(report.diagnostics()[0].path, "/allowedClients", "{refused}"); + } +} + +#[test] +fn absent_member_is_refused() { + let report = read_block::("{}").expect_err("omission is refused"); + assert!( + report.diagnostics()[0].message.contains("allowedClients"), + "{:?}", + report.diagnostics() + ); +} + +#[test] +fn a_repeated_listed_client_is_refused() { + let report = read_block::("allowedClients: [portal, portal]") + .expect_err("repeat refused"); + assert_eq!(report.diagnostics()[0].path, "/allowedClients/1"); +} + +#[test] +fn resolve_from_package_returns_the_sorted_union() { + let admitted = PackageClients::FromPackage + .resolve(&strings(&["c3", "c1", "c2", "c3", "c1"])) + .expect("resolves"); + assert_eq!(admitted.as_slice(), ["c1", "c2", "c3"]); +} + +#[test] +fn resolve_never_returns_an_empty_list() { + assert_eq!( + PackageClients::FromPackage + .resolve(&[]) + .expect_err("empty package"), + PackageClientsError::Empty + ); + assert_eq!( + PackageClients::Unrestricted + .resolve(&strings(&["c1"])) + .expect_err("unrestricted"), + PackageClientsError::Unrestricted + ); + assert_eq!( + PackageClients::Listed(Vec::new()) + .resolve(&strings(&["c1"])) + .expect_err("an unparsed empty list"), + PackageClientsError::Empty + ); + assert!(AdmittedClients::new(Vec::new()).is_none()); +} + +#[test] +fn resolve_listed_missing_a_package_client_names_the_client() { + let listed = PackageClients::Listed(strings(&["c1", "c2"])); + let error = listed + .resolve(&strings(&["c1", "c3", "c4"])) + .expect_err("c3 is missing"); + assert_eq!(error, PackageClientsError::Missing("c3".to_owned())); + assert!(error.to_string().contains("c3")); +} + +#[test] +fn resolve_listed_covering_the_package_keeps_extra_clients() { + let listed = PackageClients::Listed(strings(&["c1", "c2", "extra"])); + let admitted = listed.resolve(&strings(&["c2", "c1"])).expect("covers"); + assert_eq!(admitted.as_slice(), ["c1", "c2", "extra"]); +} diff --git a/crates/registry-platform-config/src/check_acceptances.rs b/crates/registry-platform-config/src/check_acceptances.rs index 560b94da1e..2469d53548 100644 --- a/crates/registry-platform-config/src/check_acceptances.rs +++ b/crates/registry-platform-config/src/check_acceptances.rs @@ -87,8 +87,30 @@ pub fn apply_check_acceptances(project_root: &Path, report: &mut Report) { Ok(bytes) => { match read_project_check_acceptances(&acceptance_path.display().to_string(), &bytes) { Ok(decoded) => { - report.extend(decoded.document.report_with(Vec::new())); - Some(decoded.value) + // A posture diagnostic says what production would refuse, + // so no acceptance may hide it. + let refused: Vec = decoded + .value + .acceptances + .iter() + .enumerate() + .filter(|(_, acceptance)| crate::posture::is_posture_code(&acceptance.code)) + .map(|(index, _)| { + decoded.document.diagnostic_at_value( + Severity::Error, + "config.check-acceptance-not-acceptable", + &format!("/acceptances/{index}/code"), + "a posture diagnostic cannot be accepted", + "Remove this acceptance. Declare production and fix the setting, or leave the development warning in place.", + ) + }) + .collect(); + report.extend(decoded.document.report_with(refused)); + let mut value = decoded.value; + value + .acceptances + .retain(|acceptance| !crate::posture::is_posture_code(&acceptance.code)); + Some(value) } Err(errors) => { report.extend(errors); diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 7fc2a9e14f..79d904ad85 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -14,6 +14,9 @@ mod loader; mod metrics_bind; mod offline; pub mod package; +mod posture; +#[cfg(test)] +mod posture_load_tests; #[cfg(feature = "schema")] pub mod schema; mod secrets; @@ -23,13 +26,15 @@ use sha2::{Digest, Sha256}; #[cfg(feature = "schema")] pub use blocks::url_hook_destinations_schema; pub use blocks::{ - describe_secret_failure, is_sha256_label, url_hook_destinations, AttachmentVerifierConfig, - AttemptTimeoutMilliseconds, AuditKeyConfig, ConfigBlockError, ConfigBlockErrorKind, - DatabaseConfig, EnvironmentSecretProviderConfig, FileSecretProviderConfig, JwksSource, - ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, PackageDigestMismatch, - PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, TlsTermination, - UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, + describe_secret_failure, is_sha256_label, url_hook_destinations, AdmittedClients, + AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, AuditKeyCustody, + ConfigBlockError, ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseTransport, + DatabaseTransportError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, + PackageDigestMismatch, PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, + TlsTermination, UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_MAXIMUM_ATTEMPTS, DEFAULT_TASK_GRANT_STATUS_PATH, DEFAULT_TASK_GRANT_STATUS_SCOPE, MAX_ASSERTION_ISSUERS_PER_CLIENT, MAX_ASSERTION_ISSUER_BYTES, MAX_ASSERTION_ISSUER_CLIENTS, @@ -54,8 +59,15 @@ pub use package::{ plan_package, verify_package, write_package, write_sum_file, PackageError, PackageErrorKind, PackageLimits, VerifiedPackage, REVISION_FILE, SUM_FILE, }; +pub use posture::{ + collect_development_settings, declared, declared_from, DeclaredPosture, DevelopmentClass, + DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitProductionSetting, + FoundExplicitSetting, FoundSetting, Gated, Posture, PostureError, PostureReport, PostureSource, + SettingOrigin, DEVELOPMENT, POSTURE_ENV, +}; pub use secrets::{ - ProtectedSecret, SecretError, SecretProvider, SecretReference, SecretResolver, MAX_SECRET_BYTES, + ProtectedSecret, SecretError, SecretFileCheck, SecretProvider, SecretReference, SecretResolver, + MAX_SECRET_BYTES, MAX_SECRET_LINKS, }; fn resolve_config_env_expression( diff --git a/crates/registry-platform-config/src/loader.rs b/crates/registry-platform-config/src/loader.rs index c34927e175..7951da5317 100644 --- a/crates/registry-platform-config/src/loader.rs +++ b/crates/registry-platform-config/src/loader.rs @@ -45,6 +45,10 @@ use registry_platform_yaml::{ }; use serde::de::DeserializeOwned; +use crate::posture::{ + collect_development_settings, DeclaredPosture, DevelopmentWitness, Posture, PostureReport, + PostureSource, +}; use crate::{resolve_config_env_expression, sha256_uri}; /// The default size cap for a runtime configuration document. @@ -163,6 +167,17 @@ impl RuntimeConfigError { .in_file(file) } + /// A refusal that carries `diagnostics`, in `file`. + pub(crate) fn from_diagnostics(file: &Path, diagnostics: Vec) -> Self { + Self::from_report(Report::new(diagnostics)).in_file(file) + } + + /// This refusal with `diagnostics` listed after its own. + pub(crate) fn with_diagnostics(mut self, diagnostics: Vec) -> Self { + self.detail.diagnostics.extend(diagnostics); + self + } + fn from_report(report: Report) -> Self { let diagnostics = report.into_diagnostics(); assert!( @@ -276,6 +291,13 @@ pub struct LoadedRuntimeConfig { /// spelling of an environment expression that resolved to the same value /// carry the same digest. pub effective_digest: String, + /// The declared posture and every development-only setting the document + /// holds. A loader made without a posture reports production and records + /// no setting. + pub posture: PostureReport, + /// Proof that the process declared development: `Some` only then, and + /// the only way to read a value that selects a development-only setting. + pub development: Option, } impl std::fmt::Debug for LoadedRuntimeConfig { @@ -308,16 +330,48 @@ pub struct RuntimeConfigLoader { removed_keys: &'static [RemovedKey], retired_api_versions: &'static [RetiredApiVersion<'static>], trusted_ownership: bool, + /// The posture the process declared. `None` for a loader made without a + /// posture, which refuses and records no development-only setting. + posture: Option, +} + +/// What a parse does with the development-only settings it found. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Decision { + /// Refuse the document when the posture is production and it holds one. + Refuse, + /// Return the document and the settings, for a check that reports them. + Report, } impl RuntimeConfigLoader { + /// A loader for a process that declared `declared`. A document that + /// holds a development-only setting is refused in production, with every + /// such setting listed beside any other problem, and accepted in + /// development, which also yields the witness that reads those settings. + #[must_use] + pub const fn new(envelope: RuntimeEnvelope, declared: DeclaredPosture) -> Self { + Self { + envelope, + removed_keys: &[], + retired_api_versions: &[], + trusted_ownership: false, + posture: Some(declared), + } + } + + /// A loader that declares no posture. It reports production, never + /// issues the witness, and neither refuses nor records a development-only + /// setting: a runtime that has not adopted the posture keeps the + /// behaviour it had. #[must_use] - pub const fn new(envelope: RuntimeEnvelope) -> Self { + pub const fn new_without_posture(envelope: RuntimeEnvelope) -> Self { Self { envelope, removed_keys: &[], retired_api_versions: &[], trusted_ownership: false, + posture: None, } } @@ -372,7 +426,7 @@ impl RuntimeConfigLoader { lookup: impl Fn(&str) -> Option, ) -> Result, RuntimeConfigError> { let bytes = self.read_file(path)?; - self.parse_file(path, &bytes, &lookup) + self.parse_file(path, &bytes, &lookup, Decision::Refuse) } /// The bytes of the file at `path`, read under the file rules: the one @@ -387,9 +441,15 @@ impl RuntimeConfigLoader { path: &Path, bytes: &[u8], lookup: &dyn Fn(&str) -> Option, + decision: Decision, ) -> Result, RuntimeConfigError> { - self.parse(&path.display().to_string(), bytes, Fill::Variables(lookup)) - .map_err(|error| error.in_file(path)) + self.parse( + &path.display().to_string(), + bytes, + Fill::Variables(lookup), + decision, + ) + .map_err(|error| error.in_file(path)) } /// Apply every rule after the file read to the `bytes` read from `path`, @@ -400,9 +460,15 @@ impl RuntimeConfigLoader { path: &Path, bytes: &[u8], stand_in: &dyn Fn(&str) -> String, + decision: Decision, ) -> Result, RuntimeConfigError> { - self.parse(&path.display().to_string(), bytes, Fill::StandIns(stand_in)) - .map_err(|error| error.in_file(path)) + self.parse( + &path.display().to_string(), + bytes, + Fill::StandIns(stand_in), + decision, + ) + .map_err(|error| error.in_file(path)) } /// Apply every rule after the file read to `text`. Used by authoring tools @@ -413,15 +479,70 @@ impl RuntimeConfigLoader { text: &str, lookup: impl Fn(&str) -> Option, ) -> Result, RuntimeConfigError> { - self.parse(BUFFER_NAME, text.as_bytes(), Fill::Variables(&lookup)) + self.parse( + BUFFER_NAME, + text.as_bytes(), + Fill::Variables(&lookup), + Decision::Refuse, + ) } + /// Decode the document, then settle the posture: collect the + /// development-only settings the decode finds, and under + /// [`Decision::Refuse`] refuse them in production. fn parse( &self, file: &str, bytes: &[u8], fill: Fill<'_>, + decision: Decision, ) -> Result, RuntimeConfigError> { + let Some(declared) = self.posture else { + let (config, effective_digest) = self.decode::(file, bytes, fill)?; + return Ok(LoadedRuntimeConfig { + config, + effective_digest, + posture: PostureReport::new(DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }), + development: None, + }); + }; + let (decoded, found) = collect_development_settings(|| self.decode::(file, bytes, fill)); + let mut posture = PostureReport::new(declared); + for setting in found { + posture.record(setting); + } + let named = Path::new(file); + match decoded { + Ok((config, effective_digest)) => { + if decision == Decision::Refuse { + posture.decide(named)?; + } + Ok(LoadedRuntimeConfig { + config, + effective_digest, + posture, + development: (declared.posture == Posture::Development) + .then(DevelopmentWitness::issue), + }) + } + // The settings found before the failure are still reported, so + // one run lists every problem (CFG-DIAG-5). + Err(error) => Err(match decision { + Decision::Refuse if declared.posture == Posture::Development => error, + _ => error.with_diagnostics(posture.diagnostics(named)), + }), + } + } + + fn decode( + &self, + file: &str, + bytes: &[u8], + fill: Fill<'_>, + ) -> Result<(T, String), RuntimeConfigError> { let removed: Vec<(String, String)> = self .removed_keys .iter() @@ -457,10 +578,7 @@ impl RuntimeConfigLoader { "Write every number as a plain decimal within the range JSON can carry.", ) })?; - Ok(LoadedRuntimeConfig { - config: decoded.value, - effective_digest: sha256_uri(&canonical), - }) + Ok((decoded.value, sha256_uri(&canonical))) } fn read(&self, path: &Path) -> Result, RuntimeConfigError> { diff --git a/crates/registry-platform-config/src/loader_tests.rs b/crates/registry-platform-config/src/loader_tests.rs index 4a1091706b..67ac3f7b18 100644 --- a/crates/registry-platform-config/src/loader_tests.rs +++ b/crates/registry-platform-config/src/loader_tests.rs @@ -64,7 +64,7 @@ struct Audit { } fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(ENVELOPE).removed_keys(REMOVED) + RuntimeConfigLoader::new_without_posture(ENVELOPE).removed_keys(REMOVED) } fn header() -> String { @@ -1094,7 +1094,7 @@ mod files { #[test] fn the_shared_removed_jwks_uri_key_names_jwks_source() { - let loader = RuntimeConfigLoader::new(ENVELOPE) + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE) .removed_keys(std::slice::from_ref(&REMOVED_OIDC_JWKS_URI)); let error = loader .parse_str::( @@ -1119,7 +1119,7 @@ fn the_shared_removed_jwks_uri_key_names_jwks_source() { #[test] fn the_shared_removed_jwks_source_kind_key_names_type() { - let loader = RuntimeConfigLoader::new(ENVELOPE) + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE) .removed_keys(std::slice::from_ref(&REMOVED_OIDC_JWKS_SOURCE_KIND)); let error = loader .parse_str::( diff --git a/crates/registry-platform-config/src/offline.rs b/crates/registry-platform-config/src/offline.rs index 6cfc0aa51d..a350c2d35f 100644 --- a/crates/registry-platform-config/src/offline.rs +++ b/crates/registry-platform-config/src/offline.rs @@ -12,6 +12,7 @@ use registry_platform_yaml::{ }; use serde::de::DeserializeOwned; +use crate::loader::Decision; use crate::{ contains_environment_expression, LoadedRuntimeConfig, RuntimeConfigLoader, UNAVAILABLE_CODE, }; @@ -32,7 +33,10 @@ pub struct RuntimeFileCheck { /// Every loader finding, each naming the file as the path was given. A /// finding that depends on the value of a deferred expression is left /// out; in its place stands a warning, coded [`INCOMPLETE_CODE`], that - /// the check stopped at that member. + /// the check stopped at that member. Under a declared posture, each + /// development-only setting the file holds is one finding: an error in + /// production and a warning in development, with the same code. The + /// file is still decoded, so the product's own checks run beside them. pub diagnostics: Vec, /// The file could not be read at all, as opposed to read and refused. pub unavailable: bool, @@ -224,6 +228,9 @@ impl RuntimeConfigLoader { /// repeat. A member that refuses its stand-in stops the decode: the check /// then reports a warning at that member, coded [`INCOMPLETE_CODE`], for /// the members it did not read. + /// + /// The posture is the loader's: a loader made without a posture reports + /// no development-only setting. pub fn check_offline( &self, path: &Path, @@ -241,15 +248,26 @@ impl RuntimeConfigLoader { }; let loaded = bytes.and_then(|bytes| { if substitute { - self.parse_file::(path, &bytes, &|name| std::env::var(name).ok()) + self.parse_file::( + path, + &bytes, + &|name| std::env::var(name).ok(), + Decision::Report, + ) } else { - self.parse_file_with_stand_ins::(path, &bytes, &|pointer| { - deferred.stand_in(pointer).to_owned() - }) + self.parse_file_with_stand_ins::( + path, + &bytes, + &|pointer| deferred.stand_in(pointer).to_owned(), + Decision::Report, + ) } }); let (loaded, diagnostics, unavailable) = match loaded { - Ok(loaded) => (Some(loaded), Vec::new(), false), + Ok(loaded) => { + let found = loaded.posture.diagnostics(path); + (Some(loaded), found, false) + } Err(error) => ( None, error @@ -413,7 +431,7 @@ mod tests { use serde::Deserialize; use std::fs; - const LOADER: RuntimeConfigLoader = RuntimeConfigLoader::new(RuntimeEnvelope { + const LOADER: RuntimeConfigLoader = RuntimeConfigLoader::new_without_posture(RuntimeEnvelope { api_version: "registry.registrystack.org/example-runtime/v1alpha1", kind: "ExampleRuntimeConfig", }); diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs new file mode 100644 index 0000000000..5b453ddba4 --- /dev/null +++ b/crates/registry-platform-config/src/posture.rs @@ -0,0 +1,538 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Development-only configuration values and the one decision about them. +//! +//! A configuration type that has values only a development process may use +//! implements [`DevelopmentClass`], and the member that holds it is a +//! [`Gated`]. Decoding a `Gated` never fails because of the posture: it records +//! what it found, and [`PostureReport::decide`] is the single place where +//! production refuses and development accepts and lists. A development value +//! is readable only with the [`DevelopmentWitness`] the loader issues to a +//! process that declared development. +//! +//! # A witness cannot be made outside this crate +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = DevelopmentWitness { _sealed: () }; +//! ``` +//! +//! The compiling twin names the type and nothing else: +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! fn takes(_: Option<&DevelopmentWitness>) {} +//! takes(None); +//! ``` +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = DevelopmentWitness::default(); +//! ``` +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! let _: Option = None; +//! ``` +//! +//! ```compile_fail +//! use registry_platform_config::DevelopmentWitness; +//! let _ = serde_json::from_str::("null"); +//! ``` +//! +//! ``` +//! use registry_platform_config::DevelopmentWitness; +//! let _ = serde_json::from_str::>("null"); +//! let _: Option = None; +//! ``` +//! +//! # A gated value has no way out but `get` +//! +//! ```compile_fail +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! let _ = g.0; +//! ``` +//! +//! ```compile_fail +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! let _ = &*g; +//! ``` +//! +//! The compiling twin reads the same value through `get`: +//! +//! ``` +//! # use registry_platform_config::{DevelopmentClass, DevelopmentSetting, Gated}; +//! # enum Transport { Tls, Plaintext } +//! # static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { +//! # code: "platform.posture.example", key: "transport", summary: "s", production: "p", +//! # }; +//! # impl DevelopmentClass for Transport { +//! # const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; +//! # fn development_setting(&self) -> Option<&'static DevelopmentSetting> { +//! # match self { Transport::Tls => None, Transport::Plaintext => Some(&PLAINTEXT) } +//! # } +//! # } +//! let g = Gated::everywhere(Transport::Tls).unwrap(); +//! assert!(matches!(g.get(None), Ok(Transport::Tls))); +//! let _ = Transport::Plaintext; +//! ``` + +use std::cell::RefCell; +use std::fmt; +use std::marker::PhantomData; +use std::path::Path; + +use registry_platform_posture::POSTURE_FLAG; +use registry_platform_yaml::{ + escape_pointer_segment, gated_site, Diagnostic, Position, Severity, Source, DEVELOPMENT_ONLY, +}; +use serde::de::{Deserializer, Visitor}; +use serde::{Deserialize, Serialize, Serializer}; +use serde_json::{Map, Value}; + +pub use registry_platform_posture::{ + declared, declared_from, DeclaredPosture, Posture, PostureError, PostureSource, DEVELOPMENT, + POSTURE_ENV, +}; + +use crate::RuntimeConfigError; + +/// Proof that this process declared development. Only the loader creates it. +#[derive(Clone, Copy, Debug)] +pub struct DevelopmentWitness { + _sealed: (), +} + +impl DevelopmentWitness { + /// The loader issues the witness to a process that declared development. + pub(crate) const fn issue() -> Self { + Self { _sealed: () } + } +} + +/// One development-only setting, described by the crate that owns it. +#[derive(Debug, PartialEq, Eq)] +pub struct DevelopmentSetting { + /// `.posture.` (CFG-DIAG-3). + pub code: &'static str, + /// The authored key that holds the value: the last pointer segment. + pub key: &'static str, + /// Value-free: what the setting weakens. + pub summary: &'static str, + /// What to write for production. + pub production: &'static str, +} + +/// A configuration type that has development-only values. +pub trait DevelopmentClass { + /// Every setting a value of this type can select. Docs, schemas and tests + /// read it. + const SETTINGS: &'static [&'static DevelopmentSetting]; + + /// The setting this value selects, or `None` when it is valid in every + /// posture. Implement it with an exhaustive `match`, so a new variant + /// forces a decision. + fn development_setting(&self) -> Option<&'static DevelopmentSetting>; +} + +/// The refusal to read a development-only value without a witness. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("the setting {} is accepted only when the process declares development", .setting.code)] +pub struct DevelopmentOnlyRefused { + pub setting: &'static DevelopmentSetting, +} + +/// A value that may select a development-only setting. Read it with +/// [`Gated::get`]. +/// +/// There is no `Deref` and no way to take the value out: a value that selects +/// a development-only setting is unreadable without a [`DevelopmentWitness`]. +#[derive(Clone, PartialEq, Eq)] +pub struct Gated(T); + +impl Gated { + /// Hold `value`, whatever it selects. Shared blocks use it for the value + /// an omitted member stands for. + pub(crate) const fn wrap(value: T) -> Self { + Self(value) + } +} + +impl Gated { + /// The value, whatever it selects, for a shared block that decodes a + /// member through the gate so the loader records it, and keeps the member + /// readable by products that have not adopted the posture. + pub(crate) fn into_inner(self) -> T { + self.0 + } +} + +impl Gated { + /// The value, when it is valid in every posture or the caller holds the + /// witness. + pub fn get(&self, witness: Option<&DevelopmentWitness>) -> Result<&T, DevelopmentOnlyRefused> { + match (self.0.development_setting(), witness) { + (Some(setting), None) => Err(DevelopmentOnlyRefused { setting }), + _ => Ok(&self.0), + } + } + + /// The setting the value selects, or `None` when it is valid in every + /// posture. + pub fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.development_setting() + } + + /// A value that is valid in every posture, for code that writes + /// configuration. + pub fn everywhere(value: T) -> Result { + match value.development_setting() { + Some(setting) => Err(DevelopmentOnlyRefused { setting }), + None => Ok(Self(value)), + } + } + + /// A value of any kind, for tests that exercise a development path. + #[cfg(any(test, feature = "test-support"))] + pub fn for_tests(value: T) -> Self { + Self(value) + } +} + +impl fmt::Debug for Gated { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, formatter) + } +} + +impl Serialize for Gated { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de, T: DevelopmentClass + Deserialize<'de>> Deserialize<'de> for Gated { + fn deserialize>(deserializer: D) -> Result { + struct Reads(PhantomData); + impl<'de, T: DevelopmentClass + Deserialize<'de>> Visitor<'de> for Reads { + type Value = Gated; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a configuration value") + } + + fn visit_newtype_struct>( + self, + inner: D, + ) -> Result, D::Error> { + let site = gated_site(); + let value = T::deserialize(inner)?; + if let Some(setting) = value.development_setting() { + let (pointer, position) = match site { + Some(site) if site.exact => (Some(site.pointer), site.position), + // A flattened member is one of the holding mapping's own keys. + Some(site) => ( + Some(format!( + "{}/{}", + site.pointer, + escape_pointer_segment(setting.key) + )), + site.position, + ), + None => (None, None), + }; + record(FoundSetting { + setting, + pointer, + position, + origin: SettingOrigin::RuntimeFile, + }); + } + Ok(Gated(value)) + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Reads(PhantomData)) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for Gated { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> std::borrow::Cow<'static, str> { + T::schema_name() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let mut schema = generator.subschema_for::(); + let codes: Vec<&str> = T::SETTINGS.iter().map(|setting| setting.code).collect(); + schema.insert("x-registry-development-only".to_owned(), codes.into()); + schema + } +} + +/// Where a recorded setting was found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SettingOrigin { + RuntimeFile, + Package, + Combination, +} + +/// A development-only setting found in a process's configuration. +#[derive(Clone, Debug)] +pub struct FoundSetting { + pub setting: &'static DevelopmentSetting, + pub pointer: Option, + pub position: Option, + pub origin: SettingOrigin, +} + +/// A setting valid in every posture that an operator states deliberately and +/// that relaxes something. It never refuses and is never a diagnostic: the +/// startup log and `check` say it is in use, and `/ready`, which answers +/// without credentials, does not list it. +#[derive(Debug, PartialEq, Eq)] +pub struct ExplicitProductionSetting { + /// `.posture.` (CFG-DIAG-3), distinct from every + /// development code. + pub code: &'static str, + /// The authored key, the last pointer segment. + pub key: &'static str, + /// Value-free: what it relaxes and why the operator states it. + pub summary: &'static str, +} + +/// An [`ExplicitProductionSetting`] found in a process's configuration. +#[derive(Clone, Debug)] +pub struct FoundExplicitSetting { + pub setting: &'static ExplicitProductionSetting, + pub pointer: Option, + pub position: Option, + pub origin: SettingOrigin, +} + +/// Run `decode` and return what it returned with every development-only +/// setting a [`Gated`] recorded while it ran. Calls nest: an inner call keeps +/// its own findings and restores the outer collector, also on a panic. +pub fn collect_development_settings(decode: impl FnOnce() -> R) -> (R, Vec) { + let guard = CollectorGuard { + previous: COLLECTOR.with(|collector| collector.borrow_mut().replace(Vec::new())), + }; + let result = decode(); + let found = COLLECTOR + .with(|collector| collector.borrow_mut().take()) + .unwrap_or_default(); + drop(guard); + (result, found) +} + +thread_local! { + static COLLECTOR: RefCell>> = const { RefCell::new(None) }; +} + +/// Restores the collector that was installed before this one, also on a panic. +struct CollectorGuard { + previous: Option>, +} + +impl Drop for CollectorGuard { + fn drop(&mut self) { + COLLECTOR.with(|collector| *collector.borrow_mut() = self.previous.take()); + } +} + +/// Add `found` to the active collector. Outside a collector nothing is +/// recorded, and a development value stays unreadable without a witness. +fn record(found: FoundSetting) { + COLLECTOR.with(|collector| { + if let Some(found_so_far) = collector.borrow_mut().as_mut() { + found_so_far.push(found); + } + }); +} + +/// The posture a process declared and every setting found under it. +#[derive(Clone, Debug)] +pub struct PostureReport { + declared: DeclaredPosture, + settings: Vec, + explicit: Vec, +} + +impl PostureReport { + #[must_use] + pub fn new(declared: DeclaredPosture) -> Self { + Self { + declared, + settings: Vec::new(), + explicit: Vec::new(), + } + } + + pub fn record(&mut self, found: FoundSetting) { + self.settings.push(found); + } + + pub fn record_explicit(&mut self, found: FoundExplicitSetting) { + self.explicit.push(found); + } + + #[must_use] + pub fn posture(&self) -> Posture { + self.declared.posture + } + + #[must_use] + pub fn settings(&self) -> &[FoundSetting] { + &self.settings + } + + #[must_use] + pub fn explicit_settings(&self) -> &[FoundExplicitSetting] { + &self.explicit + } + + /// The one decision. Production refuses every recorded setting and + /// development accepts and lists them, under the same codes. + #[must_use] + pub fn diagnostics(&self, file: &Path) -> Vec { + let production = self.posture() == Posture::Production; + self.settings + .iter() + .map(|found| { + let setting = found.setting; + let pointer = found.pointer.as_deref().unwrap_or(""); + let (message, action) = if production { + ( + format!( + "{}; it is accepted only when the process declares development", + setting.summary + ), + format!( + "{} For a laptop or test run, start it with `rstack dev`, or declare development with {POSTURE_ENV}={DEVELOPMENT} or --{POSTURE_FLAG} {DEVELOPMENT}.", + setting.production + ), + ) + } else { + ( + format!("{}; production refuses it", setting.summary), + setting.production.to_owned(), + ) + }; + let mut diagnostic = if production { + Diagnostic::error(setting.code, pointer, message, action) + } else { + Diagnostic::warning(setting.code, pointer, message, action) + }; + diagnostic.source = Some(Source { + file: file.display().to_string(), + line: found.position.map(|position| position.line), + column: found.position.map(|position| position.column), + }); + diagnostic + }) + .collect() + } + + /// `Err` exactly when [`PostureReport::diagnostics`] holds an error. + pub fn decide(&self, file: &Path) -> Result<(), RuntimeConfigError> { + let diagnostics = self.diagnostics(file); + if diagnostics + .iter() + .any(|diagnostic| diagnostic.severity == Severity::Error) + { + return Err(RuntimeConfigError::from_diagnostics(file, diagnostics)); + } + Ok(()) + } + + /// The members a runtime adds to its `/ready` body: the posture and the + /// development settings. Explicit production settings are left out, since + /// `/ready` answers without credentials. + #[must_use] + pub fn ready_member(&self) -> Map { + let listed = |code: &str, pointer: &Option| { + let mut member = Map::new(); + member.insert("code".to_owned(), Value::from(code)); + if let Some(pointer) = pointer { + member.insert("pointer".to_owned(), Value::from(pointer.as_str())); + } + Value::Object(member) + }; + let mut members = Map::new(); + members.insert("posture".to_owned(), Value::from(self.posture().as_str())); + members.insert( + "developmentSettings".to_owned(), + self.settings + .iter() + .map(|found| listed(found.setting.code, &found.pointer)) + .collect(), + ); + members + } + + /// Log the declared posture and what is in use. + pub fn log_startup(&self) { + let source = match self.declared.source { + PostureSource::Flag => "flag", + PostureSource::Environment => "environment", + PostureSource::Default => "default", + }; + tracing::info!( + posture = self.posture().as_str(), + posture_source = source, + development_settings = self.settings.len(), + explicit_production_settings = self.explicit.len(), + "posture declared" + ); + if self.posture() == Posture::Development { + for found in &self.settings { + tracing::warn!( + error_code = found.setting.code, + pointer = found.pointer.as_deref().unwrap_or(""), + "development-only setting in use; production refuses it" + ); + } + } + for found in &self.explicit { + tracing::info!( + setting_code = found.setting.code, + pointer = found.pointer.as_deref().unwrap_or(""), + "explicit production setting in use" + ); + } + } +} + +/// Whether `code` is a posture code: `.posture.`. +pub(crate) fn is_posture_code(code: &str) -> bool { + code.split('.').nth(1) == Some("posture") +} + +#[cfg(test)] +#[path = "posture_tests.rs"] +mod tests; diff --git a/crates/registry-platform-config/src/posture_load_tests.rs b/crates/registry-platform-config/src/posture_load_tests.rs new file mode 100644 index 0000000000..ef21e0bc68 --- /dev/null +++ b/crates/registry-platform-config/src/posture_load_tests.rs @@ -0,0 +1,625 @@ +//! The loader and the offline check under a declared posture, with the shared +//! blocks that hold development-only settings. + +use std::fs; +use std::net::{IpAddr, Ipv4Addr}; +use std::path::PathBuf; + +use registry_platform_yaml::Severity; +use serde::Deserialize; + +use crate::blocks::{ + plaintext_permitted_with, AuditKeyConfig, AuditKeyCustody, DatabaseConfig, DatabaseHost, + DatabaseTransport, DatabaseTransportError, JwksSource, OidcIssuerConfig, +}; +use crate::{ + DeclaredPosture, Gated, Posture, PostureSource, RuntimeConfigLoader, RuntimeEnvelope, + DEFAULT_STAND_IN, +}; + +const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { + api_version: "registry.registrystack.org/example-runtime/v1alpha1", + kind: "ExampleRuntimeConfig", +}; + +const HEAD: &str = + "apiVersion: registry.registrystack.org/example-runtime/v1alpha1\nkind: ExampleRuntimeConfig\n"; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[allow(dead_code)] +struct Example { + database: DatabaseConfig, + authentication: Authentication, + audit: Audit, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Authentication { + oidc: Oidc, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Oidc { + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/oidc-issuer"))] + provider: OidcIssuerConfig, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[allow(dead_code)] +struct Audit { + path: String, + #[serde(rename(deserialize = "registry-platform-yaml/shared-block/audit-key"))] + key: AuditKeyConfig, +} + +const SHARED_CODES: [&str; 3] = [ + "platform.posture.database-private-plaintext", + "platform.posture.insecure-issuer-http", + "platform.posture.generated-audit-key", +]; + +const SHARED_POINTERS: [&str; 3] = [ + "/database/transport", + "/authentication/oidc/allowInsecureHttp", + "/audit/hashKeyCustody", +]; + +/// A file holding every development-only setting the shared blocks have. +fn every_setting() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\n transport: private-network-plaintext\nauthentication:\n oidc:\n issuer: http://issuer.example.test\n audience: api\n allowInsecureHttp: true\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n hashKeyCustody: development-generated\n" + ) +} + +/// The same file with every setting at a value valid in every posture. +fn no_setting() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\n transport: verified-tls\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: api\n allowInsecureHttp: false\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n hashKeyCustody: operator-provisioned\n" + ) +} + +fn declared(posture: Posture) -> DeclaredPosture { + DeclaredPosture { + posture, + source: PostureSource::Flag, + } +} + +fn parse( + loader: &RuntimeConfigLoader, + text: &str, +) -> Result, crate::RuntimeConfigError> { + loader.parse_str::(text, |_| None) +} + +#[test] +fn production_refuses_every_shared_development_setting_and_lists_each_with_its_pointer() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let error = parse(&loader, &every_setting()).expect_err("production refuses"); + let diagnostics = error.diagnostics(); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == *code) + .unwrap_or_else(|| panic!("{code} is listed: {diagnostics:?}")); + assert_eq!(found.path, pointer, "{code}"); + assert_eq!(found.severity, Severity::Error, "{code}"); + assert!(found.source.as_ref().unwrap().line.is_some(), "{code}"); + } + assert_eq!(diagnostics.len(), 3, "{diagnostics:?}"); +} + +#[test] +fn a_decode_failure_and_the_settings_found_before_it_are_reported_together() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let text = every_setting().replace("audience: api\n", "audience: api\n unknown: 1\n"); + let error = parse(&loader, &text).expect_err("production refuses"); + let codes: Vec<&str> = error + .diagnostics() + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert!(codes.contains(&"config.unknown-key"), "{codes:?}"); + assert!( + codes.contains(&"platform.posture.database-private-plaintext"), + "{codes:?}" + ); +} + +#[test] +fn development_admits_the_settings_lists_them_and_yields_a_witness() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let loaded = parse(&loader, &every_setting()).expect("development admits"); + assert_eq!(loaded.posture.posture(), Posture::Development); + let witness = loaded.development.as_ref().expect("a witness"); + let listed: Vec<(&str, Option<&str>)> = loaded + .posture + .settings() + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + assert!( + listed.contains(&(*code, Some(pointer))), + "{code}: {listed:?}" + ); + } + assert_eq!(listed.len(), 3); + let warnings = loaded + .posture + .diagnostics(PathBuf::from("runtime.yaml").as_path()); + assert!(warnings + .iter() + .all(|diagnostic| diagnostic.severity == Severity::Warning)); + loaded + .posture + .decide(PathBuf::from("runtime.yaml").as_path()) + .unwrap(); + + let database = &loaded.config.database; + let transport = database.transport.as_ref().expect("written"); + assert_eq!( + transport.get(Some(witness)).unwrap(), + &DatabaseTransport::PrivateNetworkPlaintext + ); + assert!(transport.get(None).is_err()); + assert_eq!( + loaded + .config + .audit + .key + .hash_key_custody + .get(Some(witness)) + .unwrap(), + &AuditKeyCustody::DevelopmentGenerated + ); +} + +#[test] +fn a_file_with_no_development_setting_loads_the_same_in_both_postures_and_only_development_holds_a_witness( +) { + for posture in [Posture::Production, Posture::Development] { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(posture)); + let loaded = parse(&loader, &no_setting()).expect("valid in every posture"); + assert!(loaded.posture.settings().is_empty(), "{posture:?}"); + assert_eq!( + loaded.development.is_some(), + posture == Posture::Development, + "{posture:?}" + ); + } + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + assert!(parse(&loader, &every_setting()).is_err()); +} + +#[test] +fn an_omitted_custody_is_operator_provisioned_and_an_omitted_transport_is_verified_tls() { + let text = no_setting() + .replace(" transport: verified-tls\n", "") + .replace(" hashKeyCustody: operator-provisioned\n", "") + .replace(" allowInsecureHttp: false\n", ""); + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let loaded = parse(&loader, &text).expect("valid"); + assert!(loaded.posture.settings().is_empty()); + assert!(loaded.config.database.transport.is_none()); + assert_eq!( + loaded.config.audit.key.hash_key_custody.get(None).unwrap(), + &AuditKeyCustody::OperatorProvisioned + ); + assert_eq!( + serde_json::to_value(&loaded.config.audit.key).unwrap(), + serde_json::json!({"hashKeyRef": "secret:env/AUDIT_KEY"}), + "an omitted custody is not written back" + ); +} + +#[test] +fn the_entry_point_without_a_posture_admits_what_it_always_admitted_and_reports_production() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let loaded = parse(&loader, &every_setting()).expect("admitted, as before"); + assert_eq!(loaded.posture.posture(), Posture::Production); + assert!(loaded.posture.settings().is_empty()); + assert!(loaded.development.is_none()); + assert!( + loaded + .config + .authentication + .oidc + .provider + .allow_insecure_http + ); +} + +fn check_file(loader: &RuntimeConfigLoader, text: &str) -> crate::RuntimeFileCheck { + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let path = directory.path().join("runtime.yaml"); + fs::write(&path, text).unwrap(); + loader.check_offline::(&path, true, |_| DEFAULT_STAND_IN) +} + +#[test] +fn the_offline_check_in_production_decodes_the_file_and_reports_each_setting_as_an_error() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some(), "product checks still run"); + assert_eq!(check.diagnostics.len(), 3, "{:?}", check.diagnostics); + for (code, pointer) in SHARED_CODES.iter().zip(SHARED_POINTERS) { + let found = check + .diagnostics + .iter() + .find(|diagnostic| diagnostic.code == *code) + .unwrap_or_else(|| panic!("{code}: {:?}", check.diagnostics)); + assert_eq!(found.path, pointer); + assert_eq!(found.severity, Severity::Error); + } + let report = check.report_with("example", Vec::new()); + assert_eq!(report.diagnostics().len(), 3); +} + +#[test] +fn the_offline_check_in_development_reports_the_same_codes_as_warnings() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some()); + let codes: Vec<&str> = check + .diagnostics + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert_eq!(codes.len(), 3, "{codes:?}"); + for code in SHARED_CODES { + assert!(codes.contains(&code), "{code}: {codes:?}"); + } + assert!(check + .diagnostics + .iter() + .all(|diagnostic| diagnostic.severity == Severity::Warning)); +} + +#[test] +fn the_offline_check_without_a_posture_adds_nothing() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let check = check_file(&loader, &every_setting()); + assert!(check.loaded.is_some()); + assert!(check.diagnostics.is_empty(), "{:?}", check.diagnostics); +} + +#[test] +fn a_decode_failure_in_a_check_carries_the_settings_found_before_it() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let text = every_setting().replace("audience: api\n", "audience: api\n unknown: 1\n"); + let check = check_file(&loader, &text); + assert!(check.loaded.is_none()); + let codes: Vec<&str> = check + .diagnostics + .iter() + .map(|diagnostic| diagnostic.code.as_str()) + .collect(); + assert!(codes.contains(&"config.unknown-key"), "{codes:?}"); + assert!( + codes.contains(&"platform.posture.database-private-plaintext"), + "{codes:?}" + ); +} + +// The issuer check + +/// One shared block read alone, through the shared reader. +fn read_block(text: &str) -> T { + use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader}; + const BLOCK: FormatSpec = FormatSpec { + kind: "SharedRuntimeBlock", + envelope: EnvelopeRule::Exempt { + reason: "a shared runtime block read alone by its unit tests", + }, + removed_keys: &[], + }; + Reader::new("block.yaml") + .decode::(text.as_bytes(), &Expect::one(&BLOCK)) + .expect("the block decodes") + .value +} + +fn issuer(address: &str, allow_insecure_http: bool) -> OidcIssuerConfig { + read_block(&format!( + "issuer: {address}\naudience: api\nallowInsecureHttp: {allow_insecure_http}\n" + )) +} + +#[test] +fn a_loopback_http_issuer_needs_no_setting_and_a_remote_one_needs_the_development_flag() { + for loopback in [ + "http://127.0.0.1:8082", + "http://localhost:8082", + "http://[::1]:8082", + ] { + issuer(loopback, false) + .check("authentication.oidc") + .unwrap_or_else(|error| panic!("{loopback}: {error}")); + } + issuer("http://issuer.example.test", false) + .check("authentication.oidc") + .expect_err("remote plain http is refused without the flag"); + issuer("http://issuer.example.test", true) + .check("authentication.oidc") + .expect("the flag admits it; the posture decision refuses it in production"); + issuer("https://issuer.example.test", false) + .check("authentication.oidc") + .expect("https"); +} + +#[test] +fn the_check_without_a_posture_keeps_the_loopback_argument() { + let loopback = issuer("http://127.0.0.1:8082", false); + loopback + .check_without_posture("authentication.oidc", true) + .expect("admitted when asked"); + loopback + .check_without_posture("authentication.oidc", false) + .expect_err("refused when not asked"); +} + +// Database transport + +fn database(transport: Option<&str>, test_only_plaintext: bool) -> DatabaseConfig { + let mut text = String::from( + "runtimeUrlRef: secret:env/DB_RUNTIME\nmigrationUrlRef: secret:env/DB_MIGRATION\n", + ); + if let Some(transport) = transport { + text.push_str(&format!("transport: {transport}\n")); + } + if test_only_plaintext { + text.push_str("testOnlyPlaintext: true\n"); + } + read_block(&text) +} + +fn resolve(name: &str) -> std::io::Result> { + match name { + "db.internal" => Ok(vec![IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3))]), + "db.mixed" => Ok(vec![ + IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), + IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)), + ]), + "db.example.com" => Ok(vec![IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34))]), + _ => Err(std::io::Error::other("no such name")), + } +} + +fn tcp(host: &str) -> Vec { + vec![DatabaseHost::Tcp(host.to_owned())] +} + +#[test] +fn plaintext_permitted_answers_each_host_for_each_transport() { + use DatabaseTransport::{LoopbackPlaintext, PrivateNetworkPlaintext, VerifiedTls}; + let witness_holder = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)) + .parse_str::(&every_setting(), |_| None) + .unwrap(); + let witness = witness_holder.development.as_ref(); + + let hosts: Vec<(&str, Vec)> = vec![ + ("socket", vec![DatabaseHost::Unix]), + ("127.0.0.1", tcp("127.0.0.1")), + ("::1", tcp("::1")), + ("[::1]", tcp("[::1]")), + ("localhost", tcp("localhost")), + ("10.0.0.5", tcp("10.0.0.5")), + ("172.16.0.1", tcp("172.16.0.1")), + ("192.168.1.1", tcp("192.168.1.1")), + ("fd00::1", tcp("fd00::1")), + ("db.internal", tcp("db.internal")), + ("db.mixed", tcp("db.mixed")), + ("db.example.com", tcp("db.example.com")), + ("172.32.0.1", tcp("172.32.0.1")), + ("8.8.8.8", tcp("8.8.8.8")), + ("2001:db8::1", tcp("2001:db8::1")), + ("unresolvable", tcp("unresolvable")), + ]; + // (host, loopback-plaintext permits, private-network-plaintext permits) + let expected = [ + ("socket", true, true), + ("127.0.0.1", true, true), + ("::1", true, true), + ("[::1]", true, true), + ("localhost", true, true), + ("10.0.0.5", false, true), + ("172.16.0.1", false, true), + ("192.168.1.1", false, true), + ("fd00::1", false, true), + ("db.internal", false, true), + ("db.mixed", false, false), + ("db.example.com", false, false), + ("172.32.0.1", false, false), + ("8.8.8.8", false, false), + ("2001:db8::1", false, false), + ("unresolvable", false, false), + ]; + for ((name, hosts), (expected_name, loopback, private)) in hosts.iter().zip(expected) { + assert_eq!(*name, expected_name); + for (transport, permitted) in [ + ("loopback-plaintext", loopback), + ("private-network-plaintext", private), + ] { + let config = database(Some(transport), false); + let answer = plaintext_permitted_with(&config, hosts, witness, &resolve); + assert_eq!(answer.is_ok(), permitted, "{name} under {transport}"); + if !permitted { + assert!( + matches!(answer, Err(DatabaseTransportError::HostMismatch(_))), + "{name} under {transport}: {answer:?}" + ); + } + } + // `verified-tls`, written or omitted, takes every host. + for transport in [Some("verified-tls"), None] { + let config = database(transport, false); + assert_eq!( + plaintext_permitted_with(&config, hosts, witness, &resolve), + Ok(VerifiedTls), + "{name}" + ); + } + } + let config = database(Some("loopback-plaintext"), false); + assert_eq!( + plaintext_permitted_with(&config, &[DatabaseHost::Unix], None, &resolve), + Ok(LoopbackPlaintext) + ); + let config = database(Some("private-network-plaintext"), false); + assert_eq!( + plaintext_permitted_with(&config, &tcp("10.0.0.5"), witness, &resolve), + Ok(PrivateNetworkPlaintext) + ); +} + +#[test] +fn a_private_network_transport_is_unreadable_without_the_witness() { + let config = database(Some("private-network-plaintext"), false); + let answer = plaintext_permitted_with(&config, &tcp("10.0.0.5"), None, &resolve); + assert!( + matches!(answer, Err(DatabaseTransportError::DevelopmentOnly(_))), + "{answer:?}" + ); + assert_eq!( + answer.unwrap_err().code(), + "platform.posture.database-private-plaintext" + ); +} + +#[test] +fn a_transport_beside_test_only_plaintext_is_a_conflict_in_every_build() { + let both = database(Some("loopback-plaintext"), true); + for test_build in [false, true] { + assert_eq!( + both.check(test_build), + Err(DatabaseTransportError::Conflict), + "{test_build}" + ); + } + assert_eq!( + DatabaseTransportError::Conflict.code(), + "platform.database.transport-conflict" + ); +} + +#[test] +fn test_only_plaintext_is_refused_outside_test_builds() { + let config = database(None, true); + assert_eq!( + config.check(false), + Err(DatabaseTransportError::TestOnlyPlaintext) + ); + assert_eq!(config.check(true), Ok(())); + let error = DatabaseTransportError::TestOnlyPlaintext; + assert_eq!(error.code(), "platform.database.test-only-plaintext"); + assert_eq!( + error.to_string(), + "database.testOnlyPlaintext is accepted only by test builds" + ); + assert_eq!( + error.suggested_action(), + "Remove it, and set database.transport for a plaintext connection on the same host." + ); + assert_eq!(database(None, false).check(false), Ok(())); +} + +/// A file whose issuer reads its keys from a test issuer. +fn test_issuer_file() -> String { + format!( + "{HEAD}database:\n runtimeUrlRef: secret:env/DB_RUNTIME\n migrationUrlRef: secret:env/DB_MIGRATION\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: api\n jwksSource:\n type: test-issuer\n documentRef: secret:env/TEST_JWKS\naudit:\n path: /var/lib/audit\n hashKeyRef: secret:env/AUDIT_KEY\n" + ) +} + +#[test] +fn production_refuses_a_test_issuer_with_its_code_and_pointer() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Production)); + let error = parse(&loader, &test_issuer_file()).expect_err("production refuses"); + let diagnostics = error.diagnostics(); + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "platform.posture.test-issuer") + .unwrap_or_else(|| panic!("the test issuer is listed: {diagnostics:?}")); + assert_eq!(found.path, "/authentication/oidc/jwksSource"); + assert_eq!(found.severity, Severity::Error); + assert!(found.source.as_ref().unwrap().line.is_some()); + assert_eq!(diagnostics.len(), 1, "{diagnostics:?}"); +} + +#[test] +fn development_admits_a_test_issuer_lists_it_and_the_witness_reads_it() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let loaded = parse(&loader, &test_issuer_file()).expect("development admits"); + let listed: Vec<(&str, Option<&str>)> = loaded + .posture + .settings() + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + assert_eq!( + listed, + [( + "platform.posture.test-issuer", + Some("/authentication/oidc/jwksSource") + )] + ); + let witness = loaded.development.as_ref().expect("a witness"); + let source = &loaded.config.authentication.oidc.provider.jwks_source; + assert_eq!(source.document_ref(), Some("secret:env/TEST_JWKS")); + let gated = Gated::everywhere(JwksSource::default()).expect("discovery is valid everywhere"); + assert!(gated.get(None).is_ok()); + let gated = Gated::for_tests(source.clone()); + assert_eq!( + gated.get(None).unwrap_err().setting.code, + "platform.posture.test-issuer" + ); + assert_eq!(gated.get(Some(witness)).unwrap(), source); +} + +#[test] +fn the_transitional_loader_reads_a_test_issuer_like_static() { + let loader = RuntimeConfigLoader::new_without_posture(ENVELOPE); + let loaded = parse(&loader, &test_issuer_file()).expect("the transitional loader admits"); + assert_eq!(loaded.posture.posture(), Posture::Production); + assert!(loaded.posture.settings().is_empty()); + let from_static = test_issuer_file().replace("type: test-issuer", "type: static"); + let loaded_static = parse(&loader, &from_static).expect("static loads"); + assert_eq!( + loaded + .config + .authentication + .oidc + .provider + .jwks_source + .document_ref(), + loaded_static + .config + .authentication + .oidc + .provider + .jwks_source + .document_ref() + ); +} + +#[test] +fn an_unknown_member_beside_a_test_issuer_is_refused() { + let loader = RuntimeConfigLoader::new(ENVELOPE, declared(Posture::Development)); + let text = test_issuer_file().replace( + " documentRef: secret:env/TEST_JWKS\n", + " documentRef: secret:env/TEST_JWKS\n uri: https://issuer.example.test/jwks\n", + ); + let error = parse(&loader, &text).expect_err("an unknown member"); + assert!( + error + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "config.unknown-key"), + "{:?}", + error.diagnostics() + ); +} diff --git a/crates/registry-platform-config/src/posture_tests.rs b/crates/registry-platform-config/src/posture_tests.rs new file mode 100644 index 0000000000..aa5a787768 --- /dev/null +++ b/crates/registry-platform-config/src/posture_tests.rs @@ -0,0 +1,592 @@ +use super::*; +use crate::{RuntimeConfigLoader, RuntimeEnvelope}; +use registry_platform_yaml::Severity; +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { + api_version: "registry.registrystack.org/example-runtime/v1alpha1", + kind: "ExampleRuntimeConfig", +}; + +const HEAD: &str = + "apiVersion: registry.registrystack.org/example-runtime/v1alpha1\nkind: ExampleRuntimeConfig\n"; + +static PLAINTEXT: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.example-plaintext", + key: "transport", + summary: "The database connection is not encrypted", + production: "Write transport: tls.", +}; + +static INSECURE: DevelopmentSetting = DevelopmentSetting { + code: "platform.posture.example-insecure", + key: "allow", + summary: "The issuer is reached over plain HTTP", + production: "Write allow: false.", +}; + +static COMBINATION: DevelopmentSetting = DevelopmentSetting { + code: "evidence.posture.example-combination", + key: "assuranceProfile", + summary: "Development is declared with a production profile", + production: "Write assuranceProfile: local.", +}; + +static UNRESTRICTED: ExplicitProductionSetting = ExplicitProductionSetting { + code: "adapter.posture.example-unrestricted", + key: "allowedClients", + summary: "Every client is admitted, which the operator states deliberately", +}; + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +enum Transport { + Tls, + Plaintext, +} + +impl DevelopmentClass for Transport { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&PLAINTEXT]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + match self { + Transport::Tls => None, + Transport::Plaintext => Some(&PLAINTEXT), + } + } +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(transparent)] +struct Insecure(bool); + +impl DevelopmentClass for Insecure { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&INSECURE]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + self.0.then_some(&INSECURE) + } +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Database { + transport: Gated, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Shared { + allow: Gated, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Issuer { + #[serde(flatten)] + shared: Shared, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +#[serde(rename_all = "camelCase")] +struct Example { + database: Database, + #[serde(default)] + issuer: Option, + #[serde(default)] + replicas: Vec, +} + +fn declared(posture: Posture) -> DeclaredPosture { + DeclaredPosture { + posture, + source: PostureSource::Flag, + } +} + +fn load(body: &str) -> (Result<(), String>, Vec) { + let text = format!("{HEAD}{body}"); + let (result, found) = collect_development_settings(|| { + RuntimeConfigLoader::new_without_posture(ENVELOPE).parse_str::(&text, |_| None) + }); + (result.map(|_| ()).map_err(|error| error.to_string()), found) +} + +fn found(setting: &'static DevelopmentSetting, pointer: Option<&str>) -> FoundSetting { + FoundSetting { + setting, + pointer: pointer.map(str::to_owned), + position: Some(Position { line: 7, column: 5 }), + origin: SettingOrigin::RuntimeFile, + } +} + +// Gated + +#[test] +fn get_without_a_witness_refuses_a_development_value_and_with_one_returns_it() { + let value = Gated::for_tests(Transport::Plaintext); + let witness = DevelopmentWitness::issue(); + assert_eq!( + value.get(None).unwrap_err(), + DevelopmentOnlyRefused { + setting: &PLAINTEXT + } + ); + assert_eq!(value.get(Some(&witness)).unwrap(), &Transport::Plaintext); +} + +#[test] +fn get_returns_a_value_valid_everywhere_with_or_without_a_witness() { + let value = Gated::everywhere(Transport::Tls).unwrap(); + let witness = DevelopmentWitness::issue(); + assert_eq!(value.get(None).unwrap(), &Transport::Tls); + assert_eq!(value.get(Some(&witness)).unwrap(), &Transport::Tls); + assert_eq!(value.development_setting(), None); +} + +#[test] +fn everywhere_refuses_a_development_value() { + let refused = Gated::everywhere(Transport::Plaintext).unwrap_err(); + assert_eq!(refused.setting.code, "platform.posture.example-plaintext"); + assert_eq!( + refused.to_string(), + "the setting platform.posture.example-plaintext is accepted only when the process declares development" + ); +} + +#[test] +fn a_gated_value_serializes_as_its_inner_value_and_debug_delegates() { + let value = Gated::for_tests(Transport::Plaintext); + assert_eq!(serde_json::to_string(&value).unwrap(), "\"plaintext\""); + assert_eq!(format!("{value:?}"), "Plaintext"); + assert_eq!(value.clone(), value); + assert_ne!(value, Gated::for_tests(Transport::Tls)); +} + +#[test] +fn the_development_setting_names_what_a_value_selects() { + assert_eq!( + Gated::for_tests(Transport::Plaintext).development_setting(), + Some(&PLAINTEXT) + ); +} + +// Collecting + +#[test] +fn a_decode_records_a_member_a_list_item_and_a_flattened_member() { + let (result, found) = load(concat!( + "database:\n transport: plaintext\n", + "issuer:\n allow: true\n", + "replicas:\n - transport: tls\n - transport: plaintext\n", + )); + assert_eq!(result, Ok(()), "a development value never fails the decode"); + let pointers: Vec<_> = found + .iter() + .map(|found| (found.setting.code, found.pointer.as_deref())) + .collect(); + assert_eq!( + pointers, + [ + ( + "platform.posture.example-plaintext", + Some("/database/transport") + ), + ("platform.posture.example-insecure", Some("/issuer/allow")), + ( + "platform.posture.example-plaintext", + Some("/replicas/1/transport") + ), + ] + ); + assert!(found.iter().all(|found| found.position.is_some())); + assert!(found + .iter() + .all(|found| found.origin == SettingOrigin::RuntimeFile)); +} + +#[test] +fn the_position_of_an_exact_site_is_the_value() { + let (_, found) = load("database:\n transport: plaintext\n"); + assert_eq!( + found[0].position, + Some(Position { + line: 4, + column: 14 + }) + ); +} + +#[test] +fn a_value_valid_in_every_posture_is_not_recorded() { + let (result, found) = load("database:\n transport: tls\nissuer:\n allow: false\n"); + assert_eq!(result, Ok(())); + assert!(found.is_empty()); +} + +#[test] +fn a_decode_that_fails_part_way_still_reports_what_it_found() { + let (result, found) = load("database:\n transport: plaintext\nunknown: 1\n"); + assert!(result.is_err()); + assert_eq!(found.len(), 1); +} + +#[test] +fn a_value_decoded_without_the_reader_is_recorded_without_a_pointer() { + let (value, found) = collect_development_settings(|| { + serde_json::from_str::>("\"plaintext\"").unwrap() + }); + assert_eq!(found.len(), 1); + assert_eq!(found[0].pointer, None); + assert_eq!(found[0].position, None); + assert!(value.get(None).is_err()); +} + +#[test] +fn a_decode_with_no_collector_records_nothing_and_still_gates_the_value() { + let value = serde_json::from_str::>("\"plaintext\"").unwrap(); + assert!(value.get(None).is_err()); + let (_, found) = collect_development_settings(|| ()); + assert!(found.is_empty()); +} + +#[test] +fn a_nested_collector_keeps_its_own_findings_and_restores_the_outer() { + let ((inner, after), outer) = collect_development_settings(|| { + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + let (_, inner) = collect_development_settings(|| { + let _ = serde_json::from_str::>("true").unwrap(); + }); + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + let (_, after) = collect_development_settings(|| ()); + (inner, after) + }); + assert_eq!( + inner.iter().map(|f| f.setting.code).collect::>(), + ["platform.posture.example-insecure"] + ); + assert!(after.is_empty()); + assert_eq!( + outer.iter().map(|f| f.setting.code).collect::>(), + [ + "platform.posture.example-plaintext", + "platform.posture.example-plaintext" + ] + ); +} + +#[test] +fn a_panic_inside_a_collector_restores_the_outer_collector() { + let (_, outer) = collect_development_settings(|| { + let panicked = + std::panic::catch_unwind(|| collect_development_settings(|| panic!("decode failed"))); + assert!(panicked.is_err()); + let _ = serde_json::from_str::>("\"plaintext\"").unwrap(); + }); + assert_eq!(outer.len(), 1); + let (_, none) = collect_development_settings(|| ()); + assert!(none.is_empty()); +} + +// F1 + +#[test] +fn production_refuses_each_setting_with_an_error_and_development_warns_under_the_same_code() { + let mut production = PostureReport::new(declared(Posture::Production)); + let mut development = PostureReport::new(declared(Posture::Development)); + for report in [&mut production, &mut development] { + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record(found(&COMBINATION, None)); + } + let file = Path::new("/etc/example/runtime.yaml"); + let refused = production.diagnostics(file); + let accepted = development.diagnostics(file); + assert_eq!( + refused.iter().map(|d| d.code.as_str()).collect::>(), + accepted.iter().map(|d| d.code.as_str()).collect::>() + ); + assert!(refused.iter().all(|d| d.severity == Severity::Error)); + assert!(accepted.iter().all(|d| d.severity == Severity::Warning)); + + assert_eq!(refused[0].code, "platform.posture.example-plaintext"); + assert_eq!(refused[0].path, "/database/transport"); + assert_eq!( + refused[0].message, + "The database connection is not encrypted; it is accepted only when the process declares development" + ); + assert_eq!( + refused[0].suggested_action, + "Write transport: tls. For a laptop or test run, start it with `rstack dev`, or declare development with REGISTRY_STACK_POSTURE=development or --posture development." + ); + let source = refused[0].source.as_ref().unwrap(); + assert_eq!(source.file, "/etc/example/runtime.yaml"); + assert_eq!((source.line, source.column), (Some(7), Some(5))); + + assert_eq!( + accepted[0].message, + "The database connection is not encrypted; production refuses it" + ); + assert_eq!(accepted[0].suggested_action, "Write transport: tls."); +} + +#[test] +fn a_combination_has_no_pointer() { + let mut report = PostureReport::new(declared(Posture::Production)); + report.record(FoundSetting { + setting: &COMBINATION, + pointer: None, + position: None, + origin: SettingOrigin::Combination, + }); + let diagnostics = report.diagnostics(Path::new("/etc/example/runtime.yaml")); + assert_eq!(diagnostics[0].path, ""); +} + +#[test] +fn decide_refuses_in_production_with_every_setting_and_accepts_in_development() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut production = PostureReport::new(declared(Posture::Production)); + let mut development = PostureReport::new(declared(Posture::Development)); + for report in [&mut production, &mut development] { + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record(found(&INSECURE, Some("/issuer/allow"))); + } + let error = production.decide(file).unwrap_err(); + assert_eq!( + error + .diagnostics() + .iter() + .map(|d| d.code.as_str()) + .collect::>(), + [ + "platform.posture.example-plaintext", + "platform.posture.example-insecure" + ] + ); + assert_eq!(error.file(), Some(file)); + assert_eq!(development.decide(file), Ok(())); +} + +#[test] +fn a_report_with_no_settings_decides_ok_in_both_postures() { + let file = Path::new("/etc/example/runtime.yaml"); + for posture in [Posture::Production, Posture::Development] { + let report = PostureReport::new(declared(posture)); + assert!(report.diagnostics(file).is_empty()); + assert_eq!(report.decide(file), Ok(())); + } +} + +#[test] +fn ready_member_shape() { + let mut development = PostureReport::new(declared(Posture::Development)); + development.record(found(&PLAINTEXT, Some("/database/transport"))); + development.record(FoundSetting { + setting: &COMBINATION, + pointer: None, + position: None, + origin: SettingOrigin::Combination, + }); + assert_eq!( + Value::Object(development.ready_member()), + serde_json::json!({ + "posture": "development", + "developmentSettings": [ + {"code": "platform.posture.example-plaintext", "pointer": "/database/transport"}, + {"code": "evidence.posture.example-combination"} + ] + }) + ); + let production = PostureReport::new(declared(Posture::Production)); + assert_eq!( + Value::Object(production.ready_member()), + serde_json::json!({ + "posture": "production", + "developmentSettings": [] + }) + ); +} + +// Explicit production settings + +fn explicit(pointer: Option<&str>) -> FoundExplicitSetting { + FoundExplicitSetting { + setting: &UNRESTRICTED, + pointer: pointer.map(str::to_owned), + position: Some(Position { line: 9, column: 3 }), + origin: SettingOrigin::RuntimeFile, + } +} + +#[test] +fn an_explicit_setting_decides_ok_in_production_and_adds_no_diagnostic() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut report = PostureReport::new(declared(Posture::Production)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + assert_eq!(report.explicit_settings().len(), 1); + assert!(report.settings().is_empty()); + assert!(report.diagnostics(file).is_empty()); + assert_eq!(report.decide(file), Ok(())); +} + +#[test] +fn an_explicit_setting_appears_in_no_ready_member() { + for (posture, name) in [ + (Posture::Production, "production"), + (Posture::Development, "development"), + ] { + let mut report = PostureReport::new(declared(posture)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + assert_eq!( + Value::Object(report.ready_member()), + serde_json::json!({"posture": name, "developmentSettings": []}) + ); + } +} + +#[test] +fn explicit_settings_do_not_change_the_development_diagnostics() { + let file = Path::new("/etc/example/runtime.yaml"); + let mut report = PostureReport::new(declared(Posture::Development)); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + report.record(found(&PLAINTEXT, Some("/database/transport"))); + assert_eq!(report.diagnostics(file).len(), 1); +} + +// Startup log + +#[derive(Clone, Debug)] +struct Logged { + level: tracing::Level, + fields: BTreeMap, +} + +struct Collect(Arc>>); + +struct Fields<'a>(&'a mut BTreeMap); + +impl tracing::field::Visit for Fields<'_> { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) { + self.0.insert(field.name().to_owned(), format!("{value:?}")); + } + + fn record_str(&mut self, field: &tracing::field::Field, value: &str) { + self.0.insert(field.name().to_owned(), value.to_owned()); + } + + fn record_u64(&mut self, field: &tracing::field::Field, value: u64) { + self.0.insert(field.name().to_owned(), value.to_string()); + } +} + +impl tracing::Subscriber for Collect { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + + fn event(&self, event: &tracing::Event<'_>) { + let mut fields = BTreeMap::new(); + event.record(&mut Fields(&mut fields)); + self.0.lock().unwrap().push(Logged { + level: *event.metadata().level(), + fields, + }); + } + + fn enter(&self, _: &tracing::span::Id) {} + + fn exit(&self, _: &tracing::span::Id) {} +} + +fn logged(report: &PostureReport) -> Vec { + let events = Arc::new(Mutex::new(Vec::new())); + tracing::subscriber::with_default(Collect(events.clone()), || report.log_startup()); + let events = events.lock().unwrap().clone(); + events +} + +#[test] +fn startup_logs_the_posture_a_warning_per_development_setting_and_each_explicit_setting() { + let mut report = PostureReport::new(DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Environment, + }); + report.record(found(&PLAINTEXT, Some("/database/transport"))); + report.record_explicit(explicit(Some("/serve/allowedClients"))); + let events = logged(&report); + assert_eq!(events.len(), 3); + + assert_eq!(events[0].level, tracing::Level::INFO); + assert_eq!(events[0].fields["message"], "posture declared"); + assert_eq!(events[0].fields["posture"], "development"); + assert_eq!(events[0].fields["posture_source"], "environment"); + assert_eq!(events[0].fields["development_settings"], "1"); + assert_eq!(events[0].fields["explicit_production_settings"], "1"); + + assert_eq!(events[1].level, tracing::Level::WARN); + assert_eq!( + events[1].fields["message"], + "development-only setting in use; production refuses it" + ); + assert_eq!( + events[1].fields["error_code"], + "platform.posture.example-plaintext" + ); + assert_eq!(events[1].fields["pointer"], "/database/transport"); + + assert_eq!(events[2].level, tracing::Level::INFO); + assert_eq!( + events[2].fields["message"], + "explicit production setting in use" + ); + assert_eq!( + events[2].fields["setting_code"], + "adapter.posture.example-unrestricted" + ); + assert_eq!(events[2].fields["pointer"], "/serve/allowedClients"); +} + +#[test] +fn startup_in_production_logs_one_line_for_a_clean_report() { + let report = PostureReport::new(declared(Posture::Production)); + let events = logged(&report); + assert_eq!(events.len(), 1); + assert_eq!(events[0].fields["posture"], "production"); + assert_eq!(events[0].fields["posture_source"], "flag"); + assert_eq!(events[0].fields["development_settings"], "0"); +} + +#[test] +fn posture_codes_are_recognised_by_their_second_segment() { + assert!(is_posture_code("platform.posture.insecure-issuer-http")); + assert!(is_posture_code("breg.posture.placeholder-identity")); + assert!(!is_posture_code("platform.database.test-only-plaintext")); + assert!(!is_posture_code("platform.activation.posture-mismatch")); + assert!(!is_posture_code("config.unknown-key")); + assert!(!is_posture_code("posture")); +} + +#[cfg(feature = "schema")] +#[test] +fn the_schema_is_the_inner_schema_with_the_development_codes() { + let mut generator = schemars::generate::SchemaSettings::draft2020_12().into_generator(); + let schema = generator.subschema_for::>(); + let schema = serde_json::to_value(&schema).unwrap(); + assert_eq!( + schema["x-registry-development-only"], + serde_json::json!(["platform.posture.example-plaintext"]) + ); +} diff --git a/crates/registry-platform-config/src/schema.rs b/crates/registry-platform-config/src/schema.rs index 4c7c6824f3..784ea825da 100644 --- a/crates/registry-platform-config/src/schema.rs +++ b/crates/registry-platform-config/src/schema.rs @@ -4,8 +4,9 @@ use serde_json::{Map, Value}; use crate::blocks::{ AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, JwksSource, ListenerConfig, - MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, PackageConfig, - PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, UrlHookDestinationConfig, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageConfig, PrivateListenerConfig, SecretProvidersConfig, + TaskGrantStatusConfig, UrlHookDestinationConfig, }; /// File name the shared-blocks generator writes. @@ -26,6 +27,7 @@ struct SharedBlocks { audit_key: AuditKeyConfig, oidc_issuer: OidcIssuerConfig, oidc_clients: OidcClientsConfig, + oidc_package_clients: OidcPackageClientsConfig, task_grant_status: TaskGrantStatusConfig, object_storage: ObjectStorageConfig, attachment_verifier: AttachmentVerifierConfig, diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 150e7339d0..c1e9a89107 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -7,11 +7,14 @@ use std::{ fs::File, io::Read, path::{Path, PathBuf}, + sync::atomic::{AtomicU16, Ordering}, }; use thiserror::Error; use zeroize::Zeroizing; +use crate::DevelopmentWitness; + /// Maximum accepted size of one resolved secret value. pub const MAX_SECRET_BYTES: usize = 64 * 1024; @@ -88,13 +91,168 @@ pub enum SecretError { #[error("the referenced secret is unavailable")] Unavailable, #[error("the referenced secret file is unsafe")] - UnsafeFile, + UnsafeFile(SecretFileCheck), #[error("the referenced secret could not be read")] Read, #[error("the referenced secret value is invalid")] InvalidValue, } +impl SecretError { + /// What the operator does about this failure. It states the same fix + /// wherever the failure surfaces, so a product does not restate the rule. + #[must_use] + pub fn suggested_action(&self) -> &'static str { + match self { + Self::InvalidReference => { + "Write the reference as an exact secret:env/NAME or secret:file/name." + } + Self::ProviderDisabled => { + "Enable the reference's provider under secretProviders in the runtime file." + } + Self::InvalidProviderConfiguration => { + "Enable at least one secret provider, and give the file provider an absolute root." + } + Self::Unavailable => { + "Create the secret under the configured provider, or correct the name." + } + Self::UnsafeFile(check) => check.suggested_action(), + Self::Read => "Check that the secret can be read by the runtime user.", + Self::InvalidValue => { + "Store a non-empty value of at most 64 KiB, without NUL bytes unless the secret is a binary key." + } + } + } +} + +/// The check a refused secret file failed. Each has its own code, text and +/// fix, none of which names a path, a reference or a value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SecretFileCheck { + /// A link target is absolute, empty, or holds a `..` component. + LinkLeavesRoot, + /// More than [`MAX_SECRET_LINKS`] links were followed. + TooManyLinks, + /// The runtime user cannot open the file. + CannotOpen, + /// The name does not lead to a regular file. + NotRegular, + /// The file has more than one hard link. + HardLinked, + /// The owner is neither the runtime user nor root. + Owner, + /// Users outside the owner and group can write the file. + WorldWritable, + /// Users outside the owner and group can read the file. + WorldReadable, + /// The group has access the rule does not allow. + GroupAccess, + /// An execute, setuid, setgid or sticky bit, or an owner that cannot read. + ModeBits, +} + +impl SecretFileCheck { + /// The diagnostic code, `platform.secret-file.`. + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::LinkLeavesRoot => "platform.secret-file.link-leaves-root", + Self::TooManyLinks => "platform.secret-file.too-many-links", + Self::CannotOpen => "platform.secret-file.cannot-open", + Self::NotRegular => "platform.secret-file.not-regular", + Self::HardLinked => "platform.secret-file.hard-linked", + Self::Owner => "platform.secret-file.owner", + Self::WorldWritable => "platform.secret-file.world-writable", + Self::WorldReadable => "platform.secret-file.world-readable", + Self::GroupAccess => "platform.secret-file.group-access", + Self::ModeBits => "platform.secret-file.mode-bits", + } + } + + /// What is wrong, without a path, a reference or a value. + #[must_use] + pub const fn message(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "the secret file is reached through a link that leaves secretProviders.file.root" + } + Self::TooManyLinks => "the secret file is reached through more than 8 links", + Self::CannotOpen => "the runtime user cannot open the secret file", + Self::NotRegular => "the secret file is not a regular file", + Self::HardLinked => "the secret file has more than one hard link", + Self::Owner => "the secret file is owned by neither the runtime user nor root", + Self::WorldWritable => { + "users outside the file's owner and group can write the secret file" + } + Self::WorldReadable => { + "users outside the file's owner and group can read the secret file" + } + Self::GroupAccess => "the secret file's group has access the rule does not allow", + Self::ModeBits => { + "the secret file has an execute, setuid, setgid or sticky bit, or its owner cannot read it" + } + } + } + + /// The fix, one sentence per step. + #[must_use] + pub const fn suggested_action(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "Put the file under secretProviders.file.root, or use a relative link without `..` that stays below it." + } + Self::TooManyLinks => { + "Point the name at the file, or at a chain of at most 8 links below secretProviders.file.root." + } + Self::CannotOpen => { + "Make the file readable by the runtime user: mode 0400 or 0600 owned by that user, or 0440 owned by root with the runtime user's group. On Kubernetes, set the secret volume's defaultMode to 0440 and the pod's securityContext.fsGroup to the runtime user's group." + } + Self::NotRegular => { + "Point the name at a regular file, not a directory, device, socket or pipe." + } + Self::HardLinked => "Replace it with a copy that has one link.", + Self::Owner => { + "Give it to the runtime user with mode 0400 or 0600, or to root with mode 0440 and the runtime user's group." + } + Self::WorldWritable => "Remove all access for others (chmod o-rwx).", + Self::WorldReadable => { + "Remove access for others: mode 0400 or 0600 for a file the runtime user owns, 0440 for a root-owned file. On Kubernetes, set the secret volume's defaultMode to 0440 and the pod's securityContext.fsGroup to the runtime user's group." + } + Self::GroupAccess => { + "Use mode 0400 or 0600 for a file the runtime user owns. Group read is accepted only on a root-owned file (0440 or 0640) read by a non-root runtime." + } + Self::ModeBits => "Set mode 0400 or 0600.", + } + } + + /// Whether a development process loads the file with a warning instead of + /// refusing it. Production refuses every check. + #[must_use] + pub const fn warns_in_development(self) -> bool { + matches!( + self, + Self::WorldReadable | Self::GroupAccess | Self::ModeBits + ) + } + + const fn bit(self) -> u16 { + 1 << (self as u16) + } +} + +/// Which checks have already warned in this process. +#[derive(Default)] +struct WarnedChecks(AtomicU16); + +impl WarnedChecks { + /// True the first time `check` is seen. + fn first(&self, check: SecretFileCheck) -> bool { + self.0.fetch_or(check.bit(), Ordering::Relaxed) & check.bit() == 0 + } +} + +static WARNED: WarnedChecks = WarnedChecks(AtomicU16::new(0)); + /// Secret bytes that are erased when dropped and never exposed by `Debug`. pub struct ProtectedSecret(Zeroizing>); @@ -125,13 +283,21 @@ impl fmt::Debug for ProtectedSecret { /// Resolver for exact secret references under an explicit provider allowlist. /// /// File names are single bounded path components and are opened relative to -/// the configured absolute root with `openat`. The opened file, rather than a -/// later pathname lookup, is checked for type, ownership, mode, and link count -/// before at most [`MAX_SECRET_BYTES`] are retained. +/// the configured absolute root with `openat`. A link is followed only by +/// downward relative steps from that root, at most [`MAX_SECRET_LINKS`] of +/// them. The opened file, rather than a later pathname lookup, is checked for +/// type, ownership, mode, and link count before at most [`MAX_SECRET_BYTES`] +/// are retained. +/// +/// The production rule accepts a file owned by the runtime user with mode 0400 +/// or 0600, and a root-owned file with no bit outside 0640 when the runtime is +/// not root. [`Self::in_development`] relaxes the read and mode-bit checks to a +/// warning for a process that declared development. #[derive(Debug)] pub struct SecretResolver { providers: BTreeSet, file_root: PathBuf, + development: bool, } impl SecretResolver { @@ -144,6 +310,7 @@ impl SecretResolver { Self { providers: BTreeSet::new(), file_root: PathBuf::new(), + development: false, } } @@ -162,9 +329,35 @@ impl SecretResolver { Ok(Self { providers, file_root, + development: false, }) } + /// Apply the development rule when the process holds the witness. Without + /// it the resolver keeps the production rule, so a production path cannot + /// relax the rule by mistake. + #[must_use] + pub fn in_development(mut self, witness: Option<&DevelopmentWitness>) -> Self { + self.development = witness.is_some(); + self + } + + /// Run every check a read runs, without retaining the bytes. A check tool + /// uses this to give the verdict the runtime would give. + pub fn inspect_reference(&self, reference: &SecretReference) -> Result<(), SecretError> { + if !self.providers.contains(&reference.provider()) { + return Err(SecretError::ProviderDisabled); + } + match reference.provider() { + SecretProvider::Environment => env::var_os(reference.name()) + .map(|_| ()) + .ok_or(SecretError::Unavailable), + SecretProvider::File => { + open_secret_file(&self.file_root, reference.name(), self.development).map(|_| ()) + } + } + } + /// Resolve one exact `secret:env/NAME` or `secret:file/name` reference. pub fn resolve(&self, reference: &str) -> Result { let reference = SecretReference::parse(reference)?; @@ -195,7 +388,9 @@ impl SecretResolver { let bytes = match reference.provider() { SecretProvider::Environment => read_environment(reference.name())?, - SecretProvider::File => read_secret_file(&self.file_root, reference.name())?, + SecretProvider::File => { + read_secret_file(&self.file_root, reference.name(), self.development)? + } }; validate_binary_secret(bytes) } @@ -216,53 +411,208 @@ fn read_environment(name: &str) -> Result>, SecretError> { Ok(Zeroizing::new(bytes)) } +/// The most links a secret name may pass through. Kubernetes uses two. +pub const MAX_SECRET_LINKS: usize = 8; + +#[cfg(unix)] +fn read_secret_file( + root: &Path, + name: &str, + development: bool, +) -> Result>, SecretError> { + read_bounded(open_secret_file(root, name, development)?) +} + +/// What the rule looks at in an opened file. +#[derive(Clone, Copy, Debug)] +struct Facts { + kind: FileKind, + uid: u32, + mode: u32, + nlink: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum FileKind { + Regular, + Directory, + Fifo, + Socket, + Device, +} + +/// Judge an opened file. Production refuses at the first failing check. In +/// development the shape, link-count, owner and world-write checks still +/// refuse, and the checks that [`SecretFileCheck::warns_in_development`] names +/// are returned as warnings. +fn judge( + facts: Facts, + euid: u32, + development: bool, +) -> Result, SecretFileCheck> { + use SecretFileCheck::{ + GroupAccess, HardLinked, ModeBits, NotRegular, Owner, WorldReadable, WorldWritable, + }; + + if facts.kind != FileKind::Regular { + return Err(NotRegular); + } + if facts.nlink != 1 { + return Err(HardLinked); + } + if facts.uid != euid && facts.uid != 0 { + return Err(Owner); + } + if facts.mode & 0o002 != 0 { + return Err(WorldWritable); + } + let own = facts.uid == euid; + let mut failed = Vec::new(); + if facts.mode & 0o005 != 0 { + failed.push(WorldReadable); + } + let group_bits = if own { 0o070 } else { 0o030 }; + if facts.mode & group_bits != 0 { + failed.push(GroupAccess); + } + if facts.mode & 0o7100 != 0 || (own && facts.mode & 0o400 == 0) { + failed.push(ModeBits); + } + match (development, failed.first()) { + (false, Some(check)) => Err(*check), + _ => Ok(failed), + } +} + +/// Walk `name` from the root by openat steps, following only relative +/// downward links, then judge the descriptor that will be read. #[cfg(unix)] -fn read_secret_file(root: &Path, name: &str) -> Result>, SecretError> { - use rustix::fs::{Mode, OFlags}; +fn open_secret_file(root: &Path, name: &str, development: bool) -> Result { + use rustix::{ + fs::{Mode, OFlags}, + io::Errno, + }; + use std::collections::VecDeque; - let root = rustix::fs::open( + let unsafe_file = SecretError::UnsafeFile; + let mut dir = rustix::fs::open( root, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::DIRECTORY, Mode::empty(), ) .map_err(|_| SecretError::Unavailable)?; - let secret = rustix::fs::openat( - &root, - name, - OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, - Mode::empty(), - ) - .map_err(|_| SecretError::Unavailable)?; + let mut pending: VecDeque> = VecDeque::from([name.as_bytes().to_vec()]); + let mut links = 0_usize; + let secret = loop { + let Some(component) = pending.pop_front() else { + // A link whose target names only the directory it sits in. + return Err(unsafe_file(SecretFileCheck::NotRegular)); + }; + let last = pending.is_empty(); + let mut flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NOCTTY; + flags |= if last { + OFlags::NONBLOCK + } else { + OFlags::DIRECTORY + }; + match rustix::fs::openat(&dir, component.as_slice(), flags, Mode::empty()) { + Ok(fd) if last => break fd, + Ok(fd) => dir = fd, + Err(Errno::LOOP | Errno::NOTDIR) => { + let target = match rustix::fs::readlinkat(&dir, component.as_slice(), Vec::new()) { + Ok(target) => target, + // Not a link: a file where a directory was needed. + Err(Errno::INVAL) => return Err(SecretError::Unavailable), + Err(_) => return Err(SecretError::Read), + }; + links += 1; + if links > MAX_SECRET_LINKS { + return Err(unsafe_file(SecretFileCheck::TooManyLinks)); + } + let target = target.into_bytes(); + if target.is_empty() || target.starts_with(b"/") { + return Err(unsafe_file(SecretFileCheck::LinkLeavesRoot)); + } + let mut steps = Vec::new(); + for step in target.split(|byte| *byte == b'/') { + match step { + b"" | b"." => {} + b".." => return Err(unsafe_file(SecretFileCheck::LinkLeavesRoot)), + step => steps.push(step.to_vec()), + } + } + for step in steps.into_iter().rev() { + pending.push_front(step); + } + } + Err(Errno::NOENT) => return Err(SecretError::Unavailable), + Err(Errno::ACCESS) => return Err(unsafe_file(SecretFileCheck::CannotOpen)), + Err(_) => return Err(SecretError::Read), + } + }; let file = File::from(secret); - validate_file_metadata(&file)?; - read_bounded(file) + judge_file(&file, development)?; + Ok(file) } #[cfg(unix)] -fn validate_file_metadata(file: &File) -> Result<(), SecretError> { - use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _}; +fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { + use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _}; let metadata = file.metadata().map_err(|_| SecretError::Read)?; - let mode = metadata.permissions().mode() & 0o7777; - if !metadata.is_file() - || metadata.uid() != rustix::process::geteuid().as_raw() - || !matches!(mode, 0o400 | 0o600) - || metadata.nlink() != 1 - { - return Err(SecretError::UnsafeFile); - } - Ok(()) + let file_type = metadata.file_type(); + let kind = if file_type.is_file() { + FileKind::Regular + } else if file_type.is_dir() { + FileKind::Directory + } else if file_type.is_fifo() { + FileKind::Fifo + } else if file_type.is_socket() { + FileKind::Socket + } else { + FileKind::Device + }; + let facts = Facts { + kind, + uid: metadata.uid(), + mode: metadata.permissions().mode() & 0o7777, + nlink: metadata.nlink(), + }; + match judge(facts, rustix::process::geteuid().as_raw(), development) { + Err(check) => Err(SecretError::UnsafeFile(check)), + Ok(warnings) => { + for check in warnings { + if WARNED.first(check) { + tracing::warn!( + error_code = check.code(), + "{}; production refuses it. {}", + check.message(), + check.suggested_action() + ); + } + } + Ok(()) + } + } } #[cfg(not(unix))] -fn read_secret_file(root: &Path, name: &str) -> Result>, SecretError> { +fn read_secret_file( + root: &Path, + name: &str, + development: bool, +) -> Result>, SecretError> { + read_bounded(open_secret_file(root, name, development)?) +} + +#[cfg(not(unix))] +fn open_secret_file(root: &Path, name: &str, _development: bool) -> Result { let path = root.join(name); let metadata = std::fs::symlink_metadata(&path).map_err(|_| SecretError::Unavailable)?; if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(SecretError::UnsafeFile); + return Err(SecretError::UnsafeFile(SecretFileCheck::NotRegular)); } - let file = File::open(path).map_err(|_| SecretError::Unavailable)?; - read_bounded(file) + File::open(path).map_err(|_| SecretError::Unavailable) } /// Read at most one byte past [`MAX_SECRET_BYTES`] into one buffer allocated @@ -290,6 +640,10 @@ fn validate_binary_secret(bytes: Zeroizing>) -> Result Facts { + Facts { + kind, + uid, + mode, + nlink, + } +} + +fn observed(result: Result, SecretFileCheck>) -> Outcome { + match result { + Err(check) => Outcome::Refuse(check), + Ok(warnings) if warnings.is_empty() => Outcome::Load, + Ok(warnings) => Outcome::Warn(Box::leak(warnings.into_boxed_slice())), + } +} + +#[test] +fn the_decision_table_gives_one_answer_per_owner_mode_and_posture() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse, Warn}; + const APP: u32 = 10001; + #[rustfmt::skip] + let rows: &[Row] = &[ + ("A1", APP, APP, 0o400, Regular, 1, Load, Load), + ("A2", APP, APP, 0o600, Regular, 1, Load, Load), + ("A3", APP, APP, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A4", APP, APP, 0o640, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A5", APP, APP, 0o620, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A6", APP, APP, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A7", APP, APP, 0o604, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A8", APP, APP, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A9a", APP, APP, 0o602, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A9b", APP, APP, 0o666, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A10a", APP, APP, 0o500, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A10b", APP, APP, 0o700, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A10c", APP, APP, 0o4600, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("A12", APP, 0, 0o440, Regular, 1, Load, Load), + ("A13", APP, 0, 0o640, Regular, 1, Load, Load), + ("A14", APP, 0, 0o400, Regular, 1, Load, Load), + ("A15a", APP, 0, 0o460, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A15b", APP, 0, 0o450, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A16a", APP, 0, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A16b", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("A17", APP, 0, 0o446, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("A19", APP, 10002, 0o644, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("A20a", 0, 0, 0o400, Regular, 1, Load, Load), + ("A20b", 0, 0, 0o600, Regular, 1, Load, Load), + ("A21", 0, 0, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("A22", 0, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("A23", 0, APP, 0o600, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("A24", APP, APP, 0o400, Regular, 2, Refuse(HardLinked), Refuse(HardLinked)), + ("A25", APP, APP, 0o400, Directory, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25f", APP, APP, 0o400, FileKind::Fifo, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25s", APP, APP, 0o400, FileKind::Socket, 1, Refuse(NotRegular), Refuse(NotRegular)), + ("A25d", APP, APP, 0o400, FileKind::Device, 1, Refuse(NotRegular), Refuse(NotRegular)), + // Observed mounts (m0 secret-mounts), by their observed owner and mode. + ("C-b", APP, APP, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("C-eb", APP, 0, 0o444, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("C-el", APP, APP, 0o400, Regular, 1, Load, Load), + ("vu/root640", APP, 0, 0o640, Regular, 1, Load, Load), + ("vu/root644", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("vu/app440", APP, APP, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("K-a", 0, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable, GroupAccess])), + ("K-b", APP, 0, 0o644, Regular, 1, Refuse(WorldReadable), Warn(&[WorldReadable])), + ("K-d", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-f", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-g2", APP, 0, 0o440, Regular, 1, Load, Load), + ("K-root-0440", 0, 0, 0o440, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ]; + for (row, euid, uid, mode, kind, nlink, production, development) in rows { + let f = facts(*kind, *uid, *mode, *nlink); + assert_eq!( + observed(judge(f, *euid, false)), + *production, + "{row} in production" + ); + assert_eq!( + observed(judge(f, *euid, true)), + *development, + "{row} in development" + ); + } +} + +#[test] +fn every_check_has_a_unique_code_a_value_free_message_and_a_full_stop_fix() { + let all = [ + LinkLeavesRoot, + TooManyLinks, + CannotOpen, + NotRegular, + HardLinked, + Owner, + WorldWritable, + WorldReadable, + GroupAccess, + ModeBits, + ]; + let mut codes = std::collections::BTreeSet::new(); + for check in all { + let code = check.code(); + assert!(code.starts_with("platform.secret-file."), "{code}"); + assert!( + code["platform.secret-file.".len()..] + .bytes() + .all(|b| b.is_ascii_lowercase() || b == b'-'), + "{code}" + ); + assert!(codes.insert(code), "{code} repeats"); + assert!(check.suggested_action().ends_with('.'), "{code}"); + for text in [check.message(), check.suggested_action()] { + assert!(!text.contains("/run/") && !text.contains("/etc/"), "{text}"); + assert!(!text.contains("secret:"), "{text}"); + } + } + for check in [CannotOpen, WorldReadable] { + let action = check.suggested_action(); + assert!(action.contains("defaultMode"), "{action}"); + assert!(action.contains("fsGroup"), "{action}"); + } + for check in all { + assert!(!check.suggested_action().contains("runAsUser")); + } +} + +#[test] +fn the_development_split_lives_in_one_place() { + for check in [WorldReadable, GroupAccess, ModeBits] { + assert!(check.warns_in_development(), "{check:?}"); + } + for check in [ + LinkLeavesRoot, + TooManyLinks, + CannotOpen, + NotRegular, + HardLinked, + Owner, + WorldWritable, + ] { + assert!(!check.warns_in_development(), "{check:?}"); + } +} + +#[test] +fn a_check_warns_once_per_process_however_often_it_fires() { + let warned = WarnedChecks::default(); + assert!(warned.first(WorldReadable)); + assert!(!warned.first(WorldReadable)); + assert!(warned.first(GroupAccess)); + assert!(!warned.first(GroupAccess)); + assert!(!warned.first(WorldReadable)); +} + +#[test] +fn error_fixes_come_from_the_error() { + assert_eq!( + SecretError::UnsafeFile(HardLinked).suggested_action(), + HardLinked.suggested_action() + ); + for error in [ + SecretError::InvalidReference, + SecretError::ProviderDisabled, + SecretError::InvalidProviderConfiguration, + SecretError::Unavailable, + SecretError::Read, + SecretError::InvalidValue, + ] { + assert!(error.suggested_action().ends_with('.'), "{error:?}"); + } +} + +#[cfg(unix)] +mod filesystem { + use super::*; + use std::{ + fs, + os::unix::fs::{symlink, PermissionsExt as _}, + path::Path, + }; + + fn write(root: &Path, name: &str, mode: u32) { + let path = root.join(name); + fs::write(&path, b"file-canary").expect("write"); + fs::set_permissions(path, fs::Permissions::from_mode(mode)).expect("mode"); + } + + fn resolver(root: &Path) -> SecretResolver { + SecretResolver::new([SecretProvider::File], root).expect("resolver") + } + + fn development(root: &Path) -> SecretResolver { + resolver(root).in_development(Some(&DevelopmentWitness::issue())) + } + + fn load(resolver: &SecretResolver, name: &str) -> Result, SecretError> { + resolver + .resolve(&format!("secret:file/{name}")) + .map(|secret| secret.expose_secret().to_vec()) + } + + #[test] + fn a_relative_link_inside_the_root_loads_the_file_it_names() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "target", 0o400); + symlink("target", root.path().join("name")).expect("link"); + fs::create_dir(root.path().join("sub")).expect("dir"); + write(&root.path().join("sub"), "token", 0o400); + symlink("sub/token", root.path().join("nested")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!(load(&resolver, "name").expect("loads"), b"file-canary"); + assert_eq!(load(&resolver, "nested").expect("loads"), b"file-canary"); + } + + fn kubernetes_layout(root: &Path, mode: u32) { + fs::create_dir(root.join("..ts")).expect("dir"); + write(&root.join("..ts"), "token", mode); + symlink("..ts", root.join("..data")).expect("link"); + symlink("..data/token", root.join("token")).expect("link"); + } + + #[test] + fn the_kubernetes_link_chain_loads_and_the_target_is_judged_not_the_links() { + let root = tempfile::tempdir().expect("root"); + kubernetes_layout(root.path(), 0o400); + assert_eq!( + load(&resolver(root.path()), "token").expect("loads"), + b"file-canary" + ); + + let loose = tempfile::tempdir().expect("root"); + kubernetes_layout(loose.path(), 0o644); + assert_eq!( + load(&resolver(loose.path()), "token"), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + assert_eq!( + load(&development(loose.path()), "token").expect("warns and loads"), + b"file-canary" + ); + } + + #[test] + fn a_chain_of_eight_links_loads_and_nine_or_a_loop_is_refused() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "end", 0o400); + let mut previous = "end".to_owned(); + for index in 1..=9 { + let name = format!("l{index}"); + symlink(&previous, root.path().join(&name)).expect("link"); + previous = name; + } + let resolver = resolver(root.path()); + assert_eq!(load(&resolver, "l8").expect("8 links load"), b"file-canary"); + assert_eq!( + load(&resolver, "l9"), + Err(SecretError::UnsafeFile(TooManyLinks)) + ); + symlink("loop-b", root.path().join("loop-a")).expect("link"); + symlink("loop-a", root.path().join("loop-b")).expect("link"); + assert_eq!( + load(&resolver, "loop-a"), + Err(SecretError::UnsafeFile(TooManyLinks)) + ); + } + + #[test] + fn a_link_that_could_leave_the_root_is_refused_in_both_postures() { + let root = tempfile::tempdir().expect("root"); + let outside = tempfile::tempdir().expect("outside"); + write(outside.path(), "token", 0o400); + write(root.path(), "inside", 0o400); + fs::create_dir(root.path().join("sub")).expect("dir"); + write(&root.path().join("sub"), "token", 0o400); + symlink(outside.path().join("token"), root.path().join("absolute")).expect("link"); + symlink( + root.path().join("inside"), + root.path().join("absolute-inside"), + ) + .expect("link"); + symlink("../x", root.path().join("parent")).expect("link"); + symlink("sub/../inside", root.path().join("dotdot")).expect("link"); + symlink(outside.path(), root.path().join("elsewhere")).expect("link"); + symlink("elsewhere/token", root.path().join("through")).expect("link"); + for resolver in [resolver(root.path()), development(root.path())] { + for name in ["absolute", "absolute-inside", "parent", "dotdot", "through"] { + assert_eq!( + load(&resolver, name), + Err(SecretError::UnsafeFile(LinkLeavesRoot)), + "{name}" + ); + } + } + } + + #[test] + fn a_link_to_a_directory_or_a_dangling_link_is_refused() { + let root = tempfile::tempdir().expect("root"); + fs::create_dir(root.path().join("sub")).expect("dir"); + symlink("sub", root.path().join("to-dir")).expect("link"); + symlink("missing", root.path().join("dangling")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!( + load(&resolver, "to-dir"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + assert_eq!(load(&resolver, "dangling"), Err(SecretError::Unavailable)); + assert_eq!(load(&resolver, "absent"), Err(SecretError::Unavailable)); + } + + #[test] + fn a_link_in_the_root_path_itself_is_refused_and_its_parents_are_not_checked() { + let real = tempfile::tempdir().expect("real"); + write(real.path(), "token", 0o400); + let holder = tempfile::tempdir().expect("holder"); + let linked_root = holder.path().join("root-link"); + symlink(real.path(), &linked_root).expect("link"); + assert_eq!( + load(&resolver(&linked_root), "token"), + Err(SecretError::Unavailable) + ); + let parent_link = holder.path().join("parent-link"); + symlink(holder.path(), &parent_link).expect("link"); + fs::create_dir(holder.path().join("child")).expect("dir"); + write(&holder.path().join("child"), "token", 0o400); + assert!(load(&resolver(&parent_link.join("child")), "token").is_ok()); + } + + #[test] + fn the_roots_own_mode_is_not_checked() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "token", 0o400); + fs::set_permissions(root.path(), fs::Permissions::from_mode(0o1777)).expect("mode"); + assert!(load(&resolver(root.path()), "token").is_ok()); + } + + #[test] + fn a_fifo_is_refused_without_blocking() { + let root = tempfile::tempdir().expect("root"); + let status = std::process::Command::new("mkfifo") + .arg(root.path().join("pipe")) + .status() + .expect("mkfifo runs"); + assert!(status.success()); + assert_eq!( + load(&resolver(root.path()), "pipe"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + } + + #[test] + fn a_directory_is_not_a_secret() { + let root = tempfile::tempdir().expect("root"); + fs::create_dir(root.path().join("directory")).expect("dir"); + assert_eq!( + load(&resolver(root.path()), "directory"), + Err(SecretError::UnsafeFile(NotRegular)) + ); + } + + #[test] + fn a_file_the_runtime_cannot_open_is_cannot_open_not_unavailable() { + if rustix::process::geteuid().is_root() { + return; + } + let root = tempfile::tempdir().expect("root"); + write(root.path(), "locked", 0o000); + assert_eq!( + load(&resolver(root.path()), "locked"), + Err(SecretError::UnsafeFile(CannotOpen)) + ); + assert_eq!( + load(&development(root.path()), "locked"), + Err(SecretError::UnsafeFile(CannotOpen)) + ); + } + + #[test] + fn development_warns_for_loose_modes_and_still_refuses_shape_owner_and_write() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "world-readable", 0o644); + write(root.path(), "group", 0o440); + write(root.path(), "executable", 0o500); + write(root.path(), "world-writable", 0o666); + symlink("/etc/hosts", root.path().join("absolute")).expect("link"); + let production = resolver(root.path()); + let development = development(root.path()); + for (name, check) in [ + ("world-readable", WorldReadable), + ("group", GroupAccess), + ("executable", ModeBits), + ] { + assert_eq!(load(&production, name), Err(SecretError::UnsafeFile(check))); + assert_eq!(load(&development, name).expect("warns"), b"file-canary"); + } + for (name, check) in [ + ("world-writable", WorldWritable), + ("absolute", LinkLeavesRoot), + ] { + assert_eq!(load(&production, name), Err(SecretError::UnsafeFile(check))); + assert_eq!( + load(&development, name), + Err(SecretError::UnsafeFile(check)) + ); + } + } + + #[test] + fn a_resolver_without_the_witness_applies_the_production_rule() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "token", 0o644); + let resolver = resolver(root.path()).in_development(None); + assert_eq!( + load(&resolver, "token"), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + } + + #[test] + fn inspecting_a_reference_gives_the_verdict_without_the_bytes() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "good", 0o400); + write(root.path(), "loose", 0o644); + let resolver = resolver(root.path()); + let good = SecretReference::parse("secret:file/good").unwrap(); + let loose = SecretReference::parse("secret:file/loose").unwrap(); + let absent = SecretReference::parse("secret:file/absent").unwrap(); + assert_eq!(resolver.inspect_reference(&good), Ok(())); + assert_eq!( + resolver.inspect_reference(&loose), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + assert_eq!( + resolver.inspect_reference(&absent), + Err(SecretError::Unavailable) + ); + } +} diff --git a/crates/registry-platform-config/tests/posture_acceptance.rs b/crates/registry-platform-config/tests/posture_acceptance.rs new file mode 100644 index 0000000000..531ddb9e08 --- /dev/null +++ b/crates/registry-platform-config/tests/posture_acceptance.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A posture diagnostic cannot be hidden by a project check acceptance. + +use registry_platform_config::apply_check_acceptances; +use registry_platform_yaml::{Diagnostic, Report, Severity, Source}; + +const ACCEPTANCES: &str = "apiVersion: id.registrystack.org/formats/platform/check-acceptances/v1alpha1\nkind: PlatformCheckAcceptances\nacceptances:\n - code: platform.posture.insecure-issuer-http\n scope:\n file: runtime.yaml\n path: /issuer/allowInsecureHttp\n reason: We need it on the laptop.\n"; + +fn posture_warning(root: &std::path::Path) -> Diagnostic { + let mut diagnostic = Diagnostic::warning( + "platform.posture.insecure-issuer-http", + "/issuer/allowInsecureHttp", + "The issuer is reached over plain HTTP; production refuses it", + "Write allowInsecureHttp: false.", + ); + diagnostic.source = Some(Source { + file: root.join("runtime.yaml").display().to_string(), + line: Some(4), + column: Some(3), + }); + diagnostic +} + +#[test] +fn an_acceptance_naming_a_posture_code_is_refused_and_hides_nothing() { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("runtime.yaml"), + "issuer:\n allowInsecureHttp: true\n", + ) + .unwrap(); + std::fs::write(root.path().join("check-acceptances.yaml"), ACCEPTANCES).unwrap(); + let mut report = Report::new(vec![posture_warning(root.path())]); + apply_check_acceptances(root.path(), &mut report); + + let posture = report + .diagnostics() + .iter() + .find(|d| d.code == "platform.posture.insecure-issuer-http") + .unwrap(); + assert_eq!(posture.accepted_reason, None); + assert_eq!(report.accepted_warning_count(), 0); + let refusal: Vec<_> = report + .diagnostics() + .iter() + .filter(|d| d.code == "config.check-acceptance-not-acceptable") + .collect(); + assert_eq!(refusal.len(), 1); + assert_eq!(refusal[0].severity, Severity::Error); + assert_eq!(refusal[0].path, "/acceptances/0/code"); +} + +#[test] +fn other_acceptances_in_the_same_file_still_apply() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("registry.yaml"), "a:\n b: 1\n").unwrap(); + let input = ACCEPTANCES.to_owned() + + " - code: example.access.unrestricted\n scope:\n file: registry.yaml\n path: /a/b\n reason: Reviewed.\n"; + std::fs::write(root.path().join("check-acceptances.yaml"), input).unwrap(); + let mut other = Diagnostic::warning("example.access.unrestricted", "/a/b", "m", "a"); + other.source = Some(Source { + file: root.path().join("registry.yaml").display().to_string(), + line: Some(2), + column: Some(3), + }); + let mut report = Report::new(vec![posture_warning(root.path()), other]); + apply_check_acceptances(root.path(), &mut report); + assert_eq!(report.accepted_warning_count(), 1); +} diff --git a/crates/registry-platform-config/tests/posture_carrier.rs b/crates/registry-platform-config/tests/posture_carrier.rs new file mode 100644 index 0000000000..21276df08e --- /dev/null +++ b/crates/registry-platform-config/tests/posture_carrier.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Product crates resolve the declared posture through this crate alone. + +use std::ffi::OsStr; + +use registry_platform_config::{ + declared_from, DeclaredPosture, Posture, PostureError, PostureSource, DEVELOPMENT, POSTURE_ENV, +}; + +#[test] +fn the_carrier_is_reachable_through_the_config_crate() { + assert_eq!(POSTURE_ENV, "REGISTRY_STACK_POSTURE"); + assert_eq!( + declared_from(Some(DEVELOPMENT), None), + Ok(DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Flag, + }) + ); + let refused = declared_from(None, Some(OsStr::new("Development"))) + .expect_err("the value is case-sensitive"); + assert_eq!(refused, PostureError::InvalidEnvironment); + assert_eq!(refused.code(), "platform.posture.invalid-value"); + // `declared` reads the process variable; this only proves the name resolves. + let _: fn(Option<&str>) -> Result = + registry_platform_config::declared; +} diff --git a/crates/registry-platform-crypto/README.md b/crates/registry-platform-crypto/README.md index bcbf2c9ee1..c19296743b 100644 --- a/crates/registry-platform-crypto/README.md +++ b/crates/registry-platform-crypto/README.md @@ -19,6 +19,8 @@ Crypto primitives shared by registry services. - Version 1 hook delivery signing and receiver verification, including input bounds, signature-version checks, constant-time comparison, and receiver-selected delivery-time skew. +- Standard Webhooks symmetric delivery signing and verification with exact + key bytes, key rotation, and a two-sided freshness window. - HMAC-SHA256 tags and legacy-interoperability HMAC-SHA1 verification in `mac`, with constant-time verification that refuses a tag of the wrong length, and a constant-time byte comparison for shared secrets such as URL @@ -274,6 +276,34 @@ interoperability and security policy. delivery headers, and body exactly as received, and choose a bounded accepted delivery-time skew for their deployment. +## Standard Webhooks delivery signatures + +`delivery_signature::sign` produces the `webhook-signature` header for the +Standard Webhooks 1.0.0 symmetric scheme. HMAC-SHA-256 +covers `..`, using the exact HTTP body +bytes (up to 1 MiB). The ID is 1 to 256 visible ASCII bytes excluding periods. +The timestamp is unsigned Unix seconds in canonical decimal. + +`DeliveryKey::new` takes 32 to 64 raw bytes, refuses `whsec_` text, and +zeroizes the stored key on drop. A 64-character hex key file supplies 64 +ASCII bytes. A trailing newline would make that file 65 bytes and fail +validation. Within the allowed range, a trailing newline is key material. +The official libraries interpret a text secret as `whsec_` followed by +base64. Give those receivers the raw key file bytes or `whsec_` followed by +the base64 encoding of those exact bytes. `DeliveryKeys::new` accepts a current key and an optional +distinct previous key. Signatures are `v1,`, joined +by one space, with the current key first when rotating. + +Receivers pass the three header values and raw body as `SignedContent`. +Pass `DELIVERY_TOLERANCE` to `verify` to authenticate the delivery with a +300-second window in either direction. Up to four signature +entries are accepted. An empty value invalidates the header, even for an +unknown version. A malformed `v1` entry also invalidates the header. A valid tag under either configured key is sufficient. Callers using +`verify_authenticity` enforce freshness themselves. Callers also own +destination binding and replay handling, including deduplication by webhook ID. + +[Standard Webhooks 1.0.0 specification](https://github.com/standard-webhooks/standard-webhooks/blob/libraries/v1.3.0/spec/standard-webhooks.md) + ## Testing ```sh diff --git a/crates/registry-platform-crypto/src/delivery_signature.rs b/crates/registry-platform-crypto/src/delivery_signature.rs index 538868e333..0c224c60c7 100644 --- a/crates/registry-platform-crypto/src/delivery_signature.rs +++ b/crates/registry-platform-crypto/src/delivery_signature.rs @@ -1,23 +1,28 @@ // SPDX-License-Identifier: Apache-2.0 -//! Version 1 hook delivery signing and verification. +//! Standard Webhooks and Registry Stack Version 1 delivery signatures. //! -//! One HMAC-SHA-256 scheme over the exact wire fields of a signed HTTP hook +//! Both schemes use HMAC-SHA-256 over the exact wire fields of an HTTP hook //! delivery, shared by the product that sends a delivery and the receiver -//! that authenticates one. The scheme carries no product policy: the caller +//! that authenticates one. The caller //! owns the key material, the destination binding, and the freshness window //! it passes as `allowed_skew`. //! //! The signing domain and the length-prefixed field order below are wire //! bytes that deployed receivers already verify, so they keep their Version //! 1 spelling whatever the Rust names around them are. +//! +//! Standard Webhooks symmetric signatures use the separate `sign` and +//! `verify` entry points and authenticate the ID, timestamp, and exact body. use std::time::{Duration, SystemTime}; +use base64::engine::general_purpose::STANDARD; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use hmac::{Hmac, KeyInit as _, Mac as _}; use sha2::Sha256; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; +use zeroize::Zeroizing; /// The Version 1 signing domain, as deployed receivers verify it. /// @@ -228,6 +233,350 @@ fn system_time_unix_nanos(value: SystemTime) -> i128 { } } +/// The Standard Webhooks symmetric signature version. +pub const SIGNATURE_VERSION: &str = "v1"; +/// Maximum length of an exact Standard Webhooks key in bytes. +pub const MAX_HMAC_SHA256_KEY_BYTES: usize = 64; +/// Maximum length of the signed webhook ID in bytes. +pub const MAX_WEBHOOK_ID_BYTES: usize = 256; +/// Maximum number of space-separated signature entries a receiver accepts. +pub const MAX_SIGNATURE_ENTRIES: usize = 4; +/// Recommended freshness window in both directions. +pub const DELIVERY_TOLERANCE: Duration = Duration::from_secs(300); + +const STANDARD_WEBHOOKS_TAG_ENCODED_BYTES: usize = 44; + +/// Validated exact key bytes for Standard Webhooks, zeroized on drop. +pub struct DeliveryKey(Zeroizing>); + +impl DeliveryKey { + /// Validate and retain the exact key bytes. + /// + /// # Errors + /// + /// Refuses keys outside 32 to 64 bytes and text beginning with `whsec_`. + pub fn new(bytes: &[u8]) -> Result { + if bytes.starts_with(b"whsec_") { + return Err(DeliveryKeyError::SecretText); + } + let length = bytes.len(); + if length < MIN_HMAC_SHA256_KEY_BYTES { + return Err(DeliveryKeyError::TooShort { length }); + } + if length > MAX_HMAC_SHA256_KEY_BYTES { + return Err(DeliveryKeyError::TooLong { + length, + trailing_newline: bytes.ends_with(b"\n"), + }); + } + Ok(Self(Zeroizing::new(bytes.to_vec()))) + } +} + +impl std::fmt::Debug for DeliveryKey { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("[REDACTED]") + } +} + +/// Standard Webhooks keys in signing order, with an optional rotation key. +#[derive(Debug)] +pub struct DeliveryKeys { + current: DeliveryKey, + previous: Option, +} + +impl DeliveryKeys { + /// Build the ordered set of signing and verification keys. + /// + /// # Errors + /// + /// Refuses a previous key equal to the current key. + pub fn new( + current: DeliveryKey, + previous: Option, + ) -> Result { + if previous + .as_ref() + .is_some_and(|key| crate::constant_time_eq(¤t.0, &key.0)) + { + return Err(DeliveryKeyError::PreviousEqualsCurrent); + } + Ok(Self { current, previous }) + } + + /// Key used for new deliveries. + pub const fn current(&self) -> &DeliveryKey { + &self.current + } + + /// Rotation key used alongside the current key when configured. + pub const fn previous(&self) -> Option<&DeliveryKey> { + self.previous.as_ref() + } + + fn iter(&self) -> impl Iterator { + std::iter::once(&self.current).chain(self.previous.iter()) + } +} + +/// A Standard Webhooks key policy refusal. +#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +pub enum DeliveryKeyError { + #[error("the delivery key is {length} bytes. The minimum is {MIN_HMAC_SHA256_KEY_BYTES}")] + TooShort { length: usize }, + #[error( + "the delivery key is {length} bytes. The maximum is {MAX_HMAC_SHA256_KEY_BYTES}{}", + if *trailing_newline { " (the last byte is a newline)" } else { "" } + )] + TooLong { + length: usize, + trailing_newline: bool, + }, + #[error("the delivery key starts with whsec_. Supply the exact key bytes")] + SecretText, + #[error("the previous delivery key equals the current delivery key")] + PreviousEqualsCurrent, +} + +impl DeliveryKeyError { + /// Stable machine-readable refusal code. + pub const fn code(&self) -> &'static str { + match self { + Self::TooShort { .. } => "key-too-short", + Self::TooLong { .. } => "key-too-long", + Self::SecretText => "key-is-secret-text", + Self::PreviousEqualsCurrent => "previous-key-equals-current", + } + } +} + +/// Two configuration labels that refer to the same delivery key bytes. +#[derive(Debug, Eq, PartialEq, thiserror::Error)] +#[error( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 \ + new random bytes to another secret and referencing it there." +)] +pub struct DuplicateDeliveryKey { + first: String, + second: String, +} + +impl DuplicateDeliveryKey { + /// Label of the first key with these bytes. + pub fn first(&self) -> &str { + &self.first + } + + /// Label of the repeated key. + pub fn second(&self) -> &str { + &self.second + } + + /// Stable machine-readable refusal code. + pub const fn code(&self) -> &'static str { + "key-repeated" + } +} + +/// Refuse exact key reuse among the supplied configuration labels. +pub fn distinct_delivery_keys<'a>( + keys: impl IntoIterator, +) -> Result<(), DuplicateDeliveryKey> { + let mut seen: Vec<(&str, &DeliveryKey)> = Vec::new(); + for (label, key) in keys { + if let Some((first, _)) = seen + .iter() + .find(|(_, prior)| crate::constant_time_eq(&prior.0, &key.0)) + { + return Err(DuplicateDeliveryKey { + first: (*first).to_owned(), + second: label.to_owned(), + }); + } + seen.push((label, key)); + } + Ok(()) +} + +/// Value-free failure while signing or verifying Standard Webhooks content. +#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +pub enum DeliverySignatureError { + #[error("the webhook ID is invalid")] + InvalidId, + #[error("the webhook timestamp is invalid")] + InvalidTimestamp, + #[error("the webhook timestamp is outside the allowed delivery window")] + StaleDelivery, + #[error("the webhook signature header is malformed")] + MalformedSignature, + #[error("the webhook signature header contains no supported version")] + UnsupportedVersion, + #[error("the webhook signature does not match")] + SignatureMismatch, + #[error("the webhook body exceeds {MAX_BODY_BYTES} bytes")] + BodyTooLarge, +} + +impl DeliverySignatureError { + /// Stable machine-readable refusal code. + pub const fn code(&self) -> &'static str { + match self { + Self::InvalidId => "invalid-id", + Self::InvalidTimestamp => "invalid-timestamp", + Self::StaleDelivery => "stale-delivery", + Self::MalformedSignature => "malformed-signature", + Self::UnsupportedVersion => "unsupported-version", + Self::SignatureMismatch => "signature-mismatch", + Self::BodyTooLarge => "body-too-large", + } + } +} + +/// Exact values from the Standard Webhooks headers and HTTP body. +#[derive(Clone, Copy, Debug)] +pub struct SignedContent<'a> { + /// Exact `webhook-id` header value. + pub id: &'a str, + /// Exact `webhook-timestamp` header value in canonical decimal. + pub timestamp: &'a str, + /// Exact `webhook-signature` header value. + pub signature: &'a str, + /// Exact HTTP body bytes. + pub body: &'a [u8], +} + +/// Produce a Standard Webhooks signature header with the current key first. +pub fn sign( + keys: &DeliveryKeys, + id: &str, + timestamp: u64, + body: &[u8], +) -> Result { + validate_standard_webhooks_input(id, body)?; + let timestamp = timestamp.to_string(); + let mut signature = String::new(); + for key in keys.iter() { + if !signature.is_empty() { + signature.push(' '); + } + let mac = standard_webhooks_mac(&key.0, id, ×tamp, body); + signature.push_str(SIGNATURE_VERSION); + signature.push(','); + STANDARD.encode_string(mac.finalize().into_bytes(), &mut signature); + } + Ok(signature) +} + +/// Authenticate the delivery and enforce the receiver's two-sided clock window. +pub fn verify( + keys: &DeliveryKeys, + content: SignedContent<'_>, + now: SystemTime, + tolerance: Duration, +) -> Result { + let timestamp = verify_authenticity(keys, content)?; + let delivery_nanos = i128::from(timestamp) * 1_000_000_000; + if delivery_nanos.abs_diff(system_time_unix_nanos(now)) > tolerance.as_nanos() { + return Err(DeliverySignatureError::StaleDelivery); + } + Ok(timestamp) +} + +/// Authenticate the exact delivery bytes and return the parsed Unix timestamp. +/// The caller must enforce freshness before using the delivery. +pub fn verify_authenticity( + keys: &DeliveryKeys, + content: SignedContent<'_>, +) -> Result { + validate_standard_webhooks_input(content.id, content.body)?; + let timestamp = parse_webhook_timestamp(content.timestamp)?; + let tags = parse_standard_webhooks_header(content.signature)?; + // Stop at the first matching entry and key. On a signature mismatch, + // compare every decoded tag against every key. Each comparison is constant time. + for key in keys.iter() { + let mac = standard_webhooks_mac(&key.0, content.id, content.timestamp, content.body); + if tags.iter().any(|tag| mac.clone().verify_slice(tag).is_ok()) { + return Ok(timestamp); + } + } + Err(DeliverySignatureError::SignatureMismatch) +} + +fn validate_standard_webhooks_input(id: &str, body: &[u8]) -> Result<(), DeliverySignatureError> { + if id.is_empty() + || id.len() > MAX_WEBHOOK_ID_BYTES + || !id + .bytes() + .all(|byte| byte.is_ascii_graphic() && byte != b'.') + { + return Err(DeliverySignatureError::InvalidId); + } + if body.len() > MAX_BODY_BYTES { + return Err(DeliverySignatureError::BodyTooLarge); + } + Ok(()) +} + +fn parse_webhook_timestamp(timestamp: &str) -> Result { + if timestamp.is_empty() + || timestamp.len() > 20 + || (timestamp.len() > 1 && timestamp.starts_with('0')) + || !timestamp.bytes().all(|byte| byte.is_ascii_digit()) + { + return Err(DeliverySignatureError::InvalidTimestamp); + } + timestamp + .parse() + .map_err(|_| DeliverySignatureError::InvalidTimestamp) +} + +fn parse_standard_webhooks_header( + header: &str, +) -> Result, DeliverySignatureError> { + let malformed = DeliverySignatureError::MalformedSignature; + let mut tags = Vec::new(); + for (index, entry) in header.split(' ').enumerate() { + if index == MAX_SIGNATURE_ENTRIES { + return Err(malformed); + } + let (version, value) = entry.split_once(',').ok_or(malformed)?; + if version.is_empty() || value.is_empty() { + return Err(malformed); + } + if version != SIGNATURE_VERSION { + continue; + } + if value.len() != STANDARD_WEBHOOKS_TAG_ENCODED_BYTES { + return Err(malformed); + } + // STANDARD requires canonical padding and zero unused bits. + let mut tag = [0; HMAC_SHA256_BYTES]; + if STANDARD + .decode_slice(value, &mut tag) + .map_err(|_| malformed)? + != tag.len() + { + return Err(malformed); + } + tags.push(tag); + } + if tags.is_empty() { + return Err(DeliverySignatureError::UnsupportedVersion); + } + Ok(tags) +} + +fn standard_webhooks_mac(key: &[u8], id: &str, timestamp: &str, body: &[u8]) -> HmacSha256 { + let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any length"); + mac.update(id.as_bytes()); + mac.update(b"."); + mac.update(timestamp.as_bytes()); + mac.update(b"."); + mac.update(body); + mac +} + #[cfg(test)] mod tests { use super::*; @@ -451,3 +800,26 @@ mod tests { assert_eq!(sign_v1(KEY, oversized), Err(SigningError::InputTooLarge)); } } + +#[cfg(test)] +mod standard_webhooks_tests { + use super::*; + + #[test] + fn sign_matches_the_published_standard_webhooks_vector() { + let key = base64::engine::general_purpose::STANDARD + .decode("MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw") + .unwrap(); + let mac = standard_webhooks_mac( + &key, + "msg_p5jXN8AQM9LWM0D4loKWxJek", + "1614265330", + br#"{"test": 2432232314}"#, + ); + let tag = base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()); + assert_eq!( + format!("{SIGNATURE_VERSION},{tag}"), + "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=" + ); + } +} diff --git a/crates/registry-platform-crypto/src/lib.rs b/crates/registry-platform-crypto/src/lib.rs index 1e3bfbea2a..10336f60e0 100644 --- a/crates/registry-platform-crypto/src/lib.rs +++ b/crates/registry-platform-crypto/src/lib.rs @@ -116,6 +116,10 @@ pub fn domain_separated_sha256(domain: &[u8], canonical_payload: &[u8]) -> [u8; /// Maximum raw JSON bytes accepted by the JWK parsing boundaries. pub const MAX_JWK_JSON_BYTES: usize = 64 * 1024; + +/// JWK members that carry private or symmetric key material. +pub const PRIVATE_JWK_MEMBERS: [&str; 8] = ["k", "d", "p", "q", "dp", "dq", "qi", "oth"]; + const MAX_DID_JWK_IDENTIFIER_BYTES: usize = MAX_JWK_JSON_BYTES.div_ceil(3) * 4; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -505,7 +509,7 @@ impl<'de> Visitor<'de> for PublicJwkVisitor { "y" => deserialize_optional_jwk_field(&mut map, &mut y, "y")?, "n" => deserialize_optional_jwk_field(&mut map, &mut n, "n")?, "e" => deserialize_optional_jwk_field(&mut map, &mut e, "e")?, - "k" | "d" | "p" | "q" | "dp" | "dq" | "qi" | "oth" => { + name if PRIVATE_JWK_MEMBERS.contains(&name) => { let _: IgnoredAny = map.next_value()?; return Err(de::Error::custom("public JWK contains private material")); } @@ -2129,8 +2133,7 @@ fn algorithm_from_fields( } fn reject_private_members(value: &Value) -> Result<(), JwkError> { - const PRIVATE_MEMBERS: [&str; 8] = ["k", "d", "p", "q", "dp", "dq", "qi", "oth"]; - if PRIVATE_MEMBERS + if PRIVATE_JWK_MEMBERS .iter() .any(|member| value.get(member).is_some()) { @@ -4020,6 +4023,26 @@ mod tests { assert!(matches!(err, JwkError::Invalid(_))); } + #[test] + fn the_private_member_list_is_complete_and_every_member_is_refused_by_parse() { + assert_eq!( + PRIVATE_JWK_MEMBERS, + ["k", "d", "p", "q", "dp", "dq", "qi", "oth"] + ); + for member in PRIVATE_JWK_MEMBERS { + let mut value: Value = serde_json::from_str(&rsa_public_json()).expect("public json"); + value + .as_object_mut() + .expect("object") + .insert(member.to_string(), json!("not-allowed-on-public")); + let json = serde_json::to_string(&value).expect("json serializes"); + assert!( + matches!(PublicJwk::parse(&json), Err(JwkError::Invalid(_))), + "{member} must be refused" + ); + } + } + #[test] fn rsa_private_public_drops_private_members() { let public = PrivateJwk::parse(RSA_JWK) diff --git a/crates/registry-platform-crypto/tests/fixtures/standard-webhooks.json b/crates/registry-platform-crypto/tests/fixtures/standard-webhooks.json new file mode 100644 index 0000000000..eb8c049e89 --- /dev/null +++ b/crates/registry-platform-crypto/tests/fixtures/standard-webhooks.json @@ -0,0 +1,194 @@ +[ + { + "name": "standard-webhooks-published", + "keyHex": "31f290f6bf06298aab4f08d43c3f082cf648a362da2da4b0", + "previousKeyHex": null, + "id": "msg_p5jXN8AQM9LWM0D4loKWxJek", + "timestamp": "1614265330", + "body": "{\"test\": 2432232314}", + "signature": "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=", + "now": 1614265330, + "expected": "accepted", + "keyPolicy": "below-minimum" + }, + { + "name": "minimum-key-32", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "maximum-key-64", + "keyHex": "62383534323132363838313338303364633834373330366435323633303630623234386639623433313235333866393265323630383031336136346537353538", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,ElRhDDgrfjEgz60OqOzVJFpVM/p1jesMC9rp1d+y7eo=", + "now": 1788048001, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "binary-key-with-nul", + "keyHex": "00167724fabcf71cfd25734088c2d78f2a1752806c162eaefb938ce83fbbb5ca", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,TpRn3gnQiaxMqZopxLFEpBM7bCFIJkeK0Dz8GQEZHTU=", + "now": 1788048001, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "rotation-two-signatures", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": "62383534323132363838313338303364633834373330366435323633303630623234386639623433313235333866393265323630383031336136346537353538", + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc= v1,ElRhDDgrfjEgz60OqOzVJFpVM/p1jesMC9rp1d+y7eo=", + "now": 1788048001, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "window-edge-past", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048301, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "window-edge-future", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788047701, + "expected": "accepted", + "keyPolicy": "accepted" + }, + { + "name": "stale-past", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048302, + "expected": "stale-delivery", + "keyPolicy": "accepted" + }, + { + "name": "stale-future", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788047700, + "expected": "stale-delivery", + "keyPolicy": "accepted" + }, + { + "name": "tampered-body", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"changed\":true}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "signature-mismatch", + "keyPolicy": "accepted" + }, + { + "name": "wrong-key", + "keyHex": "00167724fabcf71cfd25734088c2d78f2a1752806c162eaefb938ce83fbbb5ca", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "signature-mismatch", + "keyPolicy": "accepted" + }, + { + "name": "only-unknown-version", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1a,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "unsupported-version", + "keyPolicy": "accepted" + }, + { + "name": "entry-without-comma", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "malformed-signature", + "keyPolicy": "accepted" + }, + { + "name": "five-entries", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc= v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc= v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc= v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc= v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "malformed-signature", + "keyPolicy": "accepted" + }, + { + "name": "id-with-period", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg.invalid", + "timestamp": "1788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,q/75952XVYxh486xxL8vIQtjwZYp4c2RR6L22FnQ6ME=", + "now": 1788048001, + "expected": "invalid-id", + "keyPolicy": "accepted" + }, + { + "name": "timestamp-leading-zero", + "keyHex": "59a84205af9652d98932807295fba5d3d65fb8ec431d34c7263c9b1052a24eed", + "previousKeyHex": null, + "id": "msg_example", + "timestamp": "01788048001", + "body": "{\"type\":\"record.created\",\"data\":{\"label\":\"École\"}}", + "signature": "v1,Gv1ZaF7sZP2GVaqfJF1XciiHT4PkHTcV9UQ28upx0Tc=", + "now": 1788048001, + "expected": "invalid-timestamp", + "keyPolicy": "accepted" + } +] diff --git a/crates/registry-platform-crypto/tests/standard_webhooks.rs b/crates/registry-platform-crypto/tests/standard_webhooks.rs new file mode 100644 index 0000000000..966828b35f --- /dev/null +++ b/crates/registry-platform-crypto/tests/standard_webhooks.rs @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: Apache-2.0 +use std::time::{Duration, SystemTime}; + +use proptest::prelude::*; +use registry_platform_crypto::delivery_signature::*; +use serde::Deserialize; + +const BODY: &[u8] = b"{\"ok\":true}"; +const ID: &str = "msg_demo"; +const TIMESTAMP: u64 = 1_788_048_001; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Vector { + name: String, + key_hex: String, + previous_key_hex: Option, + id: String, + timestamp: String, + body: String, + signature: String, + now: u64, + expected: String, + key_policy: String, +} + +fn from_hex(value: &str) -> Vec { + (0..value.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&value[index..index + 2], 16).unwrap()) + .collect() +} + +fn key(byte: u8) -> DeliveryKey { + DeliveryKey::new(&[byte; 32]).unwrap() +} + +fn keys() -> DeliveryKeys { + DeliveryKeys::new(key(1), None).unwrap() +} + +fn content(signature: &str) -> SignedContent<'_> { + SignedContent { + id: ID, + timestamp: "1788048001", + signature, + body: BODY, + } +} + +fn at(seconds: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(seconds) +} + +#[test] +fn shared_vectors_sign_and_verify() { + let vectors: Vec = + serde_json::from_str(include_str!("fixtures/standard-webhooks.json")).unwrap(); + for vector in vectors { + let current = DeliveryKey::new(&from_hex(&vector.key_hex)); + if vector.key_policy == "below-minimum" { + assert_eq!( + current.unwrap_err(), + DeliveryKeyError::TooShort { length: 24 } + ); + continue; + } + assert_eq!(vector.key_policy, "accepted"); + let previous = vector + .previous_key_hex + .map(|hex| DeliveryKey::new(&from_hex(&hex)).unwrap()); + let keys = DeliveryKeys::new(current.unwrap(), previous).unwrap(); + let signed = SignedContent { + id: &vector.id, + timestamp: &vector.timestamp, + signature: &vector.signature, + body: vector.body.as_bytes(), + }; + let result = verify(&keys, signed, at(vector.now), DELIVERY_TOLERANCE); + if vector.expected == "accepted" { + let timestamp = vector.timestamp.parse().unwrap(); + assert_eq!(result, Ok(timestamp), "{}", vector.name); + assert_eq!( + sign(&keys, &vector.id, timestamp, vector.body.as_bytes()).unwrap(), + vector.signature, + "{}", + vector.name + ); + } else { + assert_eq!( + result.unwrap_err().code(), + vector.expected, + "{}", + vector.name + ); + } + } +} + +#[test] +fn a_key_below_32_bytes_is_refused_even_though_the_published_vector_uses_one() { + let error = DeliveryKey::new(&[0; 24]).unwrap_err(); + assert_eq!(error, DeliveryKeyError::TooShort { length: 24 }); + assert_eq!(error.code(), "key-too-short"); + assert!(error.to_string().contains("24")); +} + +#[test] +fn a_key_above_64_bytes_names_its_length_and_trailing_newline() { + let mut bytes = [b'a'; 65]; + bytes[64] = b'\n'; + let error = DeliveryKey::new(&bytes).unwrap_err(); + assert_eq!( + error, + DeliveryKeyError::TooLong { + length: 65, + trailing_newline: true + } + ); + assert_eq!(error.code(), "key-too-long"); + assert!(error.to_string().contains("65")); + assert!(error.to_string().contains("newline")); + assert_eq!( + DeliveryKey::new(&[0; 65]).unwrap_err(), + DeliveryKeyError::TooLong { + length: 65, + trailing_newline: false + } + ); +} + +#[test] +fn whsec_text_is_refused_as_key_material() { + let error = DeliveryKey::new(b"whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap_err(); + assert_eq!(error, DeliveryKeyError::SecretText); + assert_eq!(error.code(), "key-is-secret-text"); +} + +#[test] +fn two_keys_sign_two_entries_current_first() { + let rotated = DeliveryKeys::new(key(1), Some(key(2))).unwrap(); + let previous = DeliveryKeys::new(key(2), None).unwrap(); + let first = sign(&keys(), ID, TIMESTAMP, BODY).unwrap(); + let second = sign(&previous, ID, TIMESTAMP, BODY).unwrap(); + assert_eq!( + sign(&rotated, ID, TIMESTAMP, BODY).unwrap(), + format!("{first} {second}") + ); +} + +#[test] +fn a_rotated_signature_verifies_under_either_key() { + let rotated = DeliveryKeys::new(key(1), Some(key(2))).unwrap(); + let header = sign(&rotated, ID, TIMESTAMP, BODY).unwrap(); + for byte in [1, 2] { + let single = DeliveryKeys::new(key(byte), None).unwrap(); + assert_eq!( + verify_authenticity(&single, content(&header)), + Ok(TIMESTAMP) + ); + let single_header = sign(&single, ID, TIMESTAMP, BODY).unwrap(); + assert_eq!( + verify_authenticity(&rotated, content(&single_header)), + Ok(TIMESTAMP) + ); + } +} + +#[test] +fn a_previous_key_equal_to_the_current_key_is_refused() { + let error = DeliveryKeys::new(key(1), Some(key(1))).unwrap_err(); + assert_eq!(error, DeliveryKeyError::PreviousEqualsCurrent); + assert_eq!(error.code(), "previous-key-equals-current"); +} + +#[test] +fn unknown_versions_are_skipped_and_no_v1_is_unsupported() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + assert_eq!( + verify_authenticity(&keys, content(&format!("v1a,opaque {header} v2,opaque"))), + Ok(TIMESTAMP) + ); + assert_eq!( + verify_authenticity(&keys, content("v1a,opaque")), + Err(DeliverySignatureError::UnsupportedVersion) + ); +} + +#[test] +fn more_than_four_entries_is_malformed() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + assert_eq!( + verify_authenticity(&keys, content(&format!("{header} v2,a v2,b v2,c"))), + Ok(TIMESTAMP) + ); + assert_eq!( + verify_authenticity(&keys, content(&format!("{header} v2,a v2,b v2,c v2,d"))), + Err(DeliverySignatureError::MalformedSignature) + ); +} + +#[test] +fn malformed_entries_refuse_the_entire_header() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + for malformed in [ + String::new(), + format!(" {header}"), + format!("{header} v2,opaque"), + format!("{header} broken"), + format!("{header} {}", header.trim_end_matches('=')), + format!("{header} v1,{}B=", "A".repeat(42)), + format!("{header} v1,{}=", "_".repeat(43)), + format!("{header} v1,"), + ] { + assert_eq!( + verify_authenticity(&keys, content(&malformed)), + Err(DeliverySignatureError::MalformedSignature) + ); + } +} + +#[test] +fn the_window_is_300_seconds_in_both_directions() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + assert_eq!(DELIVERY_TOLERANCE, Duration::from_secs(300)); + let timestamp = at(TIMESTAMP); + for edge in [ + timestamp - DELIVERY_TOLERANCE, + timestamp + DELIVERY_TOLERANCE, + ] { + assert_eq!( + verify(&keys, content(&header), edge, DELIVERY_TOLERANCE), + Ok(TIMESTAMP) + ); + } + let outside = DELIVERY_TOLERANCE + Duration::from_nanos(1); + for stale in [timestamp - outside, timestamp + outside] { + assert_eq!( + verify(&keys, content(&header), stale, DELIVERY_TOLERANCE), + Err(DeliverySignatureError::StaleDelivery) + ); + } +} + +#[test] +fn ids_with_a_period_or_a_space_are_refused() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + for id in ["has.period", "has space", "", "é", "\x7f", &"x".repeat(257)] { + assert_eq!( + sign(&keys, id, TIMESTAMP, BODY), + Err(DeliverySignatureError::InvalidId) + ); + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + id, + ..content(&header) + } + ), + Err(DeliverySignatureError::InvalidId) + ); + } + assert!(sign(&keys, &"~".repeat(MAX_WEBHOOK_ID_BYTES), TIMESTAMP, BODY).is_ok()); +} + +#[test] +fn timestamps_must_be_canonical_decimal() { + let keys = keys(); + let header = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + for timestamp in [ + "", + "00", + "01", + "+1", + "-1", + " 1", + "1\t", + "١", + "18446744073709551616", + "111111111111111111111", + ] { + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + timestamp, + ..content(&header) + } + ), + Err(DeliverySignatureError::InvalidTimestamp) + ); + } + for value in [0, u64::MAX] { + let timestamp = value.to_string(); + let signature = sign(&keys, ID, value, BODY).unwrap(); + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + timestamp: ×tamp, + ..content(&signature) + } + ), + Ok(value) + ); + } +} + +#[test] +fn body_bounds_apply_to_signing_and_verification() { + let keys = keys(); + let body = vec![0xFF; MAX_BODY_BYTES + 1]; + let signature = sign(&keys, ID, TIMESTAMP, &body[..MAX_BODY_BYTES]).unwrap(); + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + body: &body[..MAX_BODY_BYTES], + ..content(&signature) + } + ), + Ok(TIMESTAMP) + ); + assert_eq!( + verify_authenticity( + &keys, + SignedContent { + body: &body, + ..content(&signature) + } + ), + Err(DeliverySignatureError::BodyTooLarge) + ); + assert_eq!( + sign(&keys, ID, TIMESTAMP, &body), + Err(DeliverySignatureError::BodyTooLarge) + ); +} + +#[test] +fn distinct_delivery_keys_names_both_paths() { + let first = key(b'x'); + let second = key(b'y'); + let same = key(b'x'); + distinct_delivery_keys([("one.current", &first), ("one.previous", &second)]).unwrap(); + let error = distinct_delivery_keys([ + ("one.current", &first), + ("one.previous", &second), + ("two.previous", &same), + ]) + .unwrap_err(); + assert_eq!(error.code(), "key-repeated"); + let message = error.to_string(); + assert_eq!( + message, + "one.current and two.previous resolve to the same key bytes. Give two.previous its own \ + key by writing 32 new random bytes to another secret and referencing it there." + ); + assert!(!message.contains(&"x".repeat(32))); +} + +#[test] +fn debug_redacts_delivery_keys() { + assert_eq!(format!("{:?}", key(b'x')), "[REDACTED]"); + assert_eq!( + format!( + "{:?}", + DeliveryKeys::new(key(b'x'), Some(key(b'y'))).unwrap() + ), + "DeliveryKeys { current: [REDACTED], previous: Some([REDACTED]) }" + ); +} + +#[test] +fn verifies_freshness_at_extreme_timestamps_without_panicking() { + let keys = DeliveryKeys::new(key(1), None).unwrap(); + for (timestamp, now) in [ + (u64::MAX, SystemTime::UNIX_EPOCH), + (TIMESTAMP, SystemTime::UNIX_EPOCH - Duration::from_secs(1)), + ] { + let signature = sign(&keys, ID, timestamp, BODY).unwrap(); + let result = verify( + &keys, + SignedContent { + id: ID, + timestamp: ×tamp.to_string(), + signature: &signature, + body: BODY, + }, + now, + DELIVERY_TOLERANCE, + ); + assert_eq!(result, Err(DeliverySignatureError::StaleDelivery)); + } +} + +fn signature_entries() -> impl Strategy> { + let version = + prop_oneof![Just("v1"), Just("v1a"), Just("v2"), Just("")].prop_map(str::to_owned); + let value = prop_oneof![ + 4 => "[A-Za-z0-9+/=_,-]{44}", + 1 => "[A-Za-z0-9+/=_,-]{0,46}", + ]; + proptest::collection::vec((version, value), 1..=6) +} + +proptest! { + #[test] + fn a_structured_signature_header_only_authenticates_with_a_real_tag( + entries in signature_entries(), + real_entry in proptest::option::of(0usize..6), + double_space in any::(), + ) { + let keys = DeliveryKeys::new(key(1), None).unwrap(); + let signature = sign(&keys, ID, TIMESTAMP, BODY).unwrap(); + let mut entries: Vec<_> = entries.into_iter().map(|(version, value)| { + format!("{version},{value}") + }).collect(); + if let Some(index) = real_entry { + let slot = index % entries.len(); + entries[slot].clone_from(&signature); + } + let header = entries.join(if double_space { " " } else { " " }); + let result = verify_authenticity(&keys, SignedContent { + id: ID, timestamp: &TIMESTAMP.to_string(), signature: &header, body: BODY, + }); + prop_assert!(result.is_err() || entries.contains(&signature)); + } + + #[test] + fn the_signature_header_parser_never_panics_and_round_trips( + arbitrary_header in any::(), + id in "[a-zA-Z0-9_-]{1,256}", + timestamp in any::(), + body in proptest::collection::vec(any::(), 0..1024), + rotate in any::(), + ) { + let keys = DeliveryKeys::new(key(1), rotate.then(|| key(2))).unwrap(); + let signature = sign(&keys, &id, timestamp, &body).unwrap(); + let timestamp_text = timestamp.to_string(); + let signed = SignedContent { id: &id, timestamp: ×tamp_text, signature: &signature, body: &body }; + let _ = verify_authenticity(&keys, SignedContent { signature: &arbitrary_header, ..signed }); + prop_assert_eq!(verify_authenticity(&keys, signed), Ok(timestamp)); + } +} diff --git a/crates/registry-platform-hooks/README.md b/crates/registry-platform-hooks/README.md index 694fb62aca..6ff520bdc0 100644 --- a/crates/registry-platform-hooks/README.md +++ b/crates/registry-platform-hooks/README.md @@ -29,10 +29,7 @@ stay with the owning product. - The envelope: one canonical JSON document (RFC 8785 through `registry-platform-canonical-json`) with `id`, `type`, `source`, `time`, `subject`, `dataschema`, `data`, and `causation` (`root`, `parent`, `hop`). - Delivery attributes (`attempt`, `generation`, `delivery_time`, - `idempotency_key`, `signature`) are explicitly not envelope fields; they stay - on the transport headers. The envelope is what the handler reasons over; the - attributes are what the worker reasons over. `id`, `causation.root`, and + `id`, `causation.root`, and `causation.parent` are UUIDs and the closed subject is either `{recordReference, recordRevision}` or `{proposalReference, proposalRevision}`, with its revision greater than zero, refused on both @@ -53,7 +50,7 @@ stay with the owning product. ## Budgets -- The envelope carries the 1 MiB Version 1 signable bound (1,048,576 bytes, +- The envelope carries the 1 MiB delivery signature bound (1,048,576 bytes, the delivery signature's `MAX_BODY_BYTES`), so every envelope can be signed and verified. The delivery store's 2 MiB payload column is a looser outer bound. A per-delivery bound can only tighten it: @@ -113,9 +110,35 @@ work, a dead letter, or an expired lease under its exact generation. Discard never rebinds or sends the work, refuses a live lease or recovered proposal receipt, and preserves the shared envelope while another delivery needs it. -The simple URL hook destination block, `UrlHookDestinationConfig` (a `url`, an -`hmacSha256KeyRef`, and a delivery budget), is defined in -`registry-platform-config` and re-exported from `delivery`. +A URL delivery posts the canonical envelope with `accept: application/json`, +`content-type: application/json`, `webhook-id`, `webhook-timestamp`, and +`webhook-signature`. The envelope id stays the same across retries and operator +replays and is the receiver's idempotency key. The timestamp is the attempt's +lease time in Unix seconds from the database clock. Database clock skew +counts against the receiver's freshness window. The signature covers the id, +timestamp, and exact body bytes, joined by periods. It carries one `v1,` HMAC-SHA256 entry +per active signing key, current first, separated by a single space. Each key +contains 32 to 64 exact secret bytes. Activation of a shared URL destination +inventory refuses key reuse across current and previous keys. Adding or +removing the previous key leaves the binding digest intact. To rotate, +keep the current reference `hmacSha256KeyRef` unchanged and write the new +bytes behind it. Store the old bytes separately and set +`previousHmacSha256KeyRef` to that secret. Changing the current reference +changes the binding digest and prevents delivery of work retained under +the earlier binding. + +With the `receiver` feature, `verify_hook_delivery` checks that each required +header occurs once, requires the JSON content type, verifies the signature, +and decodes the canonical envelope. It requires the envelope id to +match `webhook-id`. Freshness is checked under `DeliveryFreshness::Within`, +with a default window of 300 seconds in either direction. Callers using +`CallerEnforced` check the timestamp themselves. Receivers deduplicate on +`webhook-id` per endpoint and own source trust and handler effects. + +The simple URL hook destination block, `UrlHookDestinationConfig`, defines +`url`, `hmacSha256KeyRef`, optional `previousHmacSha256KeyRef`, and a delivery +budget. It is defined in `registry-platform-config` and re-exported from +`delivery`. `activate_url_hook_destinations` turns a map of them into signing destinations under a fixed outbound policy (https, or http on a loopback host, no private address range, no client certificate) and records the binding digest. Scheduling diff --git a/crates/registry-platform-hooks/src/delivery/destination.rs b/crates/registry-platform-hooks/src/delivery/destination.rs index cb57025b27..788a125c9e 100644 --- a/crates/registry-platform-hooks/src/delivery/destination.rs +++ b/crates/registry-platform-hooks/src/delivery/destination.rs @@ -1,27 +1,25 @@ // SPDX-License-Identifier: Apache-2.0 //! The `url` handler kind's destination: one activated logical destination, -//! its signing key, and the bounded send that reads the answer back. +//! its signing keys, and the bounded send that reads the answer back. //! //! The product builds the outbound policy (its network profile, DNS family, //! private ranges, and TLS material are deployment configuration it owns) and //! hands it here with the rest of the binding. From then on every product -//! signs, renders, sends, and reads an answer the same way: the Version 1 -//! delivery signature over `POST` and `application/json`, the closed event -//! request template, and a 2xx body read under the handler output ceiling. +//! signs and renders the canonical event with Standard Webhooks, then reads +//! a 2xx response body under the handler output ceiling. use std::fmt; use std::sync::Arc; use std::time::Duration; -use registry_platform_config::{ProtectedSecret, MAX_SECRET_BYTES}; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; +use registry_platform_crypto::delivery_signature::{sign, DeliveryKeys}; use registry_platform_httputil::destination::{ DestinationProfile, DestinationRequestError, DestinationResponseError, DestinationSendError, - EventDeliveryHeaders, EventDestinationPolicy, EventDestinationRequest, - EventDestinationRequestTemplate, MAX_DESTINATION_REQUEST_HEADER_BYTES, - MAX_DESTINATION_TARGET_BYTES, + EventDestinationPolicy, EventDestinationRequest, EventDestinationRequestTemplate, + SignedEventHeaders, MAX_DESTINATION_REQUEST_HEADER_BYTES, MAX_DESTINATION_TARGET_BYTES, }; +use registry_platform_httputil::loopback::loopback_host; use url::Url; use super::seams::{ @@ -31,7 +29,7 @@ use super::seams::{ use crate::{ErrorCategory, MAX_OUTPUT_BYTES}; /// The shortest HMAC-SHA256 delivery key a destination accepts. -pub const MIN_HMAC_SHA256_KEY_BYTES: usize = 32; +pub use registry_platform_crypto::delivery_signature::MIN_HMAC_SHA256_KEY_BYTES; /// Value-free refusal while building a [`UrlDestination`]. #[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] @@ -40,25 +38,20 @@ pub enum UrlDestinationError { /// request template. #[error("the hook destination binding is invalid")] InvalidBinding, - /// The resolved HMAC-SHA256 key is shorter than - /// [`MIN_HMAC_SHA256_KEY_BYTES`] or longer than the secret ceiling. - #[error("the hook destination signing material is invalid")] - InvalidSigningMaterial, } /// Everything one activated `url` destination is built from. pub struct UrlDestinationParts { /// The product's digest of this destination's non-secret binding. pub binding_digest: String, - /// The exact request target the template sends to and the signature - /// covers. + /// The exact request target the template sends to. pub request_target: String, /// The only outbound authority for this logical destination. pub policy: EventDestinationPolicy, /// The largest envelope this destination is sent. pub maximum_payload_bytes: usize, - /// The resolved HMAC-SHA256 delivery key. - pub hmac_sha256_key: ProtectedSecret, + /// The validated delivery keys, in signing order. + pub keys: DeliveryKeys, /// The deployed per-attempt timeout. pub attempt_timeout: Duration, /// The deployed attempt ceiling. @@ -71,20 +64,19 @@ pub struct UrlDestination { request_target: String, policy: Arc, request_template: EventDestinationRequestTemplate, - hmac_sha256_key: ProtectedSecret, + keys: DeliveryKeys, attempt_timeout: Duration, maximum_attempts: u8, } impl UrlDestination { - /// Build the destination, refusing a request target or payload ceiling - /// the closed template refuses, then a key outside its length bounds. + /// Build the destination with a closed signed event template. /// /// # Errors /// /// [`UrlDestinationError`] names which part was refused, never a value. pub fn new(parts: UrlDestinationParts) -> Result { - let request_template = EventDestinationRequestTemplate::event_delivery( + let request_template = EventDestinationRequestTemplate::signed_event_delivery( &parts.request_target, parts.maximum_payload_bytes, MAX_DESTINATION_TARGET_BYTES @@ -92,15 +84,12 @@ impl UrlDestination { + parts.maximum_payload_bytes, ) .map_err(|_| UrlDestinationError::InvalidBinding)?; - if !(MIN_HMAC_SHA256_KEY_BYTES..=MAX_SECRET_BYTES).contains(&parts.hmac_sha256_key.len()) { - return Err(UrlDestinationError::InvalidSigningMaterial); - } Ok(Self { binding_digest: parts.binding_digest, request_target: parts.request_target, policy: Arc::new(parts.policy), request_template, - hmac_sha256_key: parts.hmac_sha256_key, + keys: parts.keys, attempt_timeout: parts.attempt_timeout, maximum_attempts: parts.maximum_attempts, }) @@ -124,16 +113,15 @@ impl UrlDestination { &self.request_template } - /// Borrow the exact request target the template and the signature share, - /// so signing and transport cannot disagree about the path. + /// Borrow the exact request target the template sends to. #[must_use] pub fn request_target(&self) -> &str { &self.request_target } - /// Borrow signing bytes only for the duration of the supplied operation. - pub fn with_hmac_sha256_key(&self, use_key: impl FnOnce(&[u8]) -> T) -> T { - use_key(self.hmac_sha256_key.expose_secret()) + /// Signing keys for comparison across destinations, with their bytes kept private. + pub fn keys(&self) -> &DeliveryKeys { + &self.keys } /// Deployed per-attempt timeout. @@ -157,7 +145,7 @@ impl fmt::Debug for UrlDestination { .field("request_target", &"[REDACTED]") .field("policy", &self.policy) .field("request_template", &self.request_template) - .field("hmac_sha256_key", &"[REDACTED]") + .field("keys", &"[REDACTED]") .field("attempt_timeout", &self.attempt_timeout) .field("maximum_attempts", &self.maximum_attempts) .finish() @@ -187,48 +175,16 @@ impl HookDestination for SharedUrlDestination { &self, fields: DeliverySignatureFields<'_>, ) -> Result { - let DeliverySignatureFields { - id, - source, - event_type, - time, - data_schema, - generation, - attempt, - delivery_time, - idempotency_key, - body, - } = fields; - self.0 - .with_hmac_sha256_key(|key| { - sign_v1( - key, - SignatureFields { - id, - source, - event_type, - time, - data_schema, - generation, - attempt, - delivery_time, - method: "POST", - request_target: self.0.request_target(), - content_type: "application/json", - idempotency_key, - body, - }, - ) - }) + sign(self.0.keys(), fields.id, fields.timestamp, fields.body) .map_err(|_| DeliverySignatureRefused) } fn render_delivery( &self, - headers: EventDeliveryHeaders<'_>, + headers: SignedEventHeaders<'_>, body: Vec, ) -> Result { - self.0.request_template().render_event(headers, body) + self.0.request_template().render_signed_event(headers, body) } async fn send_delivery( @@ -305,13 +261,8 @@ pub fn url_destination_address( } let profile = match parsed.scheme() { "https" => DestinationProfile::ProductionHttps, - "http" - if matches!( - parsed.host_str(), - Some("127.0.0.1") | Some("localhost") | Some("[::1]") - ) => - { - DestinationProfile::LoopbackDevelopmentHttp + "http" if parsed.host_str().and_then(loopback_host).is_some() => { + DestinationProfile::LoopbackHttp } _ => return Err(UrlDestinationError::InvalidBinding), }; @@ -345,90 +296,71 @@ mod tests { .expect("policy") } - /// Resolve `length` key bytes through the real secret path, under an - /// environment name unique to the length so parallel tests never race. - fn key(length: usize) -> ProtectedSecret { - let name = format!("REGISTRY_PLATFORM_HOOKS_DESTINATION_TEST_KEY_{length}"); - std::env::set_var(&name, "k".repeat(length)); - registry_platform_config::SecretResolver::new( - [registry_platform_config::SecretProvider::Environment], - "/", - ) - .expect("resolver") - .resolve(&format!("secret:env/{name}")) - .expect("key") + fn keys(length: usize) -> DeliveryKeys { + use registry_platform_crypto::delivery_signature::DeliveryKey; + DeliveryKeys::new(DeliveryKey::new(&vec![b'k'; length]).unwrap(), None).unwrap() } - fn parts(key: ProtectedSecret) -> UrlDestinationParts { + fn parts(keys: DeliveryKeys) -> UrlDestinationParts { UrlDestinationParts { binding_digest: "sha256:binding".to_owned(), request_target: "/hooks".to_owned(), policy: policy(), maximum_payload_bytes: 16 * 1024, - hmac_sha256_key: key, + keys, attempt_timeout: Duration::from_secs(5), maximum_attempts: 3, } } - #[test] - fn destination_refuses_signing_keys_outside_their_bounds() { - assert_eq!( - UrlDestination::new(parts(key(MIN_HMAC_SHA256_KEY_BYTES - 1))).unwrap_err(), - UrlDestinationError::InvalidSigningMaterial - ); - let destination = - UrlDestination::new(parts(key(MIN_HMAC_SHA256_KEY_BYTES))).expect("destination"); - assert_eq!(destination.request_target(), "/hooks"); - assert_eq!(destination.maximum_attempts(), 3); - } - #[test] fn destination_debug_redacts_the_key_and_target() { - let destination = UrlDestination::new(parts(key(33))).expect("destination"); + let destination = UrlDestination::new(parts(keys(33))).expect("destination"); let rendered = format!("{destination:?}"); assert!(rendered.contains("[REDACTED]")); assert!(!rendered.contains("/hooks")); } #[test] - fn destination_signature_covers_post_and_json_over_the_request_target() { + fn a_hook_delivery_signs_id_timestamp_and_the_exact_body() { + use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, SignedContent, DELIVERY_TOLERANCE, + }; let destination = SharedUrlDestination(Arc::new( - UrlDestination::new(parts(key(33))).expect("destination"), + UrlDestination::new(parts(keys(33))).expect("destination"), )); - let fields = || DeliverySignatureFields { + let signed = destination + .sign_delivery(DeliverySignatureFields { + id: "event", + timestamp: 1000, + body: br#"{"ok":true}"#, + }) + .unwrap(); + let keys = DeliveryKeys::new(DeliveryKey::new(&[b'k'; 33]).unwrap(), None).unwrap(); + let now = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1000); + let content = SignedContent { id: "event", - source: "urn:source", - event_type: "record.created", - time: "2026-01-01T00:00:00Z", - data_schema: "urn:schema", - generation: "1", - attempt: "1", - delivery_time: "2026-01-01T00:00:01Z", - idempotency_key: "key", - body: b"{}", + timestamp: "1000", + signature: &signed, + body: br#"{"ok":true}"#, }; - let signed = destination.sign_delivery(fields()).expect("signed"); - let expected = sign_v1( - "k".repeat(33).as_bytes(), - SignatureFields { - id: "event", - source: "urn:source", - event_type: "record.created", - time: "2026-01-01T00:00:00Z", - data_schema: "urn:schema", - generation: "1", - attempt: "1", - delivery_time: "2026-01-01T00:00:01Z", - method: "POST", - request_target: "/hooks", - content_type: "application/json", - idempotency_key: "key", - body: b"{}", + assert_eq!(verify(&keys, content, now, DELIVERY_TOLERANCE), Ok(1000)); + for changed in [ + SignedContent { + id: "other", + ..content }, - ) - .expect("expected"); - assert_eq!(signed, expected); + SignedContent { + timestamp: "1001", + ..content + }, + SignedContent { + body: br#"{ "ok":true }"#, + ..content + }, + ] { + assert!(verify(&keys, changed, now, DELIVERY_TOLERANCE).is_err()); + } } #[test] @@ -459,7 +391,7 @@ mod tests { assert_eq!(address.profile, DestinationProfile::ProductionHttps); let address = url_destination_address("http://127.0.0.1:9000/in").expect("loopback"); assert_eq!(address.request_target, "/in"); - assert_eq!(address.profile, DestinationProfile::LoopbackDevelopmentHttp); + assert_eq!(address.profile, DestinationProfile::LoopbackHttp); for refused in [ "http://hooks.example/in", "https://user@hooks.example/in", @@ -475,4 +407,38 @@ mod tests { ); } } + + #[test] + fn url_address_follows_the_shared_loopback_definition() { + for admitted in [ + "http://127.0.0.1:9000/in", + "http://127.0.0.2:9000/in", + "http://[::1]:9000/in", + "http://[::ffff:127.0.0.1]:9000/in", + "http://localhost:9000/in", + "http://LOCALHOST:9000/in", + ] { + let address = url_destination_address(admitted).expect(admitted); + assert_eq!( + address.profile, + DestinationProfile::LoopbackHttp, + "{admitted}" + ); + } + for refused in [ + "http://localhost.:9000/in", + "http://hooks.localhost:9000/in", + "http://127.0.0.1.example:9000/in", + "http://0.0.0.0:9000/in", + "http://[::]:9000/in", + "http://10.0.0.1:9000/in", + "http://[::ffff:10.0.0.1]:9000/in", + ] { + assert_eq!( + url_destination_address(refused), + Err(UrlDestinationError::InvalidBinding), + "{refused}" + ); + } + } } diff --git a/crates/registry-platform-hooks/src/delivery/identity.rs b/crates/registry-platform-hooks/src/delivery/identity.rs index 7d7370fc83..3fe0f2a5a5 100644 --- a/crates/registry-platform-hooks/src/delivery/identity.rs +++ b/crates/registry-platform-hooks/src/delivery/identity.rs @@ -9,7 +9,7 @@ //! A runtime left running across an activation then stops delivering rather //! than serving work under a package that is no longer active. -use registry_platform_activation::{check_active_package, Layout}; +use registry_platform_activation::{check_active_package_without_posture, Layout}; use tokio_postgres::Transaction; use super::seams::DeliveryError; @@ -45,7 +45,7 @@ pub async fn verify_active_package( ) .await .map_err(|_| DeliveryError::Unavailable)?; - check_active_package(transaction, layout, database_id, package_digest) + check_active_package_without_posture(transaction, layout, database_id, package_digest) .await .map(drop) .map_err(|_| DeliveryError::Unavailable) diff --git a/crates/registry-platform-hooks/src/delivery/mod.rs b/crates/registry-platform-hooks/src/delivery/mod.rs index 7fce840970..76cd32c56f 100644 --- a/crates/registry-platform-hooks/src/delivery/mod.rs +++ b/crates/registry-platform-hooks/src/delivery/mod.rs @@ -6,14 +6,10 @@ //! The worker claims due deliveries under `FOR UPDATE SKIP LOCKED` leases, //! reaps expired leases, expires retained payloads, schedules retries from //! the per-delivery frozen retry profile, dead-letters exhausted work, and -//! offers bounded operator status and replay. This is the moved delivery -//! core, not a new design: claim, lease/CAS, reaping, retry scheduling, -//! dead-lettering, expiry, replay, attempt-budget accounting, idempotency-key -//! construction, and transport-vs-deadline classification keep their -//! behavior, and the worker sends the captured envelope bytes unchanged. The -//! stored payload is one [`crate::HookEnvelope`] in canonical form; the worker -//! re-reads it before every attempt and refuses a row whose headers would -//! disagree with the body it is about to sign. +//! offers bounded operator status and replay. It validates the retained +//! canonical envelope against the claim and sends its bytes unchanged. +//! Standard Webhooks signs the claimed event ID, the lease's attempt +//! timestamp, and the exact envelope bytes. //! //! A delivery row names the kind of handler that answers it. For the `url` //! kind the worker signs and sends, and the bounded response body is the @@ -28,17 +24,17 @@ //! applied, refused, or dead-lettered. //! //! Everything product-owned enters through [`DeliverySeams`]: the key -//! material, the idempotency domain, the audit journal, the operational-event +//! material, the audit journal, the operational-event //! vocabulary, the registry identity preflight, and the activated //! destinations. The pieces every product fills the same way live beside the //! seams so no product re-implements them: the `url` destination -//! ([`UrlDestination`]: Version 1 signing, the closed request template, and +//! ([`UrlDestination`]: Standard Webhooks signing, the closed request template, and //! the bounded answer read), the pooled connection, the uninhabited //! [`NoLocalHandler`], the audit words and entry shape //! ([`hook_audit_entry`]), and the activation-record identity preflight //! ([`verify_active_package`]). The library carries no product //! name and no product policy; [`DeliveryConfig`] carries the product's -//! schema name, idempotency domain, and delivery source identity. +//! schema name and delivery source identity. mod audit; mod connection; diff --git a/crates/registry-platform-hooks/src/delivery/seams.rs b/crates/registry-platform-hooks/src/delivery/seams.rs index c5633eafbe..3e4d1f0964 100644 --- a/crates/registry-platform-hooks/src/delivery/seams.rs +++ b/crates/registry-platform-hooks/src/delivery/seams.rs @@ -6,9 +6,8 @@ //! //! Everything product-owned enters here, and it enters through one trait so a //! product implements its side as a unit. The worker carries no product name -//! and no product policy: the signing scheme and its key material, the -//! idempotency domain, the audit vocabulary, the operational vocabulary, and -//! the identity check all stay with the product, expressed as the neutral +//! and no product policy: the destination and its key material, the audit vocabulary, +//! the operational vocabulary, and the identity check stay with the product, expressed as the neutral //! contracts below. use std::ops::DerefMut; @@ -16,7 +15,7 @@ use std::time::Duration; use async_trait::async_trait; use registry_platform_httputil::destination::{ - DestinationRequestError, DestinationSendError, EventDeliveryHeaders, EventDestinationRequest, + DestinationRequestError, DestinationSendError, EventDestinationRequest, SignedEventHeaders, }; use tokio_postgres::Transaction; use uuid::Uuid; @@ -205,10 +204,7 @@ pub trait DeliverySeams: Send + Sync + 'static { /// One activated delivery destination, resolved by the product for a /// compiled logical destination id. /// -/// Signing and sending stay with the product: the key material never leaves -/// the destination, and the product's mapping fills the signature's method, -/// request target, and content type from the same binding the transport -/// uses, so signing and transport cannot disagree. +/// The destination signs and sends each attempt using its activated keys. #[async_trait] pub trait HookDestination: Send + Sync { /// Digest of the exact binding this destination was activated under. @@ -220,7 +216,7 @@ pub trait HookDestination: Send + Sync { /// Deployed maximum attempt count. fn maximum_attempts(&self) -> u8; - /// Sign one delivery with the product's scheme and key material. + /// Sign the identity, attempt timestamp and body using Standard Webhooks. fn sign_delivery( &self, fields: DeliverySignatureFields<'_>, @@ -229,7 +225,7 @@ pub trait HookDestination: Send + Sync { /// Render the signed request for transport. fn render_delivery( &self, - headers: EventDeliveryHeaders<'_>, + headers: SignedEventHeaders<'_>, body: Vec, ) -> Result; @@ -241,25 +237,15 @@ pub trait HookDestination: Send + Sync { ) -> Result; } -/// The neutral signing input for one delivery attempt. -/// -/// The product maps this onto its own scheme. The values are exactly the -/// ones the wire carries: changing any of them changes wire bytes. -#[derive(Clone, Copy, Debug)] +/// Standard Webhooks signing input for one attempt. +#[derive(Clone, Copy)] pub struct DeliverySignatureFields<'a> { pub id: &'a str, - pub source: &'a str, - pub event_type: &'a str, - pub time: &'a str, - pub data_schema: &'a str, - pub generation: &'a str, - pub attempt: &'a str, - pub delivery_time: &'a str, - pub idempotency_key: &'a str, + pub timestamp: u64, pub body: &'a [u8], } -/// The product's signing scheme refused the input. +/// The delivery signature refused the input. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DeliverySignatureRefused; diff --git a/crates/registry-platform-hooks/src/delivery/service.rs b/crates/registry-platform-hooks/src/delivery/service.rs index 540eaa7e56..d8de893d30 100644 --- a/crates/registry-platform-hooks/src/delivery/service.rs +++ b/crates/registry-platform-hooks/src/delivery/service.rs @@ -3,15 +3,10 @@ //! The at-least-once delivery worker: claim, send, finalize, and the //! operator status and replay surface. //! -//! This is the moved delivery core. Claim, lease/CAS, lease reaping, retry -//! scheduling, dead-lettering, payload expiry, and operator replay run in -//! [`registry_platform_dispatch::postgres::Dispatcher`] over the delivery -//! state table, through the hook store in `store.rs`; attempt-budget -//! accounting, idempotency-key construction, and transport-vs-deadline -//! classification keep the behavior they had while the worker lived in the -//! owning product's runtime. Every product-owned input arrives through the -//! seams, and the worker sends the captured envelope bytes unchanged, with the -//! delivery attributes the transport carries beside them. +//! The shared dispatcher owns leases, retries, dead-lettering, expiry, and +//! replay through the hook store. The worker signs the captured envelope +//! bytes for each attempt and sends them unchanged through the destination +//! seam under the remaining attempt budget. use std::sync::atomic::Ordering; use std::time::{Duration, SystemTime}; @@ -22,9 +17,9 @@ use registry_platform_dispatch::postgres::{ LeasedJob, LeasedReadError, SelectSql, }; use registry_platform_dispatch::{ - idempotency_key, remaining_attempt_budget, DispatchError, FailureCode, SendOutcome, Sent, + remaining_attempt_budget, DispatchError, FailureCode, SendOutcome, Sent, }; -use registry_platform_httputil::destination::{DestinationSendError, EventDeliveryHeaders}; +use registry_platform_httputil::destination::{DestinationSendError, SignedEventHeaders}; use sha2::{Digest, Sha256}; use time::format_description::well_known::Rfc3339; use time::OffsetDateTime; @@ -134,21 +129,12 @@ impl From for RetainedBindingError { } /// The product-supplied constants the worker cannot derive. -/// -/// The adopting product passes its own values; the values it used before the -/// move keep the bytes on the wire identical. pub struct DeliveryConfig { /// The product schema that holds the delivery tables. The name is /// interpolated into SQL, so only a plain lowercase SQL identifier is /// accepted. pub schema: String, - /// The product's idempotency-key domain, bound into every delivery - /// idempotency key. It must stay stable for the life of retained work, - /// because a changed domain changes every future key. - pub idempotency_domain: Vec, - /// The delivery source identity sent with every delivery (`ce-source` - /// and the signed source component): the producing product and - /// deployment identity. + /// The producing product and deployment identity expected in the envelope. pub delivery_source: String, } @@ -156,7 +142,6 @@ pub struct DeliveryConfig { pub struct DeliveryService { dispatcher: Dispatcher>, schema: String, - idempotency_domain: Vec, delivery_source: String, execution_deadline: Option, } @@ -166,7 +151,6 @@ impl Clone for DeliveryService { Self { dispatcher: self.dispatcher.clone(), schema: self.schema.clone(), - idempotency_domain: self.idempotency_domain.clone(), delivery_source: self.delivery_source.clone(), execution_deadline: self.execution_deadline, } @@ -227,7 +211,6 @@ impl DeliveryService { Self { dispatcher, schema, - idempotency_domain: config.idempotency_domain, delivery_source: config.delivery_source, execution_deadline: None, } @@ -252,7 +235,6 @@ impl DeliveryService { self.seams().clone(), DeliveryConfig { schema: self.schema.clone(), - idempotency_domain: self.idempotency_domain.clone(), delivery_source: self.delivery_source.clone(), }, Some(revision.to_owned()), @@ -866,53 +848,23 @@ impl DeliveryService { { return Ok(DeliveryAuditOutcome::DestinationBindingRefused.into()); } - let delivery_time = OffsetDateTime::from(claim.attempt_started_at) - .format(&Rfc3339) - .map_err(|_| DeliveryError::Unavailable)?; - let event_time = OffsetDateTime::from(material.event_time) - .format(&Rfc3339) - .map_err(|_| DeliveryError::Unavailable)?; - let event_id = claim.event_id.to_string(); - let source = &self.delivery_source; - let generation = claim.generation.to_string(); - let attempt = claim.attempt.to_string(); - let idempotency_key = delivery_idempotency_key( - &self.idempotency_domain, - claim.event_id, - &claim.compiled_delivery_id, - claim.generation, - &material.payload_digest, - &material.destination_binding_digest, - ); + let (event_id, timestamp) = delivery_header_values(claim)?; let signature = destination.sign_delivery(DeliverySignatureFields { id: &event_id, - source, - event_type: &material.event_type, - time: &event_time, - data_schema: &material.data_schema, - generation: &generation, - attempt: &attempt, - delivery_time: &delivery_time, - idempotency_key: &idempotency_key, + timestamp, body: &material.body, }); let Ok(signature) = signature else { return Ok(DeliveryAuditOutcome::DestinationPolicyRefused.into()); }; + let timestamp = timestamp.to_string(); // The envelope bytes outlive the request: a proposal answer hands // them to the product's apply seam after the send returns. let envelope = material.body.clone(); let request = match destination.render_delivery( - EventDeliveryHeaders { + SignedEventHeaders { id: event_id.as_bytes(), - source: source.as_bytes(), - event_type: material.event_type.as_bytes(), - time: event_time.as_bytes(), - dataschema: material.data_schema.as_bytes(), - generation: generation.as_bytes(), - attempt: attempt.as_bytes(), - delivery_time: delivery_time.as_bytes(), - idempotency_key: idempotency_key.as_bytes(), + timestamp: timestamp.as_bytes(), signature: signature.as_bytes(), }, material.body, @@ -1925,27 +1877,13 @@ pub(super) fn validate_captured_policy( Ok(()) } -/// The delivery idempotency key for one attempt: the product's domain, then -/// the length-prefixed attempt identity, digested. Stable across retries of -/// one attempt and changed by a new generation. -fn delivery_idempotency_key( - idempotency_domain: &[u8], - event_id: Uuid, - compiled_delivery_id: &str, - generation: i64, - payload_digest: &[u8], - destination_binding_digest: &str, -) -> String { - idempotency_key( - idempotency_domain, - &[ - event_id.to_string().as_bytes(), - compiled_delivery_id.as_bytes(), - generation.to_string().as_bytes(), - payload_digest, - destination_binding_digest.as_bytes(), - ], - ) +fn delivery_header_values(claim: &DeliveryClaim) -> Result<(String, u64), DeliveryError> { + let timestamp = claim + .attempt_started_at + .duration_since(SystemTime::UNIX_EPOCH) + .map_err(|_| DeliveryError::Unavailable)? + .as_secs(); + Ok((claim.event_id.to_string(), timestamp)) } #[cfg(test)] @@ -1992,7 +1930,7 @@ mod tests { fn render_delivery( &self, - _headers: EventDeliveryHeaders<'_>, + _headers: SignedEventHeaders<'_>, _body: Vec, ) -> Result { unreachable!("no test below reaches a destination") @@ -2206,7 +2144,7 @@ mod tests { let digest = Sha256::digest(b"other bytes").to_vec(); assert!( accept_stored_envelope(&body, &stored_binding(&body, &digest)).is_err(), - "the captured payload digest still pins the bytes the idempotency key is built from" + "the captured payload digest still pins the delivered envelope" ); } @@ -2246,67 +2184,17 @@ mod tests { } #[test] - fn idempotency_key_is_stable_across_retries_and_changes_on_replay_generation() { - let domain = b"hooks-delivery-idempotency-v1"; - let event_id = - Uuid::parse_str("00000000-0000-4000-8000-000000000001").expect("fixture UUID parses"); - let digest = Sha256::digest(br#"{"label":"value"}"#); - let first_key = delivery_idempotency_key( - domain, - event_id, - "events.case.created.webhook", - 1, - digest.as_slice(), - "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - let repeated_key = delivery_idempotency_key( - domain, - event_id, - "events.case.created.webhook", - 1, - digest.as_slice(), - "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - let replay_key = delivery_idempotency_key( - domain, - event_id, - "events.case.created.webhook", - 2, - digest.as_slice(), - "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - assert_eq!(first_key, repeated_key); - assert_ne!(first_key, replay_key); - assert!(first_key.starts_with("sha256:")); - assert_eq!(first_key.len(), 71); - } - - #[test] - fn the_idempotency_key_is_bound_to_its_configured_domain() { - let event_id = - Uuid::parse_str("00000000-0000-4000-8000-000000000001").expect("fixture UUID parses"); - let digest = Sha256::digest(br#"{"label":"value"}"#); - let binding = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - let one = delivery_idempotency_key( - b"hooks-delivery-idempotency-v1", - event_id, - "events.case.created.webhook", - 1, - digest.as_slice(), - binding, - ); - let other = delivery_idempotency_key( - b"another-product-idempotency-v1", - event_id, - "events.case.created.webhook", - 1, - digest.as_slice(), - binding, - ); - assert_ne!( - one, other, - "two products never share a delivery idempotency key" - ); + fn webhook_header_values_project_the_claim_event_id_and_attempt_start() { + let mut claim = proposal_claim(); + claim.attempt_started_at = SystemTime::UNIX_EPOCH + Duration::from_millis(1_123); + for (generation, attempt, timestamp) in [(1, 1, 1), (1, 2, 2), (2, 1, 3)] { + claim.generation = generation; + claim.attempt = attempt; + let (id, actual_timestamp) = delivery_header_values(&claim).unwrap(); + assert_eq!(id, STORED_EVENT_ID); + assert_eq!(actual_timestamp, timestamp); + claim.attempt_started_at += Duration::from_secs(1); + } } #[test] @@ -2446,7 +2334,6 @@ mod tests { seams, DeliveryConfig { schema: "registry; drop table users".to_owned(), - idempotency_domain: b"hooks-delivery-refusal-test-v1".to_vec(), delivery_source: "urn:registrystack:test:instance:hooks-delivery".to_owned(), }, ); @@ -2461,7 +2348,6 @@ mod tests { }, DeliveryConfig { schema: "hooks_delivery_loop_test".to_owned(), - idempotency_domain: b"hooks-delivery-loop-test-v1".to_vec(), delivery_source: "urn:registrystack:test:instance:hooks-delivery".to_owned(), }, ); @@ -2698,7 +2584,6 @@ mod tests { }, DeliveryConfig { schema: "hooks_delivery_proposal_test".to_owned(), - idempotency_domain: b"hooks-delivery-proposal-test-v1".to_vec(), delivery_source: STORED_SOURCE.to_owned(), }, ) @@ -3054,7 +2939,6 @@ mod tests { }, DeliveryConfig { schema: "test".to_owned(), - idempotency_domain: vec![], delivery_source: STORED_SOURCE.to_owned(), }, ); @@ -3133,7 +3017,6 @@ mod tests { }, DeliveryConfig { schema: schema.to_owned(), - idempotency_domain: b"hooks-delivery-success-test-v1".to_vec(), delivery_source: STORED_SOURCE.to_owned(), }, ); @@ -3240,7 +3123,6 @@ mod tests { }, DeliveryConfig { schema: schema.to_owned(), - idempotency_domain: b"hooks-dispatch-adapter-test-v1".to_vec(), delivery_source: STORED_SOURCE.to_owned(), }, ); diff --git a/crates/registry-platform-hooks/src/delivery/url_binding.rs b/crates/registry-platform-hooks/src/delivery/url_binding.rs index fb89a3ad9e..6dedf5a4e0 100644 --- a/crates/registry-platform-hooks/src/delivery/url_binding.rs +++ b/crates/registry-platform-hooks/src/delivery/url_binding.rs @@ -16,18 +16,24 @@ use std::sync::Arc; use std::time::Duration; use registry_platform_canonical_json::canonicalize_json; -use registry_platform_config::{SecretResolver, UrlHookDestinationConfig}; +use registry_platform_config::{ + SecretError, SecretReference, SecretResolver, UrlHookDestinationConfig, +}; +use registry_platform_crypto::delivery_signature::{ + distinct_delivery_keys, DeliveryKey, DeliveryKeyError, DeliveryKeys, +}; use registry_platform_httputil::destination::EventDestinationPolicy; use registry_platform_yaml::LocalId; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; -use super::destination::{ - url_destination_address, UrlDestination, UrlDestinationError, UrlDestinationParts, -}; +use super::destination::{url_destination_address, UrlDestination, UrlDestinationParts}; -/// Value-free refusal while activating a URL hook destination. -#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +const CURRENT_KEY_MEMBER: &str = "hmacSha256KeyRef"; +const PREVIOUS_KEY_MEMBER: &str = "previousHmacSha256KeyRef"; + +/// Refusal while activating a URL hook destination. +#[derive(Debug, Eq, PartialEq, thiserror::Error)] pub enum UrlHookActivationError { /// The logical id is not a local identifier, or the attempt timeout or /// attempt count is outside the block's delivery budget. @@ -36,9 +42,28 @@ pub enum UrlHookActivationError { /// The URL or the policy built from it is refused. #[error("the URL hook destination is invalid")] InvalidDestination, - /// The signing key reference does not resolve to usable key material. - #[error("the URL hook destination signing material is invalid")] - InvalidSigningMaterial, + /// The key reference could not be resolved. + #[error("Destination {destination} could not resolve {member}: {reason}. {}", reason.suggested_action())] + SigningKeyUnavailable { + destination: String, + member: &'static str, + reason: SecretError, + }, + /// The resolved key bytes violate the signing key policy. + #[error("{}", invalid_signing_key_message(.destination, .member, *.length, *.trailing_newline, .reason))] + InvalidSigningKey { + destination: String, + member: &'static str, + length: usize, + trailing_newline: bool, + reason: DeliveryKeyError, + }, + /// Two destination members resolve to the same key bytes. + #[error( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing \ + 32 new random bytes to another secret and referencing it there." + )] + RepeatedSigningKey { first: String, second: String }, } /// Every configured URL hook destination, activated, with the digest of the @@ -83,10 +108,26 @@ pub fn activate_url_hook_destinations( digest_values.push(digest_value); bindings.insert(logical_id.clone(), Arc::new(destination)); } - let binding_digest = canonical_digest(&json!({ - "schemaVersion": binding_schema, - "destinations": digest_values, - }))?; + let labeled_keys = bindings + .iter() + .flat_map(|(logical_id, destination)| { + let keys = destination.keys(); + std::iter::once((format!("{logical_id}.{CURRENT_KEY_MEMBER}"), keys.current())).chain( + keys.previous() + .map(|key| (format!("{logical_id}.{PREVIOUS_KEY_MEMBER}"), key)), + ) + }) + .collect::>(); + distinct_delivery_keys( + labeled_keys + .iter() + .map(|(label, key)| (label.as_str(), *key)), + ) + .map_err(|error| UrlHookActivationError::RepeatedSigningKey { + first: error.first().to_owned(), + second: error.second().to_owned(), + })?; + let binding_digest = inventory_digest(binding_schema, digest_values)?; Ok(ActivatedUrlHookDestinations { bindings, binding_digest, @@ -109,9 +150,27 @@ pub fn activate_url_hook_destination( .map_err(|_| UrlHookActivationError::InvalidDestination)?; let policy = EventDestinationPolicy::new(logical_id, &address.origin, address.profile, &[]) .map_err(|_| UrlHookActivationError::InvalidDestination)?; - let hmac_sha256_key = secrets - .resolve(config.hmac_sha256_key_ref.as_str()) - .map_err(|_| UrlHookActivationError::InvalidSigningMaterial)?; + let (current, _, _) = resolve_delivery_key( + secrets, + logical_id, + CURRENT_KEY_MEMBER, + &config.hmac_sha256_key_ref, + )?; + let keys = if let Some(reference) = &config.previous_hmac_sha256_key_ref { + let (previous, length, trailing_newline) = + resolve_delivery_key(secrets, logical_id, PREVIOUS_KEY_MEMBER, reference)?; + DeliveryKeys::new(current, Some(previous)).map_err(|reason| { + UrlHookActivationError::InvalidSigningKey { + destination: logical_id.to_owned(), + member: PREVIOUS_KEY_MEMBER, + length, + trailing_newline, + reason, + } + })? + } else { + DeliveryKeys::new(current, None).expect("one validated key") + }; let digest_value = json!({ "logicalId": logical_id, "url": config.url.as_str(), @@ -128,19 +187,79 @@ pub fn activate_url_hook_destination( request_target: address.request_target, policy, maximum_payload_bytes, - hmac_sha256_key, + keys, attempt_timeout: Duration::from_millis(u64::from(config.attempt_timeout_milliseconds)), maximum_attempts: config.maximum_attempts, }) - .map_err(|error| match error { - UrlDestinationError::InvalidBinding => UrlHookActivationError::InvalidDestination, - UrlDestinationError::InvalidSigningMaterial => { - UrlHookActivationError::InvalidSigningMaterial - } - })?; + .map_err(|_| UrlHookActivationError::InvalidDestination)?; Ok((destination, digest_value)) } +fn resolve_delivery_key( + secrets: &SecretResolver, + logical_id: &str, + member: &'static str, + reference: &SecretReference, +) -> Result<(DeliveryKey, usize, bool), UrlHookActivationError> { + let secret = secrets + .resolve_binary_reference(reference) + .map_err(|reason| UrlHookActivationError::SigningKeyUnavailable { + destination: logical_id.to_owned(), + member, + reason, + })?; + let bytes = secret.expose_secret(); + let length = bytes.len(); + let trailing_newline = bytes.ends_with(b"\n"); + let key = + DeliveryKey::new(bytes).map_err(|reason| UrlHookActivationError::InvalidSigningKey { + destination: logical_id.to_owned(), + member, + length, + trailing_newline, + reason, + })?; + Ok((key, length, trailing_newline)) +} + +fn invalid_signing_key_message( + destination: &str, + member: &str, + length: usize, + trailing_newline: bool, + reason: &DeliveryKeyError, +) -> String { + let action = match reason { + DeliveryKeyError::TooShort { .. } | DeliveryKeyError::TooLong { .. } => { + "Supply 32 to 64 exact key bytes." + } + DeliveryKeyError::SecretText => "Supply the exact key bytes without the whsec_ encoding.", + DeliveryKeyError::PreviousEqualsCurrent => { + let previous = format!("{destination}.{PREVIOUS_KEY_MEMBER}"); + let current = format!("{destination}.{CURRENT_KEY_MEMBER}"); + return format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random \ + bytes to the secret {current} references and keep the old bytes behind \ + {previous}." + ); + } + }; + format!( + "Destination {destination} member {member} has {length} bytes (trailing newline: \ + {trailing_newline}). {action}" + ) +} + +fn inventory_digest( + binding_schema: &str, + destinations: Vec, +) -> Result { + canonical_digest(&json!({ + "schemaVersion": binding_schema, + "destinations": destinations, + })) +} + fn canonical_digest(value: &Value) -> Result { use std::fmt::Write as _; let canonical = diff --git a/crates/registry-platform-hooks/src/delivery/url_binding_tests.rs b/crates/registry-platform-hooks/src/delivery/url_binding_tests.rs index 0b512c36ae..b2692e9971 100644 --- a/crates/registry-platform-hooks/src/delivery/url_binding_tests.rs +++ b/crates/registry-platform-hooks/src/delivery/url_binding_tests.rs @@ -34,13 +34,200 @@ fn keyed_secrets() -> (tempfile::TempDir, SecretResolver) { (directory, secrets) } +fn write_test_key(directory: &tempfile::TempDir, name: &str, bytes: &[u8]) { + let path = directory.path().join(name); + std::fs::write(&path, bytes).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +#[test] +fn a_destination_key_over_64_bytes_names_its_length() { + let (directory, secrets) = keyed_secrets(); + let mut key = [0; 65]; + key[64] = b'\n'; + write_test_key(&directory, "hook-key", &key); + let error = activate_url_hook_destination( + SCHEDULING_BINDING_SCHEMA, + "events", + &destination("https://events.example.test/hooks", 5000, 3), + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap_err() + .to_string(); + for expected in [ + "events", + "hmacSha256KeyRef", + "65 bytes", + "trailing newline: true", + ] { + assert!(error.contains(expected), "{error}"); + } +} + +#[test] +fn a_bad_rotation_key_names_its_member_without_printing_key_bytes() { + let (directory, secrets) = keyed_secrets(); + let mut config = destination("https://events.example.test/hooks", 5000, 3); + config.previous_hmac_sha256_key_ref = + Some(registry_platform_config::SecretReference::parse("secret:file/previous").unwrap()); + for (bytes, expected) in [ + (b"x".as_slice(), DeliveryKeyError::TooShort { length: 1 }), + (b"whsec_test_value".as_slice(), DeliveryKeyError::SecretText), + ( + [0x5a; 32].as_slice(), + DeliveryKeyError::PreviousEqualsCurrent, + ), + ] { + write_test_key(&directory, "previous", bytes); + let error = activate_url_hook_destination( + SCHEDULING_BINDING_SCHEMA, + "events", + &config, + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap_err(); + assert_eq!( + error, + UrlHookActivationError::InvalidSigningKey { + destination: "events".to_owned(), + member: PREVIOUS_KEY_MEMBER, + length: bytes.len(), + trailing_newline: false, + reason: expected, + } + ); + assert!(!error.to_string().contains("whsec_test_value")); + if expected == DeliveryKeyError::PreviousEqualsCurrent { + assert_eq!( + error.to_string(), + "events.previousHmacSha256KeyRef holds the same bytes as \ + events.hmacSha256KeyRef. To rotate, write 32 new random bytes to the secret \ + events.hmacSha256KeyRef references and keep the old bytes behind \ + events.previousHmacSha256KeyRef." + ); + } + } +} + +#[test] +fn an_unsafe_secret_keeps_its_value_free_refusal_reason() { + use std::error::Error as _; + + let (directory, secrets) = keyed_secrets(); + std::fs::set_permissions( + directory.path().join("hook-key"), + std::fs::Permissions::from_mode(0o644), + ) + .unwrap(); + let error = activate_url_hook_destination( + SCHEDULING_BINDING_SCHEMA, + "events", + &destination("https://events.example.test/hooks", 5000, 3), + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap_err(); + let UrlHookActivationError::SigningKeyUnavailable { reason, .. } = &error else { + panic!("expected secret resolution refusal"); + }; + assert!(matches!(reason, SecretError::UnsafeFile(_))); + let diagnostic = error.to_string(); + assert!(diagnostic.contains(reason.suggested_action())); + assert!(!diagnostic.contains("hook-key")); + assert!(error.source().is_none()); +} + +#[test] +fn two_destinations_sharing_a_key_are_refused_naming_both() { + let (directory, secrets) = keyed_secrets(); + write_test_key(&directory, "other-key", &[0; 32]); + write_test_key(&directory, "third-key", &[1; 32]); + let shared = SecretReference::parse("secret:file/hook-key").unwrap(); + let other = SecretReference::parse("secret:file/other-key").unwrap(); + let third = SecretReference::parse("secret:file/third-key").unwrap(); + for (first_previous, second_previous) in [(false, false), (false, true), (true, true)] { + let config = destination("https://events.example.test/hooks", 5000, 3); + let mut first = config.clone(); + let mut second = config; + if first_previous { + first.hmac_sha256_key_ref = other.clone(); + first.previous_hmac_sha256_key_ref = Some(shared.clone()); + } + if second_previous { + second.hmac_sha256_key_ref = third.clone(); + second.previous_hmac_sha256_key_ref = Some(shared.clone()); + } + let error = activate_url_hook_destinations( + SCHEDULING_BINDING_SCHEMA, + &BTreeMap::from([("events".into(), first), ("mirror".into(), second)]), + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap_err(); + let member = |previous| { + if previous { + PREVIOUS_KEY_MEMBER + } else { + CURRENT_KEY_MEMBER + } + }; + assert_eq!( + error, + UrlHookActivationError::RepeatedSigningKey { + first: format!("events.{}", member(first_previous)), + second: format!("mirror.{}", member(second_previous)), + } + ); + assert!(!error.to_string().contains("hook-key")); + let (first_label, second_label) = ( + format!("events.{}", member(first_previous)), + format!("mirror.{}", member(second_previous)), + ); + assert_eq!( + error.to_string(), + format!( + "{first_label} and {second_label} resolve to the same key bytes. Give \ + {second_label} its own key by writing 32 new random bytes to another secret \ + and referencing it there." + ) + ); + } +} + +#[test] +fn adding_a_previous_key_leaves_the_binding_digest_unchanged() { + let (directory, secrets) = keyed_secrets(); + write_test_key(&directory, "old-key", &[0; 32]); + let mut config = destination("https://events.example.test/hooks", 5000, 3); + let activate = |config| { + activate_url_hook_destinations( + SCHEDULING_BINDING_SCHEMA, + &BTreeMap::from([("events".into(), config)]), + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap() + }; + let before = activate(config.clone()); + config.previous_hmac_sha256_key_ref = + Some(registry_platform_config::SecretReference::parse("secret:file/old-key").unwrap()); + let after = activate(config); + assert_eq!(before.binding_digest, after.binding_digest); + assert_eq!( + before.bindings["events"].binding_digest(), + after.bindings["events"].binding_digest() + ); +} + /// The digests Scheduling recorded before the block moved here. A retained /// delivery row is refused once its recorded digest stops matching, so the /// digest shape may not change. #[test] fn binding_digests_keep_the_shape_scheduling_records() { - let (_directory, secrets) = keyed_secrets(); - let configured = BTreeMap::from([ + let (directory, secrets) = keyed_secrets(); + let mut configured = BTreeMap::from([ ( "appointment-events".to_owned(), destination("https://events.example.test/scheduling", 5_000, 8), @@ -51,25 +238,49 @@ fn binding_digests_keep_the_shape_scheduling_records() { ), ]); + let mut digest_values = Vec::new(); + for (id, expected) in [ + ( + "appointment-events", + "sha256:519db07c7b8250700c34939c5212b9fabf77b2c37c42e72dfa997214e4da985d", + ), + ( + "audit-mirror", + "sha256:dd0b35e51274ab6a1d2456e9b0520acdf5b68e720a352d0d4819f41090ff7d97", + ), + ] { + let (binding, value) = activate_url_hook_destination( + SCHEDULING_BINDING_SCHEMA, + id, + &configured[id], + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap(); + assert_eq!(binding.binding_digest(), expected); + digest_values.push(value); + } + assert_eq!( + inventory_digest(SCHEDULING_BINDING_SCHEMA, digest_values).unwrap(), + "sha256:6021194b5df3b34eeb31b21c8b3ef448f2d639d3e8393d13b98a8276b5411df0", + ); + + // The live inventory uses distinct key references and bytes. + write_test_key(&directory, "mirror-key", &[0; 32]); + configured + .get_mut("audit-mirror") + .unwrap() + .hmac_sha256_key_ref = SecretReference::parse("secret:file/mirror-key").unwrap(); let activated = activate_url_hook_destinations( SCHEDULING_BINDING_SCHEMA, &configured, &secrets, MAXIMUM_PAYLOAD_BYTES, ) - .expect("the pinned destinations activate"); - + .unwrap(); assert_eq!( activated.binding_digest, - "sha256:6021194b5df3b34eeb31b21c8b3ef448f2d639d3e8393d13b98a8276b5411df0" - ); - assert_eq!( - activated.bindings["appointment-events"].binding_digest(), - "sha256:519db07c7b8250700c34939c5212b9fabf77b2c37c42e72dfa997214e4da985d" - ); - assert_eq!( - activated.bindings["audit-mirror"].binding_digest(), - "sha256:dd0b35e51274ab6a1d2456e9b0520acdf5b68e720a352d0d4819f41090ff7d97" + "sha256:63f9ba0e4c8368aa0a5f82253a3523ed604c0553b8f39c7e349b5277fc962782" ); let printed = format!("{activated:?}"); assert!(!printed.contains("events.example.test"), "{printed}"); @@ -156,7 +367,11 @@ fn activation_refuses_ids_and_budgets_outside_the_block() { .map(drop) .expect_err("no test key resolves"); let expected = if accepted { - UrlHookActivationError::InvalidSigningMaterial + UrlHookActivationError::SigningKeyUnavailable { + destination: id.clone(), + member: CURRENT_KEY_MEMBER, + reason: SecretError::ProviderDisabled, + } } else { UrlHookActivationError::DeliveryBudgetWidening }; @@ -184,3 +399,186 @@ fn activation_refuses_a_url_outside_the_fixed_policy() { assert_eq!(refused, UrlHookActivationError::InvalidDestination, "{url}"); } } + +#[cfg(feature = "receiver")] +#[tokio::test] +async fn a_key_rotation_keeps_every_retained_delivery_acceptable() { + use crate::receiver::DeliveryFreshness; + use crate::{verify_hook_delivery, EnvelopeLimits, HookDelivery, HookEnvelope}; + use registry_platform_httputil::destination::SignedEventHeaders; + use std::time::SystemTime; + use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader}; + use tokio::net::TcpListener; + + use crate::delivery::{ + DeliverySignatureFields, DestinationAnswer, HookDestination, SharedUrlDestination, + }; + + const ID: &str = "00000000-0000-4000-8000-000000000001"; + let envelope = HookEnvelope { + id: ID.to_owned(), + event_type: "case.created".to_owned(), + source: "urn:example:source".to_owned(), + time: time::OffsetDateTime::UNIX_EPOCH, + subject: crate::EventSubject::record("example/case/42", 1), + dataschema: "urn:example:schema".to_owned(), + data: json!({"event": "retained"}), + causation: crate::Causation::root(ID), + }; + let body = envelope + .to_canonical_bytes(&EnvelopeLimits::default()) + .unwrap(); + let expected_body = body.clone(); + let body = body.as_slice(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut config = destination( + &format!("http://{}/hook", listener.local_addr().unwrap()), + 5000, + 3, + ); + let (directory, secrets) = keyed_secrets(); + let k1 = || DeliveryKey::new(&[0x5a; 32]).unwrap(); + let k2 = || DeliveryKey::new(&[0; 32]).unwrap(); + let original_receiver = DeliveryKeys::new(k1(), None).unwrap(); + let rotated_receiver = DeliveryKeys::new(k2(), Some(k1())).unwrap(); + let current_only = DeliveryKeys::new(k2(), None).unwrap(); + + let activate = |config: &UrlHookDestinationConfig| { + let (destination, _) = activate_url_hook_destination( + SCHEDULING_BINDING_SCHEMA, + "events", + config, + &secrets, + MAXIMUM_PAYLOAD_BYTES, + ) + .unwrap(); + SharedUrlDestination(Arc::new(destination)) + }; + + let server = tokio::spawn(async move { + for (timestamp, response, signature_count) in [ + (1000, "503 Service Unavailable", 1), + (1001, "200 OK", 2), + (1002, "200 OK", 1), + ] { + let (stream, _) = listener.accept().await.unwrap(); + let mut stream = BufReader::new(stream); + let mut line = String::new(); + stream.read_line(&mut line).await.unwrap(); + assert_eq!(line, "POST /hook HTTP/1.1\r\n"); + let mut headers = Vec::new(); + loop { + line.clear(); + stream.read_line(&mut line).await.unwrap(); + assert!(!line.is_empty(), "incomplete request"); + if line == "\r\n" { + break; + } + let (name, value) = line.strip_suffix("\r\n").unwrap().split_once(": ").unwrap(); + headers.push((name.to_owned(), value.to_owned())); + } + let mut body = vec![0; expected_body.len()]; + stream.read_exact(&mut body).await.unwrap(); + assert_eq!(body, expected_body); + let freshness = DeliveryFreshness::default_at( + SystemTime::UNIX_EPOCH + Duration::from_secs(timestamp), + ); + let check = |headers: &[(String, String)], keys| { + let verified = verify_hook_delivery( + HookDelivery { + headers: headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())), + body: &body, + keys, + }, + freshness, + ) + .unwrap(); + assert_eq!(verified.id, ID); + assert_eq!(verified.timestamp, timestamp); + assert_eq!(verified.envelope, envelope); + }; + let mut first_only = headers.clone(); + let signature = &mut first_only + .iter_mut() + .find(|(name, _)| name.eq_ignore_ascii_case("webhook-signature")) + .unwrap() + .1; + assert_eq!(signature.split(' ').count(), signature_count); + signature.truncate(signature.find(' ').unwrap_or(signature.len())); + if timestamp <= 1001 { + check(&headers, &original_receiver); + } + if timestamp >= 1001 { + check(&headers, &rotated_receiver); + } + check( + &first_only, + if timestamp == 1000 { + &original_receiver + } else { + ¤t_only + }, + ); + stream + .write_all( + format!( + "HTTP/1.1 {response}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}" + ) + .as_bytes(), + ) + .await + .unwrap(); + } + }); + + let send = |destination: SharedUrlDestination, timestamp: u64| async move { + let signature = destination + .sign_delivery(DeliverySignatureFields { + id: ID, + timestamp, + body, + }) + .unwrap(); + let request = destination + .render_delivery( + SignedEventHeaders { + id: ID.as_bytes(), + timestamp: timestamp.to_string().as_bytes(), + signature: signature.as_bytes(), + }, + body.to_vec(), + ) + .unwrap(); + destination + .send_delivery(request, Duration::from_secs(5)) + .await + .unwrap() + }; + + let original = activate(&config); + let digest = original.binding_digest().to_owned(); + assert!(matches!( + send(original, 1000).await, + DestinationAnswer::NonSuccess { status: 503 } + )); + write_test_key(&directory, "previous", &[0x5a; 32]); + write_test_key(&directory, "hook-key", &[0; 32]); + config.previous_hmac_sha256_key_ref = + Some(registry_platform_config::SecretReference::parse("secret:file/previous").unwrap()); + let rotated = activate(&config); + assert_eq!(rotated.binding_digest(), digest); + assert!(matches!( + send(rotated, 1001).await, + DestinationAnswer::Delivered { .. } + )); + config.previous_hmac_sha256_key_ref = None; + let retired = activate(&config); + assert_eq!(retired.binding_digest(), digest); + assert!(matches!( + send(retired, 1002).await, + DestinationAnswer::Delivered { .. } + )); + server.await.unwrap(); +} diff --git a/crates/registry-platform-hooks/src/envelope.rs b/crates/registry-platform-hooks/src/envelope.rs index 5906c6f101..018b412faa 100644 --- a/crates/registry-platform-hooks/src/envelope.rs +++ b/crates/registry-platform-hooks/src/envelope.rs @@ -4,12 +4,10 @@ //! unchanged for every product and every destination kind. //! //! The fields are `id`, `type`, `source`, `time`, `subject`, `dataschema`, -//! `data`, and `causation`. Delivery attributes (`attempt`, `generation`, -//! `delivery_time`, `idempotency_key`, `signature`) are deliberately **not** -//! envelope fields and never become them: they stay on the transport headers. -//! The envelope is what the handler reasons over; the attributes are what the -//! worker reasons over. A handler that wants to be idempotent keys on the -//! envelope `id`, which the transport also sends as `idempotency_key`. +//! `data`, and `causation`. A remote handler deduplicates on the event ID, +//! which is also sent as `webhook-id`. The attempt timestamp and signature +//! are HTTP headers. The worker tracks attempts and replay generations in +//! delivery state. //! //! Causation is consumed by version one, not reserved for later: once a //! handler can propose a change that commits and fires another hook, event A @@ -28,7 +26,7 @@ use crate::error::{bounded_token, redacted_message}; /// The payload bound the envelope carries, in bytes. /// -/// The 1 MiB Version 1 signable bound +/// The 1 MiB delivery signature bound /// (`registry_platform_crypto::delivery_signature::MAX_BODY_BYTES`), so every /// envelope a product emits can be signed and verified on a delivery path. The /// delivery store's 2 MiB payload column is a looser outer bound. A diff --git a/crates/registry-platform-hooks/src/lib.rs b/crates/registry-platform-hooks/src/lib.rs index 2b153388d7..75ec4a4fe8 100644 --- a/crates/registry-platform-hooks/src/lib.rs +++ b/crates/registry-platform-hooks/src/lib.rs @@ -49,9 +49,9 @@ //! declaration features a product supports, checked with one shared //! diagnostic before any product-specific rule runs. //! -//! The opt-in `receiver` feature adds `receiver::verify_delivery`, the one -//! receiver-side reading of a signed Version 1 delivery that every product -//! receiving a hook delivery calls. +//! The opt-in `receiver` feature verifies Standard Webhooks deliveries +//! through `receiver::verify_hook_delivery` and Version 1 deliveries through +//! `receiver::verify_delivery`. mod capability; mod declaration; @@ -82,5 +82,12 @@ pub use message::{ BoundedText, BoundedTextError, HandlerOutputLimits, HookMessage, HookMessageError, HookProposal, MAX_OUTPUT_BYTES, MAX_REFUSAL_CODE_BYTES, MAX_REFUSAL_SUMMARY_BYTES, }; +#[cfg(feature = "receiver")] +pub use receiver::{ + verify_hook_delivery, HookDelivery, HookDeliveryError, VerifiedHookDelivery, + HOOK_DELIVERY_HEADERS, +}; +#[cfg(feature = "receiver")] +pub use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; pub use retry::exponential_retry_delays_ms; pub use validate::{validate_hooks, HookValidationError}; diff --git a/crates/registry-platform-hooks/src/receiver.rs b/crates/registry-platform-hooks/src/receiver.rs index 37a7d02146..a0c375ec1b 100644 --- a/crates/registry-platform-hooks/src/receiver.rs +++ b/crates/registry-platform-hooks/src/receiver.rs @@ -1,25 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 -//! Receiver-side verification of one signed Version 1 hook delivery. +//! Receiver-side authentication of Standard Webhooks and Version 1 deliveries. //! -//! Every product that receives a signed hook delivery reads the same twelve -//! transport headers, rebuilds the same signed fields, and calls the same -//! `registry-platform-crypto` verifier. This module is that one reading, so a -//! receiver never re-derives the field order, the header set, or the -//! signature shape on its own. -//! -//! It verifies authenticity only. Which source a receiver trusts, which event -//! types and schemas it accepts, the content type it requires, its -//! deduplication on the idempotency key, and what the body means stay with -//! the receiving product, which checks them on the returned -//! [`VerifiedDelivery`]. +//! [`verify_hook_delivery`] authenticates the exact HTTP body and decodes its +//! canonical hook envelope. [`verify_delivery`] authenticates the Version 1 +//! transport fields and body. Both apply the freshness policy the caller +//! selects. Receivers own source trust, deduplication, and handler effects. use std::time::{Duration, SystemTime}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_crypto::delivery_signature::{ - verify_v1, verify_v1_authenticity, SignatureFields, VerificationError, MAX_BODY_BYTES, + self, verify_v1, verify_v1_authenticity, DeliveryKeys, DeliverySignatureError, SignatureFields, + SignedContent, VerificationError, MAX_BODY_BYTES, }; +use crate::{EnvelopeLimits, HookEnvelope}; + const SIGNATURE_PREFIX: &str = "v1="; const SIGNATURE_BYTES: usize = 32; const SIGNATURE_TEXT_BYTES: usize = 43; @@ -41,18 +37,149 @@ const HEADERS: [&str; 12] = [ "x-registry-signature", ]; +/// How far a signed delivery time may be from the receiver clock, in either +/// direction, when the receiver names no window of its own. +pub const DEFAULT_DELIVERY_SKEW: Duration = delivery_signature::DELIVERY_TOLERANCE; + /// How the receiver bounds the signed delivery time. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DeliveryFreshness { /// Refuse a delivery time further than `skew` from `now`, in either /// direction. Within { now: SystemTime, skew: Duration }, - /// Check only that the delivery time is a valid RFC 3339 instant. The - /// caller enforces its own clock window on - /// [`VerifiedDelivery::delivery_time`] before acting on the body. + /// The caller enforces its clock window on the verified timestamp + /// before acting on the delivery. CallerEnforced, } +impl DeliveryFreshness { + /// The default window around `now`. + #[must_use] + pub const fn default_at(now: SystemTime) -> Self { + Self::Within { + now, + skew: DEFAULT_DELIVERY_SKEW, + } + } +} + +/// Required Standard Webhooks delivery headers, matched case-insensitively. +pub const HOOK_DELIVERY_HEADERS: [&str; 4] = [ + "content-type", + "webhook-id", + "webhook-timestamp", + "webhook-signature", +]; + +/// Exact request material. The iterator must include every header occurrence. +pub struct HookDelivery<'a, H> { + pub headers: H, + pub body: &'a [u8], + pub keys: &'a DeliveryKeys, +} + +/// Authenticated and decoded Standard Webhooks delivery. +pub struct VerifiedHookDelivery<'a> { + pub id: &'a str, + pub timestamp: u64, + pub envelope: HookEnvelope, + pub body: &'a [u8], +} + +impl std::fmt::Debug for VerifiedHookDelivery<'_> { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("VerifiedHookDelivery([REDACTED])") + } +} + +/// Value-free reasons to refuse a Standard Webhooks delivery. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum HookDeliveryError { + #[error("a required hook delivery header is missing")] + MissingHeader, + #[error("a required hook delivery header is repeated")] + DuplicateHeader, + #[error("the hook delivery content type must be application/json")] + InvalidContentType, + #[error(transparent)] + Signature(#[from] DeliverySignatureError), + #[error("the hook delivery body is not a canonical hook envelope")] + InvalidEnvelope, + #[error("webhook-id does not match the hook envelope id")] + IdMismatch, +} + +impl HookDeliveryError { + /// Stable refusal code for the failed validation. + pub const fn code(&self) -> &'static str { + match self { + Self::MissingHeader => "missing-header", + Self::DuplicateHeader => "duplicate-header", + Self::InvalidContentType => "invalid-content-type", + Self::Signature(error) => error.code(), + Self::InvalidEnvelope => "invalid-envelope", + Self::IdMismatch => "id-mismatch", + } + } +} + +/// Verify the exact received bytes before decoding the canonical hook envelope. +pub fn verify_hook_delivery<'a, H>( + delivery: HookDelivery<'a, H>, + freshness: DeliveryFreshness, +) -> Result, HookDeliveryError> +where + H: IntoIterator, +{ + let mut headers = [None; HOOK_DELIVERY_HEADERS.len()]; + for (name, value) in delivery.headers { + if let Some(index) = HOOK_DELIVERY_HEADERS + .iter() + .position(|header| name.eq_ignore_ascii_case(header)) + { + if headers[index].replace(value).is_some() { + return Err(HookDeliveryError::DuplicateHeader); + } + } + } + let [Some(content_type), Some(id), Some(timestamp), Some(signature)] = headers else { + return Err(HookDeliveryError::MissingHeader); + }; + if content_type != b"application/json" { + return Err(HookDeliveryError::InvalidContentType); + } + + let id = std::str::from_utf8(id).map_err(|_| DeliverySignatureError::InvalidId)?; + let content = SignedContent { + id, + timestamp: std::str::from_utf8(timestamp) + .map_err(|_| DeliverySignatureError::InvalidTimestamp)?, + signature: std::str::from_utf8(signature) + .map_err(|_| DeliverySignatureError::MalformedSignature)?, + body: delivery.body, + }; + let timestamp = match freshness { + DeliveryFreshness::Within { now, skew } => { + delivery_signature::verify(delivery.keys, content, now, skew) + } + DeliveryFreshness::CallerEnforced => { + delivery_signature::verify_authenticity(delivery.keys, content) + } + }?; + let envelope = HookEnvelope::from_canonical_bytes(delivery.body, &EnvelopeLimits::default()) + .map_err(|_| HookDeliveryError::InvalidEnvelope)?; + if envelope.id != id { + return Err(HookDeliveryError::IdMismatch); + } + Ok(VerifiedHookDelivery { + id, + timestamp, + envelope, + body: delivery.body, + }) +} + /// Exact request material of one received delivery. /// /// `headers` yields every received header as its name and raw value bytes, @@ -265,6 +392,178 @@ mod tests { use registry_platform_crypto::delivery_signature::sign_v1; const KEY: &[u8] = b"webhook-delivery-signing-key-0123456789abcdef"; + const HOOK_ID: &str = "00000000-0000-4000-8000-000000000001"; + const HOOK_BODY: &[u8] = br#"{"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{},"dataschema":"urn:example:schema","id":"00000000-0000-4000-8000-000000000001","source":"urn:example:source","subject":{"recordReference":"example/case/42","recordRevision":3},"time":"2026-08-30T00:00:00Z","type":"case-created"}"#; + + fn hook_keys() -> DeliveryKeys { + use registry_platform_crypto::delivery_signature::DeliveryKey; + DeliveryKeys::new(DeliveryKey::new(&[42; 32]).unwrap(), None).unwrap() + } + + fn with_hook_headers( + id: &str, + run: impl FnOnce([(&str, &[u8]); 4], &DeliveryKeys) -> T, + ) -> T { + use registry_platform_crypto::delivery_signature::sign; + let keys = hook_keys(); + let signature = sign(&keys, id, 1000, HOOK_BODY).unwrap(); + run( + [ + ("content-type", b"application/json"), + ("webhook-id", id.as_bytes()), + ("webhook-timestamp", b"1000"), + ("webhook-signature", signature.as_bytes()), + ], + &keys, + ) + } + + #[test] + fn verify_hook_delivery_accepts_a_signed_envelope() { + with_hook_headers(HOOK_ID, |headers, keys| { + let delivery = verify_hook_delivery( + HookDelivery { + headers, + body: HOOK_BODY, + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap(); + assert_eq!(delivery.id, HOOK_ID); + assert_eq!(delivery.envelope.id, HOOK_ID); + assert_eq!(delivery.timestamp, 1000); + assert_eq!(delivery.body, HOOK_BODY); + }); + } + + #[test] + fn verify_hook_delivery_refuses_missing_or_duplicate_headers() { + with_hook_headers(HOOK_ID, |headers, keys| { + for (index, (name, value)) in headers.iter().enumerate() { + let mut missing = headers.to_vec(); + missing.remove(index); + let repeated = [(name.to_ascii_uppercase(), *value)]; + for (headers, expected) in [ + (missing, "missing-header"), + ( + headers + .into_iter() + .chain([(repeated[0].0.as_str(), repeated[0].1)]) + .collect(), + "duplicate-header", + ), + ] { + let error = verify_hook_delivery( + HookDelivery { + headers, + body: HOOK_BODY, + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap_err(); + assert_eq!(error.code(), expected); + } + } + }); + } + + #[test] + fn verify_hook_delivery_refuses_an_envelope_whose_id_differs() { + with_hook_headers("other-event", |headers, keys| { + let error = verify_hook_delivery( + HookDelivery { + headers, + body: HOOK_BODY, + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap_err(); + assert_eq!(error.code(), "id-mismatch"); + }); + } + + #[test] + fn verify_hook_delivery_checks_content_type_and_authenticity_before_decoding() { + use registry_platform_crypto::delivery_signature::sign; + with_hook_headers(HOOK_ID, |mut headers, keys| { + headers[0].1 = b"application/json; charset=utf-8"; + let error = verify_hook_delivery( + HookDelivery { + headers, + body: b"!", + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap_err(); + assert_eq!(error.code(), "invalid-content-type"); + headers[0].1 = b"application/json"; + let error = verify_hook_delivery( + HookDelivery { + headers, + body: b"!", + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap_err(); + assert_eq!(error.code(), "signature-mismatch"); + let signature = sign(keys, HOOK_ID, 1000, b"!").unwrap(); + let headers = [ + headers[0], + headers[1], + headers[2], + ("webhook-signature", signature.as_bytes()), + ]; + let error = verify_hook_delivery( + HookDelivery { + headers, + body: b"!", + keys, + }, + DeliveryFreshness::CallerEnforced, + ) + .unwrap_err(); + assert_eq!(error.code(), "invalid-envelope"); + }); + } + + #[test] + fn verify_hook_delivery_applies_300_seconds_by_default() { + with_hook_headers(HOOK_ID, |headers, keys| { + for now in [700, 1300] { + assert!(verify_hook_delivery( + HookDelivery { + headers, + body: HOOK_BODY, + keys + }, + DeliveryFreshness::default_at( + SystemTime::UNIX_EPOCH + Duration::from_secs(now) + ) + ) + .is_ok()); + } + for now in [699, 1301] { + let error = verify_hook_delivery( + HookDelivery { + headers, + body: HOOK_BODY, + keys, + }, + DeliveryFreshness::default_at( + SystemTime::UNIX_EPOCH + Duration::from_secs(now), + ), + ) + .unwrap_err(); + assert_eq!(error.code(), "stale-delivery"); + } + }); + } + const BODY: &[u8] = br#"{"entity":"case","values":{"label":"value"}}"#; const TARGET: &str = "/hooks/registry"; // The crypto crate's fixed Version 1 vector for these exact fields. @@ -381,6 +680,24 @@ mod tests { ); } + #[test] + fn the_default_window_is_300_seconds_in_both_directions() { + assert_eq!(DEFAULT_DELIVERY_SKEW, Duration::from_secs(300)); + let headers = headers(); + let at = |now: SystemTime| verify(&headers, BODY, DeliveryFreshness::default_at(now)); + let delivered = delivery_instant(); + assert!(at(delivered + Duration::from_secs(300)).is_ok()); + assert_eq!( + at(delivered + Duration::from_secs(301)), + Err(ReceiverError::Stale) + ); + assert!(at(delivered - Duration::from_secs(300)).is_ok()); + assert_eq!( + at(delivered - Duration::from_secs(301)), + Err(ReceiverError::Stale) + ); + } + #[test] fn every_signed_header_is_required_and_bound() { for name in HEADERS { diff --git a/crates/registry-platform-httpsec/Cargo.toml b/crates/registry-platform-httpsec/Cargo.toml index ef1780c393..0332ab1ecd 100644 --- a/crates/registry-platform-httpsec/Cargo.toml +++ b/crates/registry-platform-httpsec/Cargo.toml @@ -12,7 +12,19 @@ workspace = true [features] default = ["server"] -server = ["dep:axum", "dep:tokio", "dep:tower", "dep:tower-http", "dep:ulid", "dep:url"] +server = [ + "dep:axum", + "dep:tokio", + "dep:tower", + "dep:tower-http", + "dep:ulid", + "dep:url", +] + +# Implements authcommon's `RefusalTraceId` for `TraceId`, so a service passes +# its request trace id to `record_refusal!`. Opt-in because authcommon reaches +# the crypto stack, which a service that only serves HTTP does not carry. +refusal-trace-id = ["server", "dep:registry-platform-authcommon"] [[test]] name = "integration" @@ -21,6 +33,9 @@ required-features = ["server"] [dependencies] axum = { workspace = true, optional = true } http.workspace = true +registry-platform-authcommon = { workspace = true, optional = true } +registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true @@ -31,4 +46,5 @@ ulid = { workspace = true, optional = true } url = { workspace = true, optional = true } [dev-dependencies] +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } tokio.workspace = true diff --git a/crates/registry-platform-httpsec/README.md b/crates/registry-platform-httpsec/README.md index 6f08728ea4..0f085410c3 100644 --- a/crates/registry-platform-httpsec/README.md +++ b/crates/registry-platform-httpsec/README.md @@ -8,8 +8,14 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. - Restrictive CSP header generation through `CspBuilder`, including a `deny_by_default` policy (`default-src 'none'`) and an optional `form-action` directive for server-rendered forms. -- `security_headers` middleware for CSP, content sniffing, referrer, and frame - protections. +- `security_headers(csp, posture)` middleware for CSP, content sniffing, + referrer, and frame protections. A development process also marks every + response with `Registry-Posture: development`, overwriting a value a handler + set. A production process sends no mark. `security_headers_without_posture` + is the transitional entry point for a caller that holds no posture yet, and + behaves as production. +- `posture_mark(posture)`, a layer that only sets the development mark, for + routers that do not use `security_headers`. - Conditional Cross-Origin-Resource-Policy handling. - Request body limit layer construction. - RFC 9457 Problem Details responses with `application/problem+json`. @@ -22,7 +28,19 @@ Client-safe HTTP validation plus Axum and Tower helpers for HTTP security. 422 framework bodies in the service's own problem vocabulary through a caller-supplied mapping from `FrameworkRejection`. - `TraceId` and `TraceContext`, the shared strict W3C `traceparent` transport - primitives for Registry service responses. + primitives for Registry service responses. With the `refusal-trace-id` + feature, which pulls in `registry-platform-authcommon` and so the crypto + stack, `TraceId` implements `registry_platform_authcommon::RefusalTraceId`, so a + service passes its request trace id to `record_refusal!`. +- `loopback`, a re-export of `registry-platform-loopback`, the one definition + of loopback for outbound destinations and loopback origins: + `loopback_address`, `loopback_host` and `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped + form of `127.0.0.0/8` is loopback, and so is the exact name `localhost` + once the connection is pinned to loopback addresses + (`LoopbackHost::pinned_by`). A site that accepts the name must pin the + connection; a site that cannot pin uses `loopback_literal`. Bind sites keep + their own, stricter rule. The module is available with + `default-features = false`. - `ProblemBody`, the fixed value-free Registry Stack problem envelope with `type`, `title`, `status`, `detail`, `code`, and `traceId` members. - `response_trace_id` for exact-one canonical W3C v0 response correlation. @@ -38,6 +56,7 @@ use axum::{http::Method, Router}; use registry_platform_httpsec::{ corp_conditional, request_body_limit, security_headers, CorsPolicy, CspBuilder, }; +use registry_platform_posture::Posture; let cors = CorsPolicy { allowed_origins: vec!["https://app.example.test".to_string()], @@ -48,7 +67,7 @@ let cors = CorsPolicy { let app = Router::new() .layer(corp_conditional()) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers(CspBuilder::restrictive(), Posture::Production)) .layer(cors.layer()) .layer(request_body_limit(1024 * 1024)); let _ = app; @@ -61,6 +80,7 @@ let _ = app; - HTTPS origins are accepted. HTTP origins are accepted only for loopback development origins. - Existing security headers are preserved when `security_headers` is applied. + The development posture mark is the exception: it overwrites. - Invalid, duplicate, or absent inbound `traceparent` values receive a fresh server trace. One valid lower-case W3C version 0 `traceparent` is retained. Caller `tracestate` is never echoed. diff --git a/crates/registry-platform-httpsec/src/lib.rs b/crates/registry-platform-httpsec/src/lib.rs index ac050841db..d913d8b3e8 100644 --- a/crates/registry-platform-httpsec/src/lib.rs +++ b/crates/registry-platform-httpsec/src/lib.rs @@ -1,6 +1,7 @@ //! HTTP security primitives shared by Registry Stack servers and clients. mod client; +pub use registry_platform_loopback as loopback; pub use client::{ response_trace_id, ProblemDocument, ProblemDocumentError, ResponseTraceError, TraceId, diff --git a/crates/registry-platform-httpsec/src/server.rs b/crates/registry-platform-httpsec/src/server.rs index 3b52a6ecb4..a2bbe6a7c9 100644 --- a/crates/registry-platform-httpsec/src/server.rs +++ b/crates/registry-platform-httpsec/src/server.rs @@ -14,6 +14,7 @@ use axum::body::Body; use axum::http::header::{HeaderName, HeaderValue, CONTENT_TYPE}; use axum::http::{HeaderMap, Method, Request, Response, StatusCode}; use axum::response::IntoResponse; +use registry_platform_posture::{Posture, POSTURE_HEADER}; use serde::Serialize; use serde_json::Value; use tower::{Layer, Service}; @@ -103,6 +104,13 @@ fn parse_traceparent(value: &str) -> Option { }) } +// The request trace id is the one value `record_refusal!` takes from a request: +// it is a validated W3C trace id, so it carries no other caller text. +#[cfg(feature = "refusal-trace-id")] +impl registry_platform_authcommon::__refusal_trace_id_seal::Sealed for TraceId {} +#[cfg(feature = "refusal-trace-id")] +impl registry_platform_authcommon::RefusalTraceId for TraceId {} + fn fresh_span_id() -> String { let value = u128::from(Ulid::generate()); let span = u64::try_from(value & u128::from(u64::MAX)).unwrap_or(1); @@ -337,10 +345,87 @@ fn checked_sources(sources: &[&'static str]) -> Vec<&'static str> { /// HSTS for deployments that terminate TLS upstream or serve plain HTTP. pub const DEFAULT_HSTS_VALUE: &str = "max-age=63072000; includeSubDomains"; -pub fn security_headers(csp: CspBuilder) -> SecurityHeadersLayer { +/// The shared response-header baseline for a service of the given posture. +/// +/// A development process also marks every response with `Registry-Posture: +/// development`, overwriting a value a handler set. A production process sends +/// no mark, so an absent field makes no claim. +pub fn security_headers(csp: CspBuilder, posture: Posture) -> SecurityHeadersLayer { SecurityHeadersLayer { csp: csp.header_value(), hsts: Some(HeaderValue::from_static(DEFAULT_HSTS_VALUE)), + posture, + } +} + +/// [`security_headers`] for a caller that does not yet hold a posture. It +/// behaves as production: no mark is sent. +pub fn security_headers_without_posture(csp: CspBuilder) -> SecurityHeadersLayer { + security_headers(csp, Posture::Production) +} + +/// A layer that only sets the posture mark, for routers that do not use +/// [`security_headers`]. A development process sets `Registry-Posture: +/// development` on every response, overwriting a handler value. A production +/// process sets nothing. +pub fn posture_mark(posture: Posture) -> PostureMarkLayer { + PostureMarkLayer { posture } +} + +fn mark_development(response: &mut Response, posture: Posture) { + if posture == Posture::Development { + response.headers_mut().insert( + HeaderName::from_static(POSTURE_HEADER), + HeaderValue::from_static(Posture::Development.as_str()), + ); + } +} + +#[derive(Debug, Clone)] +pub struct PostureMarkLayer { + posture: Posture, +} + +impl Layer for PostureMarkLayer { + type Service = PostureMarkService; + + fn layer(&self, inner: S) -> Self::Service { + PostureMarkService { + inner, + posture: self.posture, + } + } +} + +#[derive(Debug, Clone)] +pub struct PostureMarkService { + inner: S, + posture: Posture, +} + +impl Service> for PostureMarkService +where + S: Service, Response = Response> + Send + 'static, + S::Future: Send + 'static, + S::Error: Send + 'static, + ResBody: Send + 'static, +{ + type Response = Response; + type Error = S::Error; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, request: Request) -> Self::Future { + let future = self.inner.call(request); + let posture = self.posture; + Box::pin(async move { + let mut response = future.await?; + mark_development(&mut response, posture); + Ok(response) + }) } } @@ -352,6 +437,7 @@ pub struct SecurityHeadersLayer { /// [`SecurityHeadersLayer::without_hsts`] for deployments that terminate /// TLS upstream or serve plain HTTP. hsts: Option, + posture: Posture, } impl SecurityHeadersLayer { @@ -383,6 +469,7 @@ impl Layer for SecurityHeadersLayer { inner, csp: self.csp.clone(), hsts: self.hsts.clone(), + posture: self.posture, } } } @@ -392,6 +479,7 @@ pub struct SecurityHeadersService { inner: S, csp: HeaderValue, hsts: Option, + posture: Posture, } impl Service> for SecurityHeadersService @@ -413,6 +501,7 @@ where let future = self.inner.call(request); let csp = self.csp.clone(); let hsts = self.hsts.clone(); + let posture = self.posture; Box::pin(async move { let mut response = future.await?; insert_if_missing( @@ -454,6 +543,7 @@ where hsts_value, ); } + mark_development(&mut response, posture); Ok(response) }) } @@ -739,11 +829,7 @@ fn is_loopback_origin(url: &url::Url) -> bool { let Some(host) = url.host() else { return false; }; - match host { - url::Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"), - url::Host::Ipv4(ip) => ip.is_loopback(), - url::Host::Ipv6(ip) => ip.is_loopback(), - } + crate::loopback::loopback_host(&host.to_string()).is_some() } #[cfg(test)] @@ -808,6 +894,30 @@ mod tests { assert!(TraceId::parse("not-a-trace").is_err()); } + #[cfg(feature = "refusal-trace-id")] + #[test] + fn the_request_trace_id_is_the_one_a_refusal_line_takes() { + use registry_platform_authcommon::{ + record_refusal, FailedCheck, RefusalNote, RefusalRecorder, + }; + + // Caller text never becomes a trace id, so it cannot reach a refusal + // line through the macro's `trace_id` field. + assert!(TraceId::parse("canary-request-value-7f3a").is_err()); + + let recorder = RefusalRecorder::new("httpsec").unwrap(); + let trace = TraceContext::server_created(); + let note = RefusalNote::new(FailedCheck::Scope); + record_refusal!(recorder, note, trace_id = &trace.trace_id); + record_refusal!(recorder, note, trace_id = trace.trace_id.clone()); + record_refusal!( + recorder, + note, + trace_id = TraceId::parse("4bf92f3577b34da6a3ce929d0e0e4736").unwrap() + ); + assert_eq!(recorder.counter().get(&["scope"]), Some(3)); + } + #[test] fn version_zero_traceparent_rejects_non_lowercase_hex() { for value in [ @@ -1009,16 +1119,16 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("content-security-policy"), HeaderValue::from_static("default-src 'none'"), ); Ok::<_, std::convert::Infallible>(response) - }, - )); + }), + ); let response = service .oneshot(Request::new(Body::empty())) @@ -1064,11 +1174,11 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>(Response::new(Body::empty())) - }, - )); + }), + ); let response = service .oneshot(Request::new(Body::empty())) .await @@ -1086,7 +1196,7 @@ mod tests { use tower::service_fn; use tower::ServiceExt; - let service = security_headers(CspBuilder::restrictive()) + let service = security_headers_without_posture(CspBuilder::restrictive()) .without_hsts() .layer(service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>(Response::new(Body::empty())) @@ -1104,6 +1214,105 @@ mod tests { ); } + async fn mark_of(layer: L, handler_mark: Option<&'static str>) -> Option + where + L: Layer< + tower::util::BoxCloneService, Response, std::convert::Infallible>, + >, + L::Service: Service, Response = Response> + Send + 'static, + >>::Error: std::fmt::Debug, + >>::Future: Send + 'static, + { + use tower::ServiceExt; + + let inner = tower::service_fn(move |_request: Request| async move { + let mut response = Response::new(Body::empty()); + if let Some(value) = handler_mark { + response.headers_mut().insert( + HeaderName::from_static(registry_platform_posture::POSTURE_HEADER), + HeaderValue::from_static(value), + ); + } + Ok::<_, std::convert::Infallible>(response) + }); + let response = layer + .layer(tower::util::BoxCloneService::new(inner)) + .oneshot(Request::new(Body::empty())) + .await + .expect("service responds"); + response + .headers() + .get(registry_platform_posture::POSTURE_HEADER) + .cloned() + } + + #[tokio::test] + async fn development_security_headers_set_the_mark_over_a_handler_value() { + let layer = security_headers(CspBuilder::restrictive(), Posture::Development); + assert_eq!( + mark_of(layer.clone(), None).await, + Some(HeaderValue::from_static("development")) + ); + assert_eq!( + mark_of(layer, Some("production")).await, + Some(HeaderValue::from_static("development")), + "the layer overwrites a value a handler set" + ); + } + + #[tokio::test] + async fn production_security_headers_set_no_mark_and_leave_handler_values() { + let layer = security_headers(CspBuilder::restrictive(), Posture::Production); + assert_eq!(mark_of(layer.clone(), None).await, None); + assert_eq!( + mark_of(layer, Some("handler")).await, + Some(HeaderValue::from_static("handler")), + "production neither adds nor strips the field" + ); + } + + #[tokio::test] + async fn transitional_security_headers_behave_as_production() { + let layer = security_headers_without_posture(CspBuilder::restrictive()); + assert_eq!(mark_of(layer, None).await, None); + } + + #[tokio::test] + async fn development_posture_mark_sets_the_field_on_a_bare_service() { + let layer = posture_mark(Posture::Development); + assert_eq!( + mark_of(layer.clone(), None).await, + Some(HeaderValue::from_static("development")) + ); + assert_eq!( + mark_of(layer, Some("production")).await, + Some(HeaderValue::from_static("development")) + ); + } + + #[tokio::test] + async fn production_posture_mark_sets_nothing() { + let layer = posture_mark(Posture::Production); + assert_eq!(mark_of(layer, None).await, None); + } + + #[tokio::test] + async fn development_posture_mark_applies_to_an_axum_router() { + use tower::ServiceExt; + + let router = axum::Router::new() + .route("/", axum::routing::get(|| async { "ok" })) + .layer(posture_mark(Posture::Development)); + let response = router + .oneshot(Request::new(Body::empty())) + .await + .expect("router responds"); + assert_eq!( + response.headers().get("registry-posture"), + Some(&HeaderValue::from_static("development")) + ); + } + #[test] fn conditional_corp_matches_cors_response() { let mut response = Response::new(()); diff --git a/crates/registry-platform-httputil/Cargo.toml b/crates/registry-platform-httputil/Cargo.toml index be5d793624..272e9ea4a9 100644 --- a/crates/registry-platform-httputil/Cargo.toml +++ b/crates/registry-platform-httputil/Cargo.toml @@ -27,6 +27,8 @@ ipnet.workspace = true registry-platform-authcommon.workspace = true registry-platform-canonical-json.workspace = true registry-platform-crypto.workspace = true +registry-platform-loopback.workspace = true +registry-platform-posture.workspace = true reqwest.workspace = true rustls-native-certs.workspace = true serde.workspace = true diff --git a/crates/registry-platform-httputil/README.md b/crates/registry-platform-httputil/README.md index f93d29e747..33276890eb 100644 --- a/crates/registry-platform-httputil/README.md +++ b/crates/registry-platform-httputil/README.md @@ -13,6 +13,13 @@ Outbound HTTP utilities for registry services. `FetchUrlPolicy` for user-controlled destinations. - `read_bounded` for response bodies with content-length and streaming byte limits. +- `validate_response_headers(headers, PeerPolicy)` for response header bounds + and the peer posture check: `PeerPolicy::RefuseDevelopmentPeer` returns + `ResponseHeaderError::DevelopmentPeer` for a response whose + `Registry-Posture` field is exactly `development`. Every client construction + site chooses the policy. `is_loopback_host` is the one loopback host rule + (a loopback address literal or the exact name `localhost`), valid in every + posture. - `ServiceBaseUrl`, bearer token providers, and `PrivateKeyJwt` for hardened credential-bearing clients without product semantics. The private-key-JWT provider uses a closed `client_credentials` request shape. Its `exchange` @@ -133,13 +140,13 @@ async fn fetch_document() -> Result, Box> { `DestinationProfile::PrivateServiceHttp` refuse `localhost` and every `*.localhost` name when the binding is constructed, including trailing-dot absolute names and regardless of allowed private CIDRs. Local receivers - require `DestinationProfile::LoopbackDevelopmentHttp`. + require `DestinationProfile::LoopbackHttp`. - `FetchUrlPolicy::strict` allows HTTPS only and denies localhost, private ranges, link-local ranges, and cloud metadata endpoints. - Known metadata endpoints include link-local metadata services and public-IP metadata services such as `100.100.100.200`; IPv4-mapped IPv6 literals are normalized before classification. -- `FetchUrlPolicy::dev` allows HTTP and HTTPS, but plain HTTP is allowed only +- `FetchUrlPolicy::https_or_loopback` allows HTTP and HTTPS, but plain HTTP is allowed only for loopback hosts. Non-loopback private ranges stay denied. - `FetchUrlPolicy::validate` is deprecated compatibility. It resolves the host but discards DNS evidence, so it is not sufficient protection for a later @@ -167,6 +174,8 @@ async fn fetch_document() -> Result, Box> { ## Features - Default: `rustls`. +- `test-support`: test-only profiles such as `DestinationProfile::PinnedLoopbackHttpsTest` + and `DestinationProfile::LocalPrivateDevelopmentHttp`. ## Testing diff --git a/crates/registry-platform-httputil/src/client/exchange_authorization.rs b/crates/registry-platform-httputil/src/client/exchange_authorization.rs index e84a9a1f07..4553be278f 100644 --- a/crates/registry-platform-httputil/src/client/exchange_authorization.rs +++ b/crates/registry-platform-httputil/src/client/exchange_authorization.rs @@ -323,7 +323,7 @@ impl ExchangeAssertionSource for RemoteAssertionSource { kind: send_failure_kind(&error), })?; let status = response.status().as_u16(); - if crate::validate_response_headers(response.headers()).is_err() { + if crate::validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(TokenError::Protocol { status }); } if status != 200 { @@ -1374,7 +1374,7 @@ mod tests { ) .unwrap(); provider.bearer_token().await.unwrap(); - let provider = provider.with_fetch_url_policy(crate::FetchUrlPolicy::dev()); + let provider = provider.with_fetch_url_policy(crate::FetchUrlPolicy::https_or_loopback()); provider.bearer_token().await.unwrap(); assert_eq!(server.received_requests().await.unwrap().len(), 2); } diff --git a/crates/registry-platform-httputil/src/client/mod.rs b/crates/registry-platform-httputil/src/client/mod.rs index fabfee825c..22516844b7 100644 --- a/crates/registry-platform-httputil/src/client/mod.rs +++ b/crates/registry-platform-httputil/src/client/mod.rs @@ -20,8 +20,8 @@ pub use exchange_authorization::{ }; pub use exchange_config::exchange_authorization_from_json; pub use outbound::{ - base_url_without_userinfo, build_client, read_failure_kind, send_failure_kind, - transport_protects_the_credential, OutboundOptions, + base_url_without_userinfo, build_client, is_loopback_host, read_failure_kind, + send_failure_kind, transport_protects_the_credential, OutboundOptions, }; pub use private_key_jwt::{ valid_resource_uri, valid_scope_token, validate_requested_scopes, PrivateKeyJwt, diff --git a/crates/registry-platform-httputil/src/client/outbound.rs b/crates/registry-platform-httputil/src/client/outbound.rs index a1b935c193..b957e872c8 100644 --- a/crates/registry-platform-httputil/src/client/outbound.rs +++ b/crates/registry-platform-httputil/src/client/outbound.rs @@ -11,10 +11,6 @@ use url::Url; use super::TransportKind; -/// The one host name a cleartext URL may carry. It is reserved for the loopback -/// interface, so a credential sent to it cannot leave the host. -const LOOPBACK_NAME: &str = "localhost"; - /// What a caller may vary about an outbound client. Everything else is fixed by /// [`build_client`]. #[derive(Debug, Clone, Copy)] @@ -43,21 +39,26 @@ pub fn build_client(options: OutboundOptions<'_>) -> Result) -> bool { + crate::loopback::loopback_host(&host.to_string()).is_some() +} + /// Whether this URL's transport keeps a secret sent to it away from the network. /// -/// A secret in cleartext is only acceptable when it cannot leave the host, which -/// is the local development and tutorial case. The accepted forms are the ones an -/// adopter types: either loopback numeric family, or the reserved name -/// `localhost`. Any other name is refused, because a name that happens to resolve -/// to a loopback address is still resolved off-host, and the answer can change. +/// A secret in cleartext is only acceptable when it cannot leave the host: https, +/// or http to a host on the loopback transport class ([`is_loopback_host`]). The +/// client built by [`build_client`] is pinned to the loopback addresses for +/// `localhost`, so that name is never resolved off-host. pub fn transport_protects_the_credential(url: &Url) -> bool { match url.scheme() { "https" => true, - "http" => url.host().is_some_and(|host| match host { - url::Host::Ipv4(ip) => ip.is_loopback(), - url::Host::Ipv6(ip) => ip.is_loopback(), - url::Host::Domain(name) => name == LOOPBACK_NAME, - }), + "http" => url.host().is_some_and(|host| is_loopback_host(&host)), _ => false, } } @@ -159,6 +160,61 @@ mod tests { (address, listener, held) } + #[test] + fn cleartext_is_protected_only_on_loopback() { + for raw in [ + "http://127.0.0.1/", + "http://127.9.9.9:8080/", + "http://[::1]/", + "http://[::ffff:127.0.0.1]/", + "http://localhost:8080/", + "http://LOCALHOST/", + "https://example.org/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(transport_protects_the_credential(&url), "{raw}"); + } + for raw in [ + "http://a.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://[::ffff:10.0.0.1]/", + "http://0.0.0.0/", + "http://example.org/", + "ftp://127.0.0.1/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(!transport_protects_the_credential(&url), "{raw}"); + } + } + + #[test] + fn the_loopback_host_rule_accepts_numeric_loopback_and_the_exact_name_localhost() { + for raw in [ + "http://127.0.0.1/", + "http://127.9.9.9/", + "http://[::1]/", + "http://[::ffff:127.0.0.1]/", + "http://localhost/", + "http://LOCALHOST/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(is_loopback_host(&url.host().expect("host")), "{raw}"); + } + for raw in [ + "http://a.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://[::ffff:10.0.0.1]/", + "http://0.0.0.0/", + "http://[fe80::1]/", + "http://example.org/", + ] { + let url = Url::parse(raw).expect("url"); + assert!(!is_loopback_host(&url.host().expect("host")), "{raw}"); + } + } + #[tokio::test] async fn a_connect_timeout_is_a_connection_failure() { let (address, _listener, _held) = unanswered_address().await; diff --git a/crates/registry-platform-httputil/src/client/private_key_jwt.rs b/crates/registry-platform-httputil/src/client/private_key_jwt.rs index a646681ec0..6a4760e264 100644 --- a/crates/registry-platform-httputil/src/client/private_key_jwt.rs +++ b/crates/registry-platform-httputil/src/client/private_key_jwt.rs @@ -35,7 +35,9 @@ use std::{ time::{Duration, Instant}, }; -use crate::{read_bounded, validate_response_headers, FetchUrlError, FetchUrlPolicy}; +use crate::{ + read_bounded, validate_response_headers_without_peer_policy, FetchUrlError, FetchUrlPolicy, +}; use async_trait::async_trait; use chrono::Utc; use registry_platform_authcommon::client_assertion::{ @@ -557,8 +559,8 @@ impl PrivateKeyJwtConfig { /// /// Existing consumers retain their configured-endpoint behavior unless /// they opt in. Discovery-driven clients should always opt in, using - /// [`FetchUrlPolicy::strict`] in production and [`FetchUrlPolicy::dev`] - /// only for an explicitly selected local development profile. + /// [`FetchUrlPolicy::strict`] unless the endpoint may be on loopback, where + /// [`FetchUrlPolicy::https_or_loopback`] admits plain HTTP to the loopback class. #[must_use] pub fn with_fetch_url_policy(mut self, policy: FetchUrlPolicy) -> Self { self.fetch_url_policy = Some(policy); @@ -1067,7 +1069,7 @@ impl PrivateKeyJwt { })?; let status = response.status().as_u16(); - if validate_response_headers(response.headers()).is_err() { + if validate_response_headers_without_peer_policy(response.headers()).is_err() { return Err(TokenError::Protocol { status }); } let media_type = exact_content_type(response.headers()).map(str::to_owned); @@ -1639,7 +1641,7 @@ mod tests { let clock = Arc::new(TestClock::new(NOW)); let provider = PrivateKeyJwt::with_clock( config(endpoint(&server.uri()), client_key(Some(KEY_ID))) - .with_fetch_url_policy(FetchUrlPolicy::dev()), + .with_fetch_url_policy(FetchUrlPolicy::https_or_loopback()), clock, ) .expect("the DNS-pinned provider is usable"); @@ -1683,7 +1685,7 @@ mod tests { let clock = Arc::new(TestClock::new(NOW)); let provider = PrivateKeyJwt::with_clock( config(endpoint(&server.uri()), client_key(Some(KEY_ID))) - .with_fetch_url_policy(FetchUrlPolicy::dev()), + .with_fetch_url_policy(FetchUrlPolicy::https_or_loopback()), clock, ) .expect("the DNS-pinned provider is usable"); diff --git a/crates/registry-platform-httputil/src/destination.rs b/crates/registry-platform-httputil/src/destination.rs index 02acc1243f..68306093d3 100644 --- a/crates/registry-platform-httputil/src/destination.rs +++ b/crates/registry-platform-httputil/src/destination.rs @@ -267,9 +267,11 @@ pub enum DestinationProfile { ProductionHttps, /// Plain HTTP for one signed service hop confined to private addresses. PrivateServiceHttp, - /// Plain HTTP to an explicitly configured loopback host for development. - LoopbackDevelopmentHttp, - /// Plain HTTP to one exact, explicitly allowed private IP for local development. + /// Plain HTTP to an explicit loopback host: a loopback address literal or the + /// exact name `localhost`. Valid in every posture. + LoopbackHttp, + /// Test-only plain HTTP to one exact, explicitly allowed private IP. + #[cfg(any(test, feature = "test-support"))] LocalPrivateDevelopmentHttp, /// Test-only HTTPS profile that remains confined to loopback addresses. #[cfg(any(test, feature = "test-support"))] @@ -441,6 +443,8 @@ impl FixedDestinationPolicy { /// allocation. An origin id is canonical lowercase ASCII using alphanumeric /// characters with internal `.`, `_`, `:`, or `-` separators. Each CIDR /// must be wholly contained by RFC 1918, RFC 6598 CGNAT, or IPv6 ULA space. + /// A [`DestinationProfile::PrivateServiceHttp`] destination needs at least + /// one CIDR, since it sends only to addresses inside the listed ranges. pub fn new( origin_id: &str, origin: &str, @@ -513,7 +517,7 @@ impl FixedDestinationPolicy { DestinationProfile::PrivateServiceHttp if origin.scheme() != "http" => { return Err(DestinationPolicyError::PrivateServiceRequiresHttp); } - DestinationProfile::LoopbackDevelopmentHttp => { + DestinationProfile::LoopbackHttp => { if origin.scheme() != "http" { return Err(DestinationPolicyError::DevelopmentRequiresHttp); } @@ -521,6 +525,7 @@ impl FixedDestinationPolicy { return Err(DestinationPolicyError::DevelopmentRequiresLoopbackHost); } } + #[cfg(any(test, feature = "test-support"))] DestinationProfile::LocalPrivateDevelopmentHttp => { if origin.scheme() != "http" { return Err(DestinationPolicyError::LocalPrivateDevelopmentRequiresHttp); @@ -559,6 +564,12 @@ impl FixedDestinationPolicy { #[cfg(any(test, feature = "test-support"))] DestinationProfile::PinnedLoopbackHttpsTest => {} } + // A private service hop admits only addresses inside the listed + // ranges, so with none it could never send. Refuse it here, at + // activation, rather than at the first send. + if profile == DestinationProfile::PrivateServiceHttp && allowed_private_cidrs.is_empty() { + return Err(DestinationPolicyError::PrivateServiceRequiresPrivateCidr); + } if dns_family == DestinationDnsFamily::Ipv4Only && allowed_private_cidrs @@ -925,24 +936,24 @@ impl FixedDestinationPolicy { if !is_eligible_private_address(ip) { return Err(DestinationSendError::PrivateAddressNotAllowed); } - if self.allowed_private_cidrs.is_empty() - || self - .allowed_private_cidrs - .iter() - .any(|cidr| cidr.contains(&ip)) + if self + .allowed_private_cidrs + .iter() + .any(|cidr| cidr.contains(&ip)) { Ok(()) } else { Err(DestinationSendError::PrivateAddressNotAllowed) } } - DestinationProfile::LoopbackDevelopmentHttp => { + DestinationProfile::LoopbackHttp => { if is_loopback(ip) { Ok(()) } else { Err(DestinationSendError::DevelopmentAddressDenied) } } + #[cfg(any(test, feature = "test-support"))] DestinationProfile::LocalPrivateDevelopmentHttp => { if is_cloud_metadata_ip(ip) { return Err(DestinationSendError::CloudMetadataDenied); @@ -1237,6 +1248,10 @@ pub enum DestinationPolicyError { ProductionRequiresHttps, #[error("private service destination requires HTTP")] PrivateServiceRequiresHttp, + #[error( + "private service destination requires at least one private CIDR; name the range that holds the service's addresses" + )] + PrivateServiceRequiresPrivateCidr, #[error("destination profile denies the localhost namespace")] LocalhostNamespaceDenied, #[error("loopback development destination requires HTTP")] @@ -1662,6 +1677,7 @@ impl HeaderValueTemplate { } } +#[derive(PartialEq)] enum HeaderTemplateInput<'a> { Dynamic { name: &'a str, @@ -1677,6 +1693,7 @@ enum RequestTemplateKind { General(DestinationMethod), OAuth2ClientCredentials(OAuth2ClientCredentialsBodyFormat), EventDelivery, + SignedEventDelivery, } /// Slot-typed, immutable request shape compiled before any sensitive values exist. @@ -1759,6 +1776,19 @@ pub struct EventDeliveryHeaders<'a> { pub signature: &'a [u8], } +/// Caller-supplied Standard Webhooks header values. +pub struct SignedEventHeaders<'a> { + pub id: &'a [u8], + pub timestamp: &'a [u8], + pub signature: &'a [u8], +} + +impl fmt::Debug for SignedEventHeaders<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("SignedEventHeaders([REDACTED])") + } +} + impl fmt::Debug for EventDeliveryHeaders<'_> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("EventDeliveryHeaders([REDACTED])") @@ -1964,6 +1994,48 @@ impl BoundedDestinationRequestTemplate { ) } + /// Compile a fixed JSON POST with the Standard Webhooks headers. + pub fn signed_event_delivery( + fixed_path: &str, + max_body_bytes: usize, + max_request_bytes: usize, + ) -> Result { + Self::new_with_headers( + RequestTemplateKind::SignedEventDelivery, + fixed_path, + &[], + &SIGNED_EVENT_HEADERS, + DestinationAuthorizationTemplate::Forbidden, + DestinationBodyTemplate::Required { + max_bytes: max_body_bytes, + }, + max_request_bytes, + ) + } + + /// Render Standard Webhooks headers and already-canonical JSON bytes. + pub fn render_signed_event( + &self, + headers: SignedEventHeaders<'_>, + body: Vec, + ) -> Result { + self.render_signed_event_zeroizing(headers, Zeroizing::new(body)) + } + + /// Render a signed event with a body already held in zeroizing storage. + pub fn render_signed_event_zeroizing( + &self, + headers: SignedEventHeaders<'_>, + body: Zeroizing>, + ) -> Result { + self.render_zeroizing( + &[], + &[headers.id, headers.timestamp, headers.signature], + None, + Some(body), + ) + } + /// Render caller-owned event metadata and already-canonical JSON bytes. pub fn render_event( &self, @@ -2575,7 +2647,9 @@ impl BoundedDestinationRequestTemplate { RequestTemplateKind::OAuth2ClientCredentials(format) => { (DestinationMethod::OAuth2ClientCredentialsPost, Some(format)) } - RequestTemplateKind::EventDelivery => (DestinationMethod::EventPost, None), + RequestTemplateKind::EventDelivery | RequestTemplateKind::SignedEventDelivery => { + (DestinationMethod::EventPost, None) + } }; validate_fixed_destination_path(fixed_path)?; if query.len() > MAX_DESTINATION_REQUEST_QUERY_COMPONENTS { @@ -2596,7 +2670,13 @@ impl BoundedDestinationRequestTemplate { return Err(DestinationRequestError::MethodSlotMismatch); } if method == DestinationMethod::EventPost - && (!query.is_empty() || !closed_event_headers(headers)) + && (!query.is_empty() + || !match kind { + RequestTemplateKind::SignedEventDelivery => { + closed_signed_event_headers(headers) + } + _ => closed_event_headers(headers), + }) { return Err(DestinationRequestError::MethodSlotMismatch); } @@ -3005,6 +3085,33 @@ fn closed_event_headers(headers: &[HeaderTemplateInput<'_>]) -> bool { }) } +const SIGNED_EVENT_HEADERS: [HeaderTemplateInput<'static>; 5] = [ + HeaderTemplateInput::Exact { + name: "accept", + value: b"application/json", + }, + HeaderTemplateInput::Exact { + name: "content-type", + value: b"application/json", + }, + HeaderTemplateInput::Dynamic { + name: "webhook-id", + max_value_bytes: 256, + }, + HeaderTemplateInput::Dynamic { + name: "webhook-timestamp", + max_value_bytes: 20, + }, + HeaderTemplateInput::Dynamic { + name: "webhook-signature", + max_value_bytes: 256, + }, +]; + +fn closed_signed_event_headers(headers: &[HeaderTemplateInput<'_>]) -> bool { + headers == SIGNED_EVENT_HEADERS +} + struct BoundedTargetWriter { bytes: Zeroizing>, limit: usize, @@ -4653,24 +4760,26 @@ fn is_valid_header_value(value: &[u8]) -> bool { } fn validate_response_headers(headers: &HeaderMap) -> Result<(), DestinationSendError> { - match crate::validate_response_headers(headers) { + // The delivering process's peer policy is not threaded to destinations yet, so + // this check keeps to the bounds and accepts every peer posture. + match crate::validate_response_headers(headers, crate::PeerPolicy::AcceptDevelopmentPeer) { Ok(()) => Ok(()), - Err(crate::ResponseHeaderBoundError::TooManyFields) => { + Err(crate::ResponseHeaderError::TooManyFields) => { Err(DestinationSendError::TooManyResponseHeaders) } - Err(crate::ResponseHeaderBoundError::HeadersTooLarge) => { + Err(crate::ResponseHeaderError::HeadersTooLarge) => { Err(DestinationSendError::ResponseHeaderBytesExceeded) } + Err(crate::ResponseHeaderError::DevelopmentPeer) => { + unreachable!("a policy that accepts development peers never refuses one") + } } } fn origin_explicitly_denotes_loopback(origin: &Url) -> bool { - match origin.host() { - Some(::url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - Some(::url::Host::Ipv4(ip)) => ip.is_loopback(), - Some(::url::Host::Ipv6(ip)) => is_loopback(normalize_ipv4_mapped(IpAddr::V6(ip))), - None => false, - } + origin + .host() + .is_some_and(|host| crate::loopback::loopback_host(&host.to_string()).is_some()) } /// RFC 6761 reserves `localhost.` and every name below it for loopback. A @@ -4687,6 +4796,7 @@ fn origin_uses_localhost_namespace(origin: &Url) -> bool { } } +#[cfg(any(test, feature = "test-support"))] fn origin_explicit_private_ip(origin: &Url) -> Option { match origin.host() { Some(::url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)), @@ -4695,6 +4805,7 @@ fn origin_explicit_private_ip(origin: &Url) -> Option { } } +#[cfg(any(test, feature = "test-support"))] fn private_cidr_is_exact_host(cidr: IpNet, address: IpAddr) -> bool { match (cidr, address) { (IpNet::V4(cidr), IpAddr::V4(address)) => { @@ -4708,10 +4819,7 @@ fn private_cidr_is_exact_host(cidr: IpNet, address: IpAddr) -> bool { } fn is_loopback(ip: IpAddr) -> bool { - match normalize_ipv4_mapped(ip) { - IpAddr::V4(ip) => ip.is_loopback(), - IpAddr::V6(ip) => ip.is_loopback(), - } + crate::loopback::loopback_address(ip) } fn is_always_denied_in_production(ip: IpAddr) -> bool { @@ -5234,7 +5342,7 @@ mod tests { let policy = DataDestinationPolicy::new( "private-data", "http://127.0.0.1:9443/", - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("loopback policy") @@ -5562,19 +5670,14 @@ mod tests { "http://[::1]:8080/", "http://[::ffff:127.0.0.1]:8080/", ] { - DataDestinationPolicy::new( - "dev-data", - raw, - DestinationProfile::LoopbackDevelopmentHttp, - &[], - ) - .unwrap_or_else(|error| panic!("{raw} should validate: {error}")); + DataDestinationPolicy::new("dev-data", raw, DestinationProfile::LoopbackHttp, &[]) + .unwrap_or_else(|error| panic!("{raw} should validate: {error}")); } assert_eq!( DataDestinationPolicy::new( "dev-data", "http://service.test:8080/", - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .unwrap_err(), @@ -5671,21 +5774,54 @@ mod tests { #[test] fn private_service_http_is_dns_pinned_to_private_address_space() { - let policy = DataDestinationPolicy::new( + let error = DataDestinationPolicy::new( "private-service", "http://registry-service:8080/", DestinationProfile::PrivateServiceHttp, &[], ) - .expect("private service destination validates"); - assert_eq!(classify(&policy, &["10.89.0.4"]), Ok(())); - assert_eq!(classify(&policy, &["fd42::4"]), Ok(())); - for address in ["127.0.0.1", "169.254.169.254", "8.8.8.8", "::1"] { + .expect_err("an empty private range list is refused at activation, not at the first send"); + assert_eq!( + error, + DestinationPolicyError::PrivateServiceRequiresPrivateCidr + ); + assert!(error.to_string().contains("private CIDR"), "{error}"); + for profile in [ + DestinationProfile::ProductionHttps, + DestinationProfile::LoopbackHttp, + ] { + let origin = match profile { + DestinationProfile::ProductionHttps => "https://registry.example/", + _ => "http://127.0.0.1:8080/", + }; + DataDestinationPolicy::new("destination", origin, profile, &[]) + .expect("a public or loopback destination needs no private range"); + } + + let listed = DataDestinationPolicy::new( + "private-service", + "http://registry-service:8080/", + DestinationProfile::PrivateServiceHttp, + &[cidr("10.0.0.0/8")], + ) + .expect("listed private service destination validates"); + assert_eq!(classify(&listed, &["10.0.0.5"]), Ok(())); + assert_eq!( + classify(&listed, &["fd42::4"]), + Err(DestinationSendError::PrivateAddressNotAllowed), + "a private address outside the listed ranges stays refused at send" + ); + for address in ["127.0.0.1", "8.8.8.8", "::1"] { assert!( - classify(&policy, &[address]).is_err(), + classify(&listed, &[address]).is_err(), "private service accepted {address}" ); } + assert_eq!( + classify(&listed, &["169.254.169.254"]), + Err(DestinationSendError::CloudMetadataDenied), + "a metadata address stays refused beside a listed range" + ); let narrowed = DataDestinationPolicy::new( "private-service", @@ -6998,7 +7134,7 @@ mod tests { let strict = DataDestinationPolicy::new( "strict-data", &origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("legacy constructor remains valid"); @@ -7022,7 +7158,7 @@ mod tests { let ipv4_only = DataDestinationPolicy::new_with_dns_family( "ipv4-data", &origin, - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], DestinationDnsFamily::Ipv4Only, ) @@ -7085,7 +7221,7 @@ mod tests { let policy = DataDestinationPolicy::new( "dev-data", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development policy validates"); @@ -7160,7 +7296,7 @@ mod tests { let policy = CredentialDestinationPolicy::new( "dev-oauth", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development credential policy validates"); @@ -7237,7 +7373,7 @@ mod tests { let policy = CredentialDestinationPolicy::new( "dev-oauth-basic", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development credential policy validates"); @@ -7422,6 +7558,58 @@ mod tests { ); } + #[test] + fn the_signed_event_template_admits_exactly_its_five_headers() { + let template = EventDestinationRequestTemplate::signed_event_delivery( + "/hooks", + 256, + MAX_TEST_EVENT_REQUEST_BYTES, + ) + .unwrap(); + let request = template + .render_signed_event( + SignedEventHeaders { + id: b"event", + timestamp: b"123", + signature: b"v1,signature", + }, + b"{}".to_vec(), + ) + .unwrap(); + assert_eq!(request.method, DestinationMethod::EventPost); + let headers: Vec<_> = request + .headers + .iter() + .map(|header| (header.name.as_str(), header.value.as_slice())) + .collect(); + assert_eq!( + headers, + [ + ("accept", b"application/json".as_slice()), + ("content-type", b"application/json"), + ("webhook-id", b"event"), + ("webhook-timestamp", b"123"), + ("webhook-signature", b"v1,signature"), + ] + ); + for (id, timestamp, signature) in [ + (vec![b'a'; 257], vec![b'1'; 20], vec![b'a'; 256]), + (vec![b'a'; 256], vec![b'1'; 21], vec![b'a'; 256]), + (vec![b'a'; 256], vec![b'1'; 20], vec![b'a'; 257]), + ] { + assert!(template + .render_signed_event( + SignedEventHeaders { + id: &id, + timestamp: ×tamp, + signature: &signature + }, + b"{}".to_vec(), + ) + .is_err()); + } + } + #[test] fn event_post_is_confined_to_its_closed_slot_and_canonical_shape() { let canonical = br#"{"event":"widget.tombstoned","generation":42}"#; @@ -7659,7 +7847,7 @@ mod tests { let policy = EventDestinationPolicy::new( "dev-events", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development event policy"); @@ -7763,7 +7951,7 @@ mod tests { let policy = EventDestinationPolicy::new( "dev-event-bounds", &format!("http://localhost:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("development event policy"); @@ -8346,7 +8534,7 @@ mod tests { DataDestinationPolicy::new( "message-provider", &format!("http://127.0.0.1:{}/", address.port()), - DestinationProfile::LoopbackDevelopmentHttp, + DestinationProfile::LoopbackHttp, &[], ) .expect("loopback send policy validates") diff --git a/crates/registry-platform-httputil/src/lib.rs b/crates/registry-platform-httputil/src/lib.rs index 305a78274e..d3adef3298 100644 --- a/crates/registry-platform-httputil/src/lib.rs +++ b/crates/registry-platform-httputil/src/lib.rs @@ -8,6 +8,8 @@ use thiserror::Error; pub mod client; pub mod destination; +pub mod probe; +pub use registry_platform_loopback as loopback; pub use client::{ exchange_authorization_from_json, valid_resource_uri, valid_scope_token, @@ -30,42 +32,83 @@ pub const MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES: usize = 1024 * 1024; /// Maximum certificates accepted in one outbound client's pinned CA bundle. pub const MAXIMUM_TRUSTED_ROOT_CERTIFICATES: usize = 32; -/// Value-free reason a response's headers exceeded the shared client bounds. +/// Whether a runtime refuses a response whose peer declares the development posture. +/// +/// There is no default: every client construction site chooses. A production runtime +/// passes [`PeerPolicy::RefuseDevelopmentPeer`], a development runtime passes +/// [`PeerPolicy::AcceptDevelopmentPeer`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PeerPolicy { + /// Refuse a response that declares the development posture. + RefuseDevelopmentPeer, + /// Accept a response whatever posture it declares. + AcceptDevelopmentPeer, +} + +/// Value-free reason a response's headers were refused by the shared client checks. #[derive(Debug, Error, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] -pub enum ResponseHeaderBoundError { +pub enum ResponseHeaderError { #[error("the response carries too many header fields")] TooManyFields, #[error("the response headers exceed the configured maximum")] HeadersTooLarge, + #[error( + "the peer declared the development posture; a production runtime refuses its responses" + )] + DevelopmentPeer, } -/// Enforce strict field-count and aggregate-byte bounds before inspecting response headers. -pub fn validate_response_headers(headers: &HeaderMap) -> Result<(), ResponseHeaderBoundError> { +/// Enforce strict field-count and aggregate-byte bounds before inspecting response headers, +/// then refuse a development-marked peer when `peer` says to. +/// +/// The peer's posture field is the exact value `development`. An absent field, +/// `production`, or any other value passes. +pub fn validate_response_headers( + headers: &HeaderMap, + peer: PeerPolicy, +) -> Result<(), ResponseHeaderError> { let mut count = 0usize; let mut total = 0usize; for (name, value) in headers { count = count .checked_add(1) - .ok_or(ResponseHeaderBoundError::TooManyFields)?; + .ok_or(ResponseHeaderError::TooManyFields)?; if count > MAXIMUM_RESPONSE_HEADER_FIELDS { - return Err(ResponseHeaderBoundError::TooManyFields); + return Err(ResponseHeaderError::TooManyFields); } let field_bytes = name .as_str() .len() .checked_add(value.as_bytes().len()) - .ok_or(ResponseHeaderBoundError::HeadersTooLarge)?; + .ok_or(ResponseHeaderError::HeadersTooLarge)?; total = total .checked_add(field_bytes) - .ok_or(ResponseHeaderBoundError::HeadersTooLarge)?; + .ok_or(ResponseHeaderError::HeadersTooLarge)?; if total > MAXIMUM_RESPONSE_HEADER_BYTES { - return Err(ResponseHeaderBoundError::HeadersTooLarge); + return Err(ResponseHeaderError::HeadersTooLarge); } } + if peer == PeerPolicy::RefuseDevelopmentPeer + && headers + .get_all(registry_platform_posture::POSTURE_HEADER) + .iter() + .any(|value| value.as_bytes() == registry_platform_posture::DEVELOPMENT.as_bytes()) + { + return Err(ResponseHeaderError::DevelopmentPeer); + } Ok(()) } +/// [`validate_response_headers`] with [`PeerPolicy::RefuseDevelopmentPeer`], for call +/// sites that have not yet received their runtime's policy. Removed once every client +/// takes a required [`PeerPolicy`]. +pub fn validate_response_headers_without_peer_policy( + headers: &HeaderMap, +) -> Result<(), ResponseHeaderError> { + validate_response_headers(headers, PeerPolicy::RefuseDevelopmentPeer) +} + /// Parse exactly one RFC 9110 delta-seconds `Retry-After` field within a caller bound. /// /// HTTP-date values, duplicate field lines, non-ASCII values, zero, and waits above @@ -85,6 +128,9 @@ pub const DEFAULT_VALIDATED_FETCH_TIMEOUT: Duration = Duration::from_secs(30); pub const DEFAULT_VALIDATED_FETCH_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); pub const DEFAULT_OUTBOUND_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +/// The one host name pinned to the loopback addresses in every built client. +const LOCALHOST_NAME: &str = "localhost"; + /// Builder for outbound HTTP clients used by platform fetchers. #[derive(Clone)] pub struct OutboundClientBuilder { @@ -172,7 +218,17 @@ impl OutboundClientBuilder { /// Fallibly build one hardened client with rustls, redirects and retries disabled, /// proxy environment variables ignored, and optional exact CA pinning. pub fn try_build(self) -> Result { - let mut builder = reqwest::Client::builder() + self.try_build_from(reqwest::Client::builder()) + } + + /// Apply every setting of [`Self::try_build`] to `builder`. Tests pass a + /// builder that carries their own resolver; every other caller goes + /// through [`Self::try_build`]. + fn try_build_from( + self, + builder: reqwest::ClientBuilder, + ) -> Result { + let mut builder = builder .timeout(self.timeout) .connect_timeout(self.connect_timeout) .redirect(reqwest::redirect::Policy::none()) @@ -199,6 +255,16 @@ impl OutboundClientBuilder { } builder = builder.tls_built_in_root_certs(false); } + // The name `localhost` is pinned to the loopback addresses, so no resolver + // is asked for it and a cleartext credential sent to it cannot leave the + // host. The port 0 takes the port of each request URL. + builder = builder.resolve_to_addrs( + LOCALHOST_NAME, + &[ + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0), + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0), + ], + ); if let Some((host, addrs)) = self.resolved_host { builder = builder.resolve_to_addrs(&host, &addrs); } @@ -383,11 +449,10 @@ impl FetchUrlPolicy { } } - /// Development preset: HTTP and HTTPS are allowed, but plain HTTP only - /// for loopback hosts. Non-loopback private ranges and cloud metadata - /// endpoints stay denied. + /// HTTPS, or plain HTTP to a loopback host. Valid in every posture. + /// Non-loopback private ranges and cloud metadata endpoints stay denied. #[must_use] - pub fn dev() -> Self { + pub fn https_or_loopback() -> Self { Self { allowed_schemes: vec!["http".to_string(), "https".to_string()], allow_localhost: true, @@ -735,12 +800,11 @@ fn resolve_host(url: &reqwest::Url) -> Result, FetchUrlError> { fn host_is_allowed_localhost(host: ::url::Host<&str>, resolved: &[IpAddr]) -> bool { match host { - ::url::Host::Ipv4(ip) => ip.is_loopback(), - ::url::Host::Ipv6(ip) => ip == Ipv6Addr::LOCALHOST, - ::url::Host::Domain(host) if host.eq_ignore_ascii_case("localhost") => { - resolved.iter().all(|ip| is_loopback_ip(*ip)) + ::url::Host::Ipv4(ip) => loopback::loopback_address(IpAddr::V4(ip)), + ::url::Host::Ipv6(ip) => loopback::loopback_address(IpAddr::V6(ip)), + ::url::Host::Domain(name) => { + loopback::loopback_host(name).is_some_and(|claim| claim.pinned_by(resolved)) } - ::url::Host::Domain(_) => false, } } @@ -762,10 +826,7 @@ pub fn is_cloud_metadata_ip(ip: IpAddr) -> bool { } fn is_loopback_ip(ip: IpAddr) -> bool { - match normalize_ipv4_mapped(ip) { - IpAddr::V4(ip) => ip.is_loopback(), - IpAddr::V6(ip) => ip.is_loopback(), - } + loopback::loopback_address(ip) } fn is_private_or_link_local_ip(ip: IpAddr) -> bool { @@ -963,7 +1024,7 @@ mod tests { async fn a_pinned_get_trusts_a_private_ca_only_when_it_is_named() { let (addr, authority, _) = serve_under_private_ca().await; let url = reqwest::Url::parse(&format!("https://{addr}/keys")).expect("target URL"); - let validated = FetchUrlPolicy::dev() + let validated = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("loopback HTTPS target"); @@ -1013,7 +1074,7 @@ mod tests { std::env::set_var("SSL_CERT_FILE", &bundle); let url = reqwest::Url::parse(&format!("https://{addr}/keys")).expect("target URL"); - let response = FetchUrlPolicy::dev() + let response = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("loopback HTTPS target") .immediate_get_with_timeout(Duration::from_secs(5)) @@ -1047,6 +1108,117 @@ mod tests { assert_eq!(response.status(), StatusCode::FOUND); } + /// Serve one route on `address` and return its URL with the host name + /// `localhost` and the bound port. + async fn serve_on(address: &str) -> String { + let listener = TcpListener::bind(address).await.expect("bind test server"); + let port = listener.local_addr().expect("read listener addr").port(); + let router = Router::new().route("/", get(|| async { "ok" })); + tokio::spawn(async move { + axum::serve(listener, router).await.expect("serve"); + }); + format!("http://localhost:{port}/") + } + + async fn reaches(client: &reqwest::Client, url: &str) -> bool { + match client.get(url).send().await { + Ok(response) => response.status() == StatusCode::OK, + Err(_) => false, + } + } + + #[tokio::test] + async fn an_override_with_port_zero_follows_the_url_port_and_only_the_listed_addresses() { + let v4_only = serve_on("127.0.0.1:0").await; + let v6_only = serve_on("[::1]:0").await; + let pinned_v4 = OutboundClientBuilder::new() + .resolve_to_addrs( + "localhost".to_string(), + vec!["127.0.0.1:0".parse().unwrap()], + ) + .try_build() + .expect("client"); + assert!( + reaches(&pinned_v4, &v4_only).await, + "port 0 takes the URL port" + ); + assert!( + !reaches(&pinned_v4, &v6_only).await, + "an address outside the override is never tried" + ); + } + + #[tokio::test] + async fn the_service_client_reaches_localhost_on_either_loopback_family() { + let v4_only = serve_on("127.0.0.1:0").await; + let v6_only = serve_on("[::1]:0").await; + let client = OutboundClientBuilder::new().try_build().expect("client"); + assert!(reaches(&client, &v4_only).await, "IPv4-only listener"); + assert!(reaches(&client, &v6_only).await, "IPv6-only listener"); + } + + /// Answers every name, `localhost` included, with an address off this + /// machine, as a hosts-file override or a hostile resolver could. + struct OffHostResolver { + asked_for_localhost: std::sync::Arc, + } + + impl reqwest::dns::Resolve for OffHostResolver { + fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { + if name.as_str().eq_ignore_ascii_case(LOCALHOST_NAME) { + self.asked_for_localhost + .store(true, std::sync::atomic::Ordering::SeqCst); + } + let off_host: reqwest::dns::Addrs = + Box::new(std::iter::once(SocketAddr::from(([192, 0, 2, 1], 0)))); + Box::pin(std::future::ready(Ok(off_host))) + } + } + + #[tokio::test] + async fn the_localhost_pin_holds_against_a_resolver_that_answers_off_host() { + let url = serve_on("127.0.0.1:0").await; + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let resolver = OffHostResolver { + asked_for_localhost: std::sync::Arc::clone(&asked), + }; + let client = OutboundClientBuilder::new() + .connect_timeout(Duration::from_millis(500)) + .try_build_from(reqwest::Client::builder().dns_resolver(std::sync::Arc::new(resolver))) + .expect("client"); + assert!( + reaches(&client, &url).await, + "localhost reaches the loopback listener" + ); + assert!( + !asked.load(std::sync::atomic::Ordering::SeqCst), + "the resolver is never asked for localhost" + ); + } + + #[test] + fn the_localhost_name_is_allowed_only_when_every_answer_is_loopback() { + let name = ::url::Host::Domain("localhost"); + let other: IpAddr = "10.0.0.1".parse().unwrap(); + let v4: IpAddr = "127.0.0.1".parse().unwrap(); + assert!(host_is_allowed_localhost(name.clone(), &[v4])); + assert!(!host_is_allowed_localhost(name.clone(), &[v4, other])); + assert!(!host_is_allowed_localhost(name, &[])); + assert!(!host_is_allowed_localhost( + ::url::Host::Domain("a.localhost"), + &[v4] + )); + } + + #[test] + fn an_ipv4_mapped_loopback_literal_is_loopback_for_a_dev_fetch_only() { + let url = reqwest::Url::parse("http://[::ffff:127.0.0.1]:8080/jwks").expect("url parses"); + FetchUrlPolicy::https_or_loopback() + .validate(&url) + .expect("a mapped loopback literal is loopback"); + assert!(FetchUrlPolicy::strict().validate(&url).is_err()); + } + #[test] fn outbound_clients_ignore_ambient_proxy_variables_in_an_isolated_process() { if std::env::var_os("REGISTRY_HTTP_PROXY_CHILD").is_some() { @@ -1086,7 +1258,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let url = reqwest::Url::parse(&format!("{base}/target")).expect("target URL"); - let response = FetchUrlPolicy::dev() + let response = FetchUrlPolicy::https_or_loopback() .validate_dns_pinned_for_immediate_fetch(&url) .expect("development loopback target") .immediate_get() @@ -1496,7 +1668,7 @@ mod tests { "https://[fd00:ec2::254]/latest/meta-data/", ] { let url = reqwest::Url::parse(raw).expect("url parses"); - let err = FetchUrlPolicy::dev() + let err = FetchUrlPolicy::https_or_loopback() .validate(&url) .expect_err("metadata target rejected"); assert!( @@ -1513,22 +1685,28 @@ mod tests { "http://127.42.0.1/jwks", "http://[::1]/jwks", "http://localhost/jwks", + "http://[::ffff:127.0.0.1]/jwks", ] { let url = reqwest::Url::parse(raw).expect("url parses"); - FetchUrlPolicy::dev() + FetchUrlPolicy::https_or_loopback() .validate(&url) - .unwrap_or_else(|err| panic!("dev policy should accept {raw}: {err}")); + .unwrap_or_else(|err| { + panic!("https-or-loopback policy should accept {raw}: {err}") + }); } for raw in [ "http://93.184.216.34/jwks", "http://10.0.0.1/jwks", - "http://[::ffff:127.0.0.1]/jwks", + "http://[::ffff:10.0.0.1]/jwks", + "http://[::ffff:93.184.216.34]/jwks", + "http://[::ffff:169.254.169.254]/jwks", + "http://[::ffff:0.0.0.0]/jwks", ] { let url = reqwest::Url::parse(raw).expect("url parses"); assert!( - FetchUrlPolicy::dev().validate(&url).is_err(), - "dev policy must reject {raw}" + FetchUrlPolicy::https_or_loopback().validate(&url).is_err(), + "https-or-loopback policy must reject {raw}" ); } } @@ -1542,8 +1720,8 @@ mod tests { ] { let url = reqwest::Url::parse(raw).expect("url parses"); assert!( - FetchUrlPolicy::dev().validate(&url).is_err(), - "dev policy must reject {raw}" + FetchUrlPolicy::https_or_loopback().validate(&url).is_err(), + "https-or-loopback policy must reject {raw}" ); } } @@ -1585,8 +1763,8 @@ mod tests { too_many.append("x-test", HeaderValue::from_str(&index.to_string()).unwrap()); } assert_eq!( - validate_response_headers(&too_many), - Err(ResponseHeaderBoundError::TooManyFields) + validate_response_headers(&too_many, PeerPolicy::AcceptDevelopmentPeer), + Err(ResponseHeaderError::TooManyFields) ); let mut too_large = HeaderMap::new(); @@ -1594,11 +1772,76 @@ mod tests { "x-canary", HeaderValue::from_bytes(&vec![b'a'; MAXIMUM_RESPONSE_HEADER_BYTES]).unwrap(), ); - let error = validate_response_headers(&too_large).unwrap_err(); - assert_eq!(error, ResponseHeaderBoundError::HeadersTooLarge); + let error = + validate_response_headers(&too_large, PeerPolicy::AcceptDevelopmentPeer).unwrap_err(); + assert_eq!(error, ResponseHeaderError::HeadersTooLarge); assert!(!error.to_string().contains("canary")); } + #[test] + fn peer_policy_table_covers_four_field_states_under_both_policies() { + let header_with = |value: Option<&str>| { + let mut headers = HeaderMap::new(); + if let Some(value) = value { + headers.insert( + registry_platform_posture::POSTURE_HEADER, + HeaderValue::from_str(value).unwrap(), + ); + } + headers + }; + let cases: [(Option<&str>, bool); 5] = [ + (None, false), + (Some("production"), false), + (Some("development"), true), + (Some("Development"), false), + (Some("staging"), false), + ]; + for (value, is_development) in cases { + let headers = header_with(value); + assert_eq!( + validate_response_headers(&headers, PeerPolicy::RefuseDevelopmentPeer), + if is_development { + Err(ResponseHeaderError::DevelopmentPeer) + } else { + Ok(()) + }, + "refuse, {value:?}" + ); + assert_eq!( + validate_response_headers(&headers, PeerPolicy::AcceptDevelopmentPeer), + Ok(()), + "accept, {value:?}" + ); + assert_eq!( + validate_response_headers_without_peer_policy(&headers), + validate_response_headers(&headers, PeerPolicy::RefuseDevelopmentPeer), + "transitional entry point behaves as production, {value:?}" + ); + } + } + + #[test] + fn bounds_are_checked_before_the_peer_posture_under_either_policy() { + let mut too_many = HeaderMap::new(); + for index in 0..=MAXIMUM_RESPONSE_HEADER_FIELDS { + too_many.append("x-test", HeaderValue::from_str(&index.to_string()).unwrap()); + } + too_many.insert( + registry_platform_posture::POSTURE_HEADER, + HeaderValue::from_static("development"), + ); + for policy in [ + PeerPolicy::RefuseDevelopmentPeer, + PeerPolicy::AcceptDevelopmentPeer, + ] { + assert_eq!( + validate_response_headers(&too_many, policy), + Err(ResponseHeaderError::TooManyFields) + ); + } + } + proptest! { #[test] fn append_path_segments_keeps_each_input_as_one_segment( diff --git a/crates/registry-platform-httputil/src/probe.rs b/crates/registry-platform-httputil/src/probe.rs new file mode 100644 index 0000000000..f5bd8dd546 --- /dev/null +++ b/crates/registry-platform-httputil/src/probe.rs @@ -0,0 +1,36 @@ +//! Paths and bodies of the liveness and readiness probes every Registry Stack +//! service answers. + +/// Path of the liveness probe. It needs no authentication and does no I/O. +pub const HEALTH_PATH: &str = "/health"; +/// Path of the readiness probe. It needs no authentication. +pub const READY_PATH: &str = "/ready"; +/// Body of a successful liveness probe, served as `application/json`. +pub const HEALTH_BODY: &str = r#"{"status":"ok"}"#; +/// Body of a successful readiness probe, served as `application/json`. +pub const READY_BODY: &str = r#"{"status":"ready"}"#; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_are_the_documented_probe_routes() { + assert_eq!(HEALTH_PATH, "/health"); + assert_eq!(READY_PATH, "/ready"); + } + + #[test] + fn bodies_are_json_objects_with_the_status_word() { + let health: serde_json::Value = serde_json::from_str(HEALTH_BODY).unwrap(); + let ready: serde_json::Value = serde_json::from_str(READY_BODY).unwrap(); + assert_eq!(health, serde_json::json!({"status": "ok"})); + assert_eq!(ready, serde_json::json!({"status": "ready"})); + } + + #[test] + fn bodies_are_compact_so_they_compare_byte_for_byte() { + assert_eq!(HEALTH_BODY, r#"{"status":"ok"}"#); + assert_eq!(READY_BODY, r#"{"status":"ready"}"#); + } +} diff --git a/crates/registry-platform-loopback/Cargo.toml b/crates/registry-platform-loopback/Cargo.toml new file mode 100644 index 0000000000..71260a935e --- /dev/null +++ b/crates/registry-platform-loopback/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "registry-platform-loopback" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The one definition of loopback for outbound destinations and loopback origins." +repository.workspace = true +readme = "README.md" +publish = false + +[lints] +workspace = true diff --git a/crates/registry-platform-loopback/README.md b/crates/registry-platform-loopback/README.md new file mode 100644 index 0000000000..6c2ab577e0 --- /dev/null +++ b/crates/registry-platform-loopback/README.md @@ -0,0 +1,8 @@ +# Registry Platform Loopback + +`registry-platform-loopback` is the one definition of "loopback" for outbound destinations and loopback origins. It depends on nothing outside `std`, so a crate that only needs the rule does not pull in an HTTP server stack. + +- `loopback_address`, `loopback_host` and `loopback_literal`. A literal in `127.0.0.0/8`, `::1` or the IPv4-mapped form of `127.0.0.0/8` is loopback, and so is the exact name `localhost` once the connection is pinned to loopback addresses (`LoopbackHost::pinned_by`). `*.localhost`, `localhost.` and a bracketed IPv4 literal such as `[127.0.0.1]` are never loopback. +- A site that accepts the name `localhost` must pin the connection; a site that cannot pin uses `loopback_literal`. Bind sites keep their own, stricter rule. + +`registry-platform-httpsec` and `registry-platform-httputil` re-export this crate as `loopback`. diff --git a/crates/registry-platform-loopback/src/lib.rs b/crates/registry-platform-loopback/src/lib.rs new file mode 100644 index 0000000000..58aae8fa0b --- /dev/null +++ b/crates/registry-platform-loopback/src/lib.rs @@ -0,0 +1,157 @@ +//! The one definition of "loopback" for outbound destinations and loopback origins. +//! Bind sites keep their own, stricter rule. +//! +//! A host is loopback when it is an address literal in `127.0.0.0/8`, `::1`, or an +//! IPv4-mapped IPv6 form of an address in `127.0.0.0/8`, or when it is the exact +//! name `localhost` and the connection is made only to loopback addresses the +//! caller has checked. `*.localhost`, `localhost.` and every other name are never +//! loopback. + +use std::net::{IpAddr, Ipv6Addr}; + +/// The one name that may stand for the loopback interface. +const LOCALHOST: &str = "localhost"; + +/// True for `127.0.0.0/8`, `::1`, and IPv4-mapped IPv6 forms of `127.0.0.0/8`. +#[must_use] +pub fn loopback_address(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +/// How a host text claims to be loopback. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LoopbackHost { + /// An address literal that is loopback. + Literal(IpAddr), + /// The exact name `localhost`. It is loopback only when + /// [`LoopbackHost::pinned_by`] holds for the addresses the connection uses. + LocalhostName, +} + +impl LoopbackHost { + /// `Literal` is always pinned. `LocalhostName` is pinned when `resolved` is not + /// empty and every address in it is a loopback address. + #[must_use] + pub fn pinned_by(self, resolved: &[IpAddr]) -> bool { + match self { + Self::Literal(_) => true, + Self::LocalhostName => { + !resolved.is_empty() && resolved.iter().all(|ip| loopback_address(*ip)) + } + } + } +} + +/// Classify a URL host. `[::1]` and `::1` are both accepted. Returns `None` for every +/// other host. +/// +/// `loopback_host(..).is_some()` treats the bare name `localhost` as loopback. A +/// site that accepts the name that way must also pin the connection to loopback +/// addresses, as [`LoopbackHost::pinned_by`] checks, or a hosts file or resolver +/// can send it off the machine. A site that cannot pin uses [`loopback_literal`]. +#[must_use] +pub fn loopback_host(host: &str) -> Option { + if host.eq_ignore_ascii_case(LOCALHOST) { + return Some(LoopbackHost::LocalhostName); + } + loopback_literal(host).map(LoopbackHost::Literal) +} + +/// The literal arm alone, for a site that cannot pin a name. Brackets are +/// accepted around an IPv6 literal only, as in a URL host. +#[must_use] +pub fn loopback_literal(host: &str) -> Option { + let ip = match host + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + { + Some(inner) => IpAddr::V6(inner.parse::().ok()?), + None => host.parse().ok()?, + }; + loopback_address(ip).then_some(ip) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn loopback_claims_are_exactly_the_literals_and_the_name() { + for host in [ + "127.0.0.1", + "127.255.255.254", + "::1", + "[::1]", + "::ffff:127.0.0.1", + "[::ffff:127.0.0.1]", + "localhost", + "LOCALHOST", + ] { + assert!(loopback_host(host).is_some(), "{host} is a loopback claim"); + } + for host in [ + "localhost.", + "a.localhost", + "127.0.0.1.example", + "0.0.0.0", + "::", + "10.0.0.1", + "169.254.169.254", + "[::ffff:10.0.0.1]", + "[::1", + "::1]", + "[127.0.0.1]", + "[127.0.0.2]", + "[localhost]", + "", + ] { + assert!( + loopback_host(host).is_none(), + "{host:?} is not a loopback claim" + ); + } + } + + #[test] + fn the_name_is_a_name_claim_and_the_rest_are_literals() { + assert_eq!( + loopback_host("LocalHost"), + Some(LoopbackHost::LocalhostName) + ); + assert_eq!( + loopback_host("127.0.0.2"), + Some(LoopbackHost::Literal("127.0.0.2".parse().unwrap())) + ); + assert!(loopback_literal("localhost").is_none()); + assert!(loopback_literal("[::1]").is_some()); + assert!(loopback_literal("[::ffff:127.0.0.1]").is_some()); + assert!( + loopback_literal("[127.0.0.1]").is_none(), + "a bracketed IPv4 literal is not a URL host" + ); + } + + #[test] + fn a_name_claim_needs_every_resolved_address_to_be_loopback() { + let name = LoopbackHost::LocalhostName; + let v4: IpAddr = "127.0.0.1".parse().unwrap(); + let v6: IpAddr = "::1".parse().unwrap(); + let mapped: IpAddr = "::ffff:127.0.0.1".parse().unwrap(); + let other: IpAddr = "10.0.0.1".parse().unwrap(); + assert!(!name.pinned_by(&[])); + assert!(name.pinned_by(&[v4, v6, mapped])); + assert!(!name.pinned_by(&[v4, other])); + assert!(!name.pinned_by(&[other, v6])); + assert!(LoopbackHost::Literal(v4).pinned_by(&[])); + } + + #[test] + fn loopback_address_covers_the_block_and_mapped_forms() { + for ip in ["127.0.0.1", "127.9.9.9", "::1", "::ffff:127.0.0.1"] { + assert!(loopback_address(ip.parse().unwrap()), "{ip}"); + } + for ip in ["0.0.0.0", "::", "10.0.0.1", "::ffff:10.0.0.1", "fe80::1"] { + assert!(!loopback_address(ip.parse().unwrap()), "{ip}"); + } + } +} diff --git a/crates/registry-platform-objectstore/src/s3.rs b/crates/registry-platform-objectstore/src/s3.rs index 530e1a540a..e7ef28493a 100644 --- a/crates/registry-platform-objectstore/src/s3.rs +++ b/crates/registry-platform-objectstore/src/s3.rs @@ -11,7 +11,8 @@ use registry_platform_config::{ ObjectStorageConfig, ProtectedSecret, SecretReference, SecretResolver, }; use registry_platform_httputil::{ - read_bounded, validate_response_headers, BoundedReadError, OutboundClientBuilder, + read_bounded, validate_response_headers_without_peer_policy, BoundedReadError, + OutboundClientBuilder, }; use reqwest::{ header::{HeaderMap, HeaderValue}, @@ -100,8 +101,8 @@ impl S3Settings { let mut url = Url::parse(text).map_err(|_| ObjectStoreError::InvalidConfiguration)?; let loopback = url .host_str() - .and_then(|host| host.trim_matches(['[', ']']).parse::().ok()) - .is_some_and(|ip| ip.is_loopback()); + .and_then(registry_platform_httputil::loopback::loopback_literal) + .is_some(); let bucket = config.bucket.as_str(); let region = config.region.as_str(); if text.len() > MAXIMUM_URL_BYTES @@ -405,7 +406,8 @@ impl S3ObjectStore { .send() .await .map_err(|_| ObjectStoreError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| ObjectStoreError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| ObjectStoreError::Unavailable)?; Ok(response) } diff --git a/crates/registry-platform-objectstore/src/s3_tests.rs b/crates/registry-platform-objectstore/src/s3_tests.rs index c07f87b04f..c6ae010064 100644 --- a/crates/registry-platform-objectstore/src/s3_tests.rs +++ b/crates/registry-platform-objectstore/src/s3_tests.rs @@ -337,6 +337,25 @@ fn strict_storage_configuration_and_debug_are_value_free() { settings(input).unwrap_err(), ObjectStoreError::InvalidConfiguration ); + for url in [ + "http://127.0.0.2:1234", + "http://[::1]:1234", + "http://[::ffff:127.0.0.1]:1234", + ] { + settings(raw(url)).unwrap_or_else(|error| panic!("{url}: {error:?}")); + } + for url in [ + "http://localhost:1234", + "http://storage.localhost:1234", + "http://0.0.0.0:1234", + "http://[::ffff:10.0.0.1]:1234", + ] { + assert_eq!( + settings(raw(url)).unwrap_err(), + ObjectStoreError::InvalidConfiguration, + "{url}" + ); + } let accepted = settings(raw("https://storage.example")).unwrap(); assert_eq!( accepted.bucket_url.as_str(), diff --git a/crates/registry-platform-objectstore/src/verifier.rs b/crates/registry-platform-objectstore/src/verifier.rs index 527f8333c5..3f0a9e694d 100644 --- a/crates/registry-platform-objectstore/src/verifier.rs +++ b/crates/registry-platform-objectstore/src/verifier.rs @@ -13,12 +13,14 @@ //! scanner and rules generation the operator bound the URL to, and enters //! only the binding digest a product records beside each verdict. -use std::{fmt, net::IpAddr, time::Duration}; +use std::{fmt, time::Duration}; use registry_platform_config::{ AttachmentVerifierConfig, ProtectedSecret, SecretReference, SecretResolver, }; -use registry_platform_httputil::{read_bounded, validate_response_headers, OutboundClientBuilder}; +use registry_platform_httputil::{ + read_bounded, validate_response_headers_without_peer_policy, OutboundClientBuilder, +}; use reqwest::{ header::{HeaderMap, HeaderValue}, StatusCode, Url, @@ -106,8 +108,8 @@ impl HttpVerifierSettings { let url = Url::parse(text).map_err(|_| VerifierError::InvalidConfiguration)?; let loopback = url .host_str() - .and_then(|host| host.trim_matches(['[', ']']).parse::().ok()) - .is_some_and(|ip| ip.is_loopback()); + .and_then(registry_platform_httputil::loopback::loopback_literal) + .is_some(); let policy_id = config.policy_id.as_str(); if text.len() > MAXIMUM_URL_BYTES || text.trim() != text @@ -225,7 +227,8 @@ impl HttpVerifier { .send() .await .map_err(|_| VerifierError::Unavailable)?; - validate_response_headers(response.headers()).map_err(|_| VerifierError::Unavailable)?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| VerifierError::Unavailable)?; if response.status() != StatusCode::OK { return Err(VerifierError::Unavailable); } diff --git a/crates/registry-platform-objectstore/src/verifier_tests.rs b/crates/registry-platform-objectstore/src/verifier_tests.rs index 9da8e14ab7..1ff1704327 100644 --- a/crates/registry-platform-objectstore/src/verifier_tests.rs +++ b/crates/registry-platform-objectstore/src/verifier_tests.rs @@ -143,6 +143,25 @@ fn verifier_config_is_strict_and_redacted() { "{url}" ); } + for url in [ + "http://127.0.0.2/verify", + "http://[::1]/verify", + "http://[::ffff:127.0.0.1]/verify", + ] { + settings(raw(url)).unwrap_or_else(|error| panic!("{url}: {error:?}")); + } + for url in [ + "http://localhost/verify", + "http://verifier.localhost/verify", + "http://0.0.0.0/verify", + "http://[::ffff:10.0.0.1]/verify", + ] { + assert_eq!( + settings(raw(url)).unwrap_err(), + VerifierError::InvalidConfiguration, + "{url}" + ); + } // The shared block's `Url` already refuses these at decode. for url in [ "https://user:secret@example/verify", diff --git a/crates/registry-platform-oidc/Cargo.toml b/crates/registry-platform-oidc/Cargo.toml index d1cba5fa5d..dd8b84d159 100644 --- a/crates/registry-platform-oidc/Cargo.toml +++ b/crates/registry-platform-oidc/Cargo.toml @@ -17,8 +17,10 @@ schema = ["dep:schemars"] [dependencies] base64.workspace = true jsonwebtoken.workspace = true +registry-platform-authcommon.workspace = true registry-platform-crypto = { workspace = true } registry-platform-httputil = { workspace = true } +registry-platform-posture.workspace = true registry-platform-config.workspace = true registry-platform-yaml.workspace = true uuid = { workspace = true, features = ["serde"] } @@ -29,7 +31,6 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true -tracing.workspace = true [dev-dependencies] axum.workspace = true diff --git a/crates/registry-platform-oidc/README.md b/crates/registry-platform-oidc/README.md index c16c245eee..dbaa742ee0 100644 --- a/crates/registry-platform-oidc/README.md +++ b/crates/registry-platform-oidc/README.md @@ -163,6 +163,14 @@ response ceiling. Products decide when the check precedes their effects and how failures map to their own API; the primitive owns no mutation or durable lifecycle state. +A runtime passes a `PeerPolicy` to the status client and to `GrantClaims::verify_context`. +Under `RefuseDevelopmentPeer`, a status answer whose `Registry-Posture` field is `development` +is refused as `TaskGrantError::DevelopmentPeer` (`platform.task-grant.development-peer`), and a +task assertion carrying the claim `registry_posture: development` is refused as +`GrantContextError::DevelopmentAssertion` (`platform.task-grant.development-assertion`). +Under `AcceptDevelopmentPeer` both are accepted. Any other value of `registry_posture` is a +malformed claim. The `*_without_peer_policy` forms behave as `RefuseDevelopmentPeer`. + ## Testing ```sh diff --git a/crates/registry-platform-oidc/src/authorization_claims.rs b/crates/registry-platform-oidc/src/authorization_claims.rs index 11c72e0ee3..513ae5d285 100644 --- a/crates/registry-platform-oidc/src/authorization_claims.rs +++ b/crates/registry-platform-oidc/src/authorization_claims.rs @@ -5,6 +5,7 @@ use std::collections::HashSet; use std::fmt; +use registry_platform_httputil::PeerPolicy; use serde::{Deserialize, Serialize}; use serde_json::Value; use thiserror::Error; @@ -27,6 +28,18 @@ const MAX_SCHEDULING_ACTIONS: usize = 32; /// obtained by token exchange does not carry it at all. pub const ASSERTION_ISSUER_CLAIM: &str = "registry_assertion_issuer"; +/// Optional claim by which an issuer in the development posture marks the +/// assertions it signs. Its only meaningful value is `development`. +/// +/// The issuer derives the value from its own posture, so a client cannot choose +/// it, and no first-party signer may declare it as one of its projected +/// attributes. +pub const POSTURE_CLAIM: &str = "registry_posture"; + +/// Machine-readable code for an assertion refused because it comes from a +/// development issuer. +pub const DEVELOPMENT_ASSERTION_CODE: &str = "platform.task-grant.development-assertion"; + const REGISTERED_OR_AUTHENTICATION_CLAIMS: &[&str] = &[ "iss", "sub", @@ -94,9 +107,9 @@ impl ClaimNames { || names .iter() .any(|name| REGISTERED_OR_AUTHENTICATION_CLAIMS.contains(&name.as_str())) - || names - .iter() - .any(|name| name.as_str() == ASSERTION_ISSUER_CLAIM) + || names.iter().any(|name| { + name.as_str() == ASSERTION_ISSUER_CLAIM || name.as_str() == POSTURE_CLAIM + }) || names.iter().collect::>().len() != names.len() { return Err(ClaimError::InvalidNames); @@ -333,6 +346,7 @@ pub struct GrantClaims { exp: u64, bounds: GrantBounds, approver: String, + development: bool, } impl GrantClaims { @@ -381,12 +395,26 @@ impl GrantClaims { &self.approver } + /// Whether the issuer marked this assertion as coming from the development posture. + #[must_use] + pub const fn is_development(&self) -> bool { + self.development + } + /// Bind immutable grant context to identities already selected by the verifier. + /// + /// Under [`PeerPolicy::RefuseDevelopmentPeer`] an assertion marked as coming from the + /// development posture is refused. Under [`PeerPolicy::AcceptDevelopmentPeer`] the mark + /// is not consulted. pub fn verify_context( &self, token: &VerifiedToken, verified_resource: &str, + peer: PeerPolicy, ) -> Result<(), GrantContextError> { + if self.development && peer == PeerPolicy::RefuseDevelopmentPeer { + return Err(GrantContextError::DevelopmentAssertion); + } let client = token .matched_client_id() .map_err(|_| GrantContextError::InvalidVerifiedClient)? @@ -399,6 +427,16 @@ impl GrantClaims { } Ok(()) } + + /// [`Self::verify_context`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn verify_context_without_peer_policy( + &self, + token: &VerifiedToken, + verified_resource: &str, + ) -> Result<(), GrantContextError> { + self.verify_context(token, verified_resource, PeerPolicy::RefuseDevelopmentPeer) + } } impl fmt::Debug for GrantClaims { @@ -414,6 +452,7 @@ impl fmt::Debug for GrantClaims { .field("exp", &self.exp) .field("bounds", &self.bounds) .field("approver", &"") + .field("development", &self.development) .finish() } } @@ -432,6 +471,7 @@ pub enum ClaimMember { GrantExpiration, GrantBounds, Approver, + Posture, } #[derive(Clone, Copy, Debug, Eq, Error, PartialEq)] @@ -467,6 +507,22 @@ pub enum GrantContextError { ClientMismatch, #[error("task grant resource does not match the verified resource")] ResourceMismatch, + #[error("task grant was issued in the development posture")] + DevelopmentAssertion, +} + +impl GrantContextError { + /// The machine-readable code of a refusal that has one. + #[must_use] + pub const fn code(self) -> Option<&'static str> { + match self { + Self::DevelopmentAssertion => Some(DEVELOPMENT_ASSERTION_CODE), + Self::MissingVerifiedClient + | Self::InvalidVerifiedClient + | Self::ClientMismatch + | Self::ResourceMismatch => None, + } + } } /// Extract the strict actor kind from a verified token. @@ -548,6 +604,11 @@ pub fn grant_claims( .map_err(|_| ClaimError::Malformed(ClaimMember::GrantBounds))?; bounds.validate()?; let approver = required_extra_string(claims, &names.approver, ClaimMember::Approver)?; + let development = match claims.extra.get(POSTURE_CLAIM) { + None => false, + Some(Value::String(value)) if value == registry_platform_posture::DEVELOPMENT => true, + Some(_) => return Err(ClaimError::Malformed(ClaimMember::Posture)), + }; Ok(Some(GrantClaims { principal, @@ -559,6 +620,7 @@ pub fn grant_claims( exp: grant_exp, bounds, approver, + development, })) } @@ -1261,9 +1323,12 @@ mod tests { matched_client: Some("azp:agent-client".to_owned()), scopes: Vec::new(), }; - assert_eq!(grant.verify_context(&token, "urn:registry:breg"), Ok(())); assert_eq!( - grant.verify_context(&token, "urn:registry:other"), + grant.verify_context_without_peer_policy(&token, "urn:registry:breg"), + Ok(()) + ); + assert_eq!( + grant.verify_context_without_peer_policy(&token, "urn:registry:other"), Err(GrantContextError::ResourceMismatch) ); @@ -1273,7 +1338,7 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&client_id_token, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&client_id_token, "urn:registry:breg"), Ok(()) ); @@ -1283,7 +1348,7 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&missing, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&missing, "urn:registry:breg"), Err(GrantContextError::MissingVerifiedClient) ); @@ -1293,11 +1358,101 @@ mod tests { scopes: Vec::new(), }; assert_eq!( - grant.verify_context(&malformed, "urn:registry:breg"), + grant.verify_context_without_peer_policy(&malformed, "urn:registry:breg"), Err(GrantContextError::InvalidVerifiedClient) ); } + fn posture_grant_and_token( + posture: Option, + ) -> Result<(GrantClaims, VerifiedToken), ClaimError> { + let mut extra = + complete_grant(json!({"type":"evidence","requirement":"urn:requirement:one"})); + if let Some(posture) = posture { + extra[POSTURE_CLAIM] = posture; + } + let input = claims(extra); + let grant = grant_claims(&input, &ClaimNames::default(), 1_500)?.expect("present"); + let token = VerifiedToken { + claims: input, + matched_client: Some("azp:agent-client".to_owned()), + scopes: Vec::new(), + }; + Ok((grant, token)) + } + + #[test] + fn the_peer_policy_decides_whether_a_development_assertion_is_accepted() { + use registry_platform_httputil::PeerPolicy::{ + AcceptDevelopmentPeer, RefuseDevelopmentPeer, + }; + let resource = "urn:registry:breg"; + let (ordinary, ordinary_token) = posture_grant_and_token(None).unwrap(); + let (development, development_token) = + posture_grant_and_token(Some(json!("development"))).unwrap(); + assert_eq!( + ordinary.verify_context(&ordinary_token, resource, RefuseDevelopmentPeer), + Ok(()) + ); + assert_eq!( + ordinary.verify_context(&ordinary_token, resource, AcceptDevelopmentPeer), + Ok(()) + ); + assert_eq!( + development.verify_context(&development_token, resource, RefuseDevelopmentPeer), + Err(GrantContextError::DevelopmentAssertion) + ); + assert_eq!( + development.verify_context(&development_token, resource, AcceptDevelopmentPeer), + Ok(()) + ); + assert_eq!( + development.verify_context_without_peer_policy(&development_token, resource), + Err(GrantContextError::DevelopmentAssertion) + ); + assert_eq!( + ordinary.verify_context_without_peer_policy(&ordinary_token, resource), + Ok(()) + ); + } + + #[test] + fn a_posture_claim_other_than_development_is_malformed() { + for value in [ + json!("production"), + json!("Development"), + json!(""), + json!(true), + json!(1), + json!(["development"]), + json!(null), + ] { + assert_eq!( + posture_grant_and_token(Some(value.clone())).map(|_| ()), + Err(ClaimError::Malformed(ClaimMember::Posture)), + "{value}" + ); + } + } + + #[test] + fn the_posture_claim_name_cannot_serve_another_role() { + let names = ClaimNames { + purpose: POSTURE_CLAIM.to_owned(), + ..ClaimNames::default() + }; + assert_eq!(names.validate(), Err(ClaimError::InvalidNames)); + } + + #[test] + fn the_development_assertion_refusal_has_its_own_code() { + assert_eq!( + GrantContextError::DevelopmentAssertion.code(), + Some("platform.task-grant.development-assertion") + ); + assert_eq!(GrantContextError::ClientMismatch.code(), None); + } + #[test] fn grant_debug_redacts_claim_values() { let input = claims(complete_grant( diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index 98af2a060b..99089d5851 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -1,61 +1,27 @@ //! Bounded diagnostic categories, independent of credential and configuration values. -use std::sync::{Mutex, PoisonError}; -use std::time::{Duration, Instant}; +use registry_platform_authcommon::FailedCheck; use crate::OidcError; -/// Fixed verification stages suitable for operational logs. -#[derive(Clone, Copy, Debug)] -pub enum AuthenticationStage { - Header, - Algorithm, - TokenType, - Key, - Signature, - Issuer, - Audience, - Time, - Client, - Scope, - Profile, - Unavailable, -} - -impl AuthenticationStage { - pub const fn label(self) -> &'static str { - match self { - Self::Header => "header", - Self::Algorithm => "algorithm", - Self::TokenType => "token-type", - Self::Key => "key", - Self::Signature => "signature", - Self::Issuer => "issuer", - Self::Audience => "audience", - Self::Time => "time", - Self::Client => "client", - Self::Scope => "scope", - Self::Profile => "profile", - Self::Unavailable => "unavailable", - } - } -} - impl OidcError { - /// Never format the underlying error to diagnose a public authentication failure. - pub fn authentication_stage(&self) -> AuthenticationStage { + /// The check a verification failure maps to. Never format the underlying + /// error to diagnose a public authentication failure. + pub fn failed_check(&self) -> FailedCheck { match self { - Self::MalformedToken | Self::InvalidToken => AuthenticationStage::Header, - Self::AlgorithmNotAllowed => AuthenticationStage::Algorithm, - Self::TokenTypeNotAllowed => AuthenticationStage::TokenType, - Self::MissingKid | Self::KidTooLong | Self::UnknownKid => AuthenticationStage::Key, - Self::SignatureInvalid => AuthenticationStage::Signature, - Self::IssuerMismatch { .. } => AuthenticationStage::Issuer, - Self::AudienceMismatch => AuthenticationStage::Audience, + Self::MalformedToken | Self::InvalidToken => FailedCheck::CredentialMalformed, + Self::AlgorithmNotAllowed => FailedCheck::TokenAlgorithm, + Self::TokenTypeNotAllowed => FailedCheck::TokenType, + Self::MissingKid | Self::KidTooLong | Self::UnknownKid => FailedCheck::TokenKey, + Self::SignatureInvalid => FailedCheck::TokenSignature, + Self::IssuerMismatch { .. } => FailedCheck::TokenIssuer, + Self::AudienceMismatch => FailedCheck::TokenAudience, + Self::SubjectMismatch => FailedCheck::TokenClaims, Self::TokenExpired | Self::TokenNotYetValid | Self::InvalidTimeClaims => { - AuthenticationStage::Time + FailedCheck::TokenTime } - Self::ClientNotAllowed | Self::AssertionIssuerNotAllowed => AuthenticationStage::Client, + Self::ClientNotAllowed => FailedCheck::TokenClient, + Self::AssertionIssuerNotAllowed => FailedCheck::TokenAssertionIssuer, Self::Transport(_) | Self::BoundedRead(_) | Self::FetchUrl(_) @@ -64,95 +30,128 @@ impl OidcError { | Self::Parse | Self::InvalidJwk | Self::EmptyKeySet + | Self::StaticKeySet(_) | Self::MissingIssuer | Self::ConflictingEndpointConfiguration | Self::InsecureHttpRequiresOptIn - | Self::EndpointRefused { .. } => AuthenticationStage::Unavailable, - } - } -} - -/// Log one value-free refusal at the call site's own tracing target, at most -/// once per stage per minute per verifier. `$message` is a literal naming the -/// product; the optional `remedy` is a fixed operator hint. -#[macro_export] -macro_rules! log_authentication_refusal { - ($verifier:expr, $stage:expr, $message:literal $(, remedy = $remedy:expr)?) => { - if let Some(stage) = $verifier.authentication_diagnostic($stage) { - $crate::__tracing::info!(stage, $(remedy = $remedy,)? $message); + | Self::EndpointRefused { .. } => FailedCheck::KeySourceUnavailable, } - }; -} - -/// At most one diagnostic per fixed stage per minute, per verifier. -/// The fixed array cannot grow with attacker-controlled inputs. -#[derive(Debug, Default)] -pub struct AuthenticationDiagnostics { - last: Mutex<[Option; 12]>, -} - -impl AuthenticationDiagnostics { - pub fn admit(&self, stage: AuthenticationStage) -> bool { - self.admit_at(stage, Instant::now()) } - fn admit_at(&self, stage: AuthenticationStage, now: Instant) -> bool { - // The guarded state is plain timestamps, so a poisoned lock is safe to reuse. - let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); - let slot = &mut last[stage as usize]; - if slot.is_some_and(|previous| { - now.saturating_duration_since(previous) < Duration::from_secs(60) - }) { - return false; - } - *slot = Some(now); - true + /// True when the verifier could not reach or use its key source. + pub fn is_key_source_unavailable(&self) -> bool { + self.failed_check() == FailedCheck::KeySourceUnavailable } } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn malformed_tokens_remain_header_failures() { - assert_eq!( - OidcError::MalformedToken.authentication_stage().label(), - "header" - ); - assert_eq!( - OidcError::InvalidToken.authentication_stage().label(), - "header" - ); - } +mod failed_check_tests { + use crate::{OidcEndpoint, OidcError, StaticJwksError}; + use registry_platform_authcommon::FailedCheck; + use registry_platform_httputil::{BoundedReadError, FetchUrlError}; #[test] - fn diagnostics_are_value_free_and_bounded_per_stage() { + fn issuer_mismatch_maps_without_the_issuers() { let error = OidcError::IssuerMismatch { expected: "canary-expected-issuer".into(), actual: "canary-actual-issuer".into(), }; - let stage = error.authentication_stage(); - assert_eq!(stage.label(), "issuer"); - assert!(!format!("{stage:?}").contains("canary")); - let diagnostics = AuthenticationDiagnostics::default(); - let now = Instant::now(); - assert!(diagnostics.admit_at(stage, now)); - for _ in 0..1000 { - assert!(!diagnostics.admit_at(stage, now)); - } - assert!(diagnostics.admit_at(AuthenticationStage::Audience, now)); - assert!(diagnostics.admit_at(stage, now + Duration::from_secs(60))); + let check = error.failed_check(); + assert_eq!(check, FailedCheck::TokenIssuer); + assert!(!format!("{check:?}{}", check.as_str()).contains("canary")); + } + + #[test] + fn key_source_failures_are_unavailable() { + assert!(OidcError::EmptyKeySet.is_key_source_unavailable()); + assert!(OidcError::InvalidUrl.is_key_source_unavailable()); + assert!(!OidcError::SignatureInvalid.is_key_source_unavailable()); } + /// One row per `OidcError` variant: the reviewable spec of the mapping. + /// A header the named key cannot serve is `AlgorithmNotAllowed`, a token + /// fault; `InvalidJwk` is reserved for a key the source should not have + /// published, a key-source fault. #[test] - fn a_poisoned_lock_keeps_admitting_diagnostics() { - let diagnostics = AuthenticationDiagnostics::default(); - let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _guard = diagnostics.last.lock().unwrap(); - panic!("poison the lock"); - })); - assert!(poisoned.is_err()); - assert!(diagnostics.admit(AuthenticationStage::Header)); + fn every_variant_maps_to_its_member() { + let transport = reqwest::Client::new() + .get("not a url") + .build() + .expect_err("an unparsable URL is a client error"); + let table = [ + ( + OidcError::Transport(transport), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::BoundedRead(BoundedReadError::LengthOverflow), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::FetchUrl(FetchUrlError::MissingHost), + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::HttpStatus(503), + FailedCheck::KeySourceUnavailable, + ), + (OidcError::InvalidUrl, FailedCheck::KeySourceUnavailable), + (OidcError::Parse, FailedCheck::KeySourceUnavailable), + ( + OidcError::IssuerMismatch { + expected: String::new(), + actual: String::new(), + }, + FailedCheck::TokenIssuer, + ), + (OidcError::MalformedToken, FailedCheck::CredentialMalformed), + (OidcError::AlgorithmNotAllowed, FailedCheck::TokenAlgorithm), + (OidcError::TokenTypeNotAllowed, FailedCheck::TokenType), + (OidcError::MissingKid, FailedCheck::TokenKey), + (OidcError::KidTooLong, FailedCheck::TokenKey), + (OidcError::UnknownKid, FailedCheck::TokenKey), + (OidcError::InvalidJwk, FailedCheck::KeySourceUnavailable), + (OidcError::EmptyKeySet, FailedCheck::KeySourceUnavailable), + ( + OidcError::StaticKeySet(StaticJwksError::Empty), + FailedCheck::KeySourceUnavailable, + ), + (OidcError::TokenExpired, FailedCheck::TokenTime), + (OidcError::TokenNotYetValid, FailedCheck::TokenTime), + (OidcError::AudienceMismatch, FailedCheck::TokenAudience), + (OidcError::SubjectMismatch, FailedCheck::TokenClaims), + (OidcError::SignatureInvalid, FailedCheck::TokenSignature), + (OidcError::InvalidToken, FailedCheck::CredentialMalformed), + (OidcError::InvalidTimeClaims, FailedCheck::TokenTime), + (OidcError::ClientNotAllowed, FailedCheck::TokenClient), + ( + OidcError::AssertionIssuerNotAllowed, + FailedCheck::TokenAssertionIssuer, + ), + (OidcError::MissingIssuer, FailedCheck::KeySourceUnavailable), + ( + OidcError::ConflictingEndpointConfiguration, + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::InsecureHttpRequiresOptIn, + FailedCheck::KeySourceUnavailable, + ), + ( + OidcError::EndpointRefused { + endpoint: OidcEndpoint::DeclaredJwks, + remedy: "a fixed remedy", + }, + FailedCheck::KeySourceUnavailable, + ), + ]; + for (error, expected) in table { + assert_eq!(error.failed_check(), expected, "{error:?}"); + assert_eq!( + error.is_key_source_unavailable(), + expected == FailedCheck::KeySourceUnavailable, + "{error:?}" + ); + } } } diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 820476fa45..c2b682d4b8 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -8,16 +8,15 @@ mod access_token_algorithm; mod authorization_claims; mod diagnostics; -pub use diagnostics::{AuthenticationDiagnostics, AuthenticationStage}; -#[doc(hidden)] -pub use tracing as __tracing; +mod static_jwks; +pub use static_jwks::{public_jwks_document, StaticJwksError}; pub mod task_grant; pub use access_token_algorithm::AccessTokenAlgorithm; pub use authorization_claims::{ actor_kind, grant_claims, ActorKind, BregPermission, ClaimError, ClaimMember, ClaimNames, GrantBounds, GrantClaims, GrantContextError, MatchedClientError, SchedulingPermission, - ASSERTION_ISSUER_CLAIM, + ASSERTION_ISSUER_CLAIM, DEVELOPMENT_ASSERTION_CODE, POSTURE_CLAIM, }; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -90,14 +89,10 @@ impl IssuerNetworkPolicy { { return Err(OidcError::InvalidUrl); } - let loopback = issuer.host_str().is_some_and(|host| { - host.eq_ignore_ascii_case("localhost") - || host - .trim_start_matches('[') - .trim_end_matches(']') - .parse::() - .is_ok_and(|address| address.is_loopback()) - }); + let loopback = issuer + .host_str() + .and_then(registry_platform_httputil::loopback::loopback_host) + .is_some(); if issuer.scheme() == "http" && !loopback && !allow_insecure_http { return Err(OidcError::InsecureHttpRequiresOptIn); } @@ -470,26 +465,40 @@ impl fmt::Debug for JwksFetcher { /// Parse an operator-supplied static JWKS document for /// [`JwksFetcher::new_static`]: a non-empty key set of RSA or elliptic-curve -/// keys, each with a non-empty `kid` no other key in the set repeats. A -/// symmetric key or an unnamed key is refused here, at startup, rather than -/// when a token first selects it. +/// public keys, each with a non-empty `kid` no other key in the set repeats. +/// A symmetric key, a private-key member or an unnamed key is refused here, +/// at startup, rather than when a token first selects it. The rule on members +/// is [`public_jwks_document`]. An OKP key passes that rule and is refused +/// here with [`StaticJwksError::OctetKeyPair`], which names its position, `kid` +/// and `crv`. A key with a member of the wrong shape is refused with +/// [`StaticJwksError::KeyShape`], which names its position. pub fn parse_static_jwks(bytes: &[u8]) -> Result { - let jwks: JwkSet = serde_json::from_slice(bytes).map_err(|_| OidcError::Parse)?; - if jwks.keys.is_empty() { - return Err(OidcError::EmptyKeySet); + let document = public_jwks_document(bytes)?; + let keys = document["keys"].as_array().into_iter().flatten(); + for (key, member) in keys.enumerate() { + if member["kty"] == "OKP" { + let label = |name: &str| member[name].as_str().map(str::to_owned); + return Err(StaticJwksError::OctetKeyPair { + key, + kid: label("kid"), + crv: label("crv"), + } + .into()); + } + // Parsing each key alone names the one a member of the wrong shape + // broke, which the whole-set parse below cannot. + if serde_json::from_value::(member.clone()).is_err() { + return Err(StaticJwksError::KeyShape { key }.into()); + } } - let mut kids = BTreeSet::new(); - let all_named_asymmetric = jwks.keys.iter().all(|key| { + let jwks: JwkSet = serde_json::from_value(document).map_err(|_| OidcError::Parse)?; + let all_asymmetric = jwks.keys.iter().all(|key| { matches!( key.algorithm, AlgorithmParameters::RSA(_) | AlgorithmParameters::EllipticCurve(_) - ) && key - .common - .key_id - .as_deref() - .is_some_and(|kid| !kid.is_empty() && kids.insert(kid)) + ) }); - if all_named_asymmetric { + if all_asymmetric { Ok(jwks) } else { Err(OidcError::InvalidJwk) @@ -955,14 +964,19 @@ fn validate_jwk(jwk: &Jwk) -> Result<(), OidcError> { Ok(()) } +/// Check that the key a token's `kid` names can serve the token's header +/// `alg`. A key the source should not publish stays [`OidcError::InvalidJwk`], +/// a key-source fault. A header the key cannot serve, including a `kid` that +/// names an encryption key, is [`OidcError::AlgorithmNotAllowed`]: the caller +/// chose that header, so it is a token fault. fn validate_jwk_for_header(jwk: &Jwk, header_alg: Algorithm) -> Result<(), OidcError> { validate_jwk(jwk)?; if jwk_family(jwk) != algorithm_family(header_alg) { - return Err(OidcError::InvalidJwk); + return Err(OidcError::AlgorithmNotAllowed); } if let Some(jwk_alg) = explicit_or_inferred_jwk_algorithm(jwk)? { if jwk_alg != header_alg { - return Err(OidcError::InvalidJwk); + return Err(OidcError::AlgorithmNotAllowed); } } Ok(()) @@ -1024,6 +1038,8 @@ fn explicit_or_inferred_jwk_algorithm(jwk: &Jwk) -> Result, Oi } } +/// A key whose declared `alg` is not a signing algorithm cannot verify any +/// token, so a header that names it fails as [`OidcError::AlgorithmNotAllowed`]. fn key_algorithm_to_jwt_algorithm(algorithm: KeyAlgorithm) -> Result { match algorithm { KeyAlgorithm::HS256 => Ok(Algorithm::HS256), @@ -1041,7 +1057,7 @@ fn key_algorithm_to_jwt_algorithm(algorithm: KeyAlgorithm) -> Result Err(OidcError::InvalidJwk), + | KeyAlgorithm::UNKNOWN_ALGORITHM => Err(OidcError::AlgorithmNotAllowed), } } @@ -1279,7 +1295,6 @@ impl VerifiedToken { #[derive(Debug)] pub struct TokenVerifier { - diagnostics: AuthenticationDiagnostics, config: TokenVerifierConfig, fetcher: Arc, allowed_clients: HashSet, @@ -1303,7 +1318,6 @@ impl TokenVerifier { let allowed_id_typ = normalize_typ_set(&config.allowed_id_typ); let allowed_userinfo_typ = normalize_typ_set(&config.allowed_userinfo_typ); Self { - diagnostics: AuthenticationDiagnostics::default(), config, fetcher, allowed_clients, @@ -1328,12 +1342,6 @@ impl TokenVerifier { self.verify_access_token(token, true).await } - /// One fixed category, at most once per stage per minute. No values from - /// the error, token, claims, or operator configuration are returned. - pub fn authentication_diagnostic(&self, stage: AuthenticationStage) -> Option<&'static str> { - self.diagnostics.admit(stage).then_some(stage.label()) - } - pub async fn verify_related_token(&self, token: &str) -> Result { self.verify_id_token(token).await } @@ -1489,10 +1497,10 @@ impl TokenVerifier { return Err(OidcError::AudienceMismatch); } let Some(access_sub) = access_token.claims.sub.as_deref() else { - return Err(OidcError::InvalidToken); + return Err(OidcError::SubjectMismatch); }; if data.claims.sub.as_deref() != Some(access_sub) { - return Err(OidcError::InvalidToken); + return Err(OidcError::SubjectMismatch); } Ok(data.claims) } @@ -1736,20 +1744,48 @@ fn map_jwt_error( expected_issuer: &str, token: &str, ) -> OidcError { + let issuer_mismatch = || OidcError::IssuerMismatch { + expected: expected_issuer.to_string(), + actual: issuer_from_untrusted_payload(token).unwrap_or_default(), + }; match error.kind() { JwtErrorKind::ExpiredSignature => OidcError::TokenExpired, JwtErrorKind::ImmatureSignature => OidcError::TokenNotYetValid, - JwtErrorKind::InvalidIssuer => OidcError::IssuerMismatch { - expected: expected_issuer.to_string(), - actual: issuer_from_untrusted_payload(token).unwrap_or_default(), - }, + JwtErrorKind::InvalidIssuer => issuer_mismatch(), JwtErrorKind::InvalidAudience => OidcError::AudienceMismatch, - JwtErrorKind::MissingRequiredClaim(claim) if claim == "exp" => OidcError::InvalidTimeClaims, + JwtErrorKind::MissingRequiredClaim(claim) => match claim.as_str() { + "aud" => OidcError::AudienceMismatch, + "iss" => issuer_mismatch(), + "exp" | "nbf" => OidcError::InvalidTimeClaims, + _ => OidcError::InvalidToken, + }, + JwtErrorKind::InvalidClaimFormat(_) => OidcError::InvalidTimeClaims, + JwtErrorKind::Json(_) if time_claim_is_malformed(token) => OidcError::InvalidTimeClaims, JwtErrorKind::InvalidSignature => OidcError::SignatureInvalid, _ => OidcError::InvalidToken, } } +/// True when a time claim is present but is not a whole number of seconds +/// [`Claims`] can hold. [`decode`] reports such a claim as a JSON error, +/// after the signature has been verified. +fn time_claim_is_malformed(token: &str) -> bool { + let Some(payload) = token.split('.').nth(1) else { + return false; + }; + let Ok(decoded) = URL_SAFE_NO_PAD.decode(payload) else { + return false; + }; + let Ok(claims) = serde_json::from_slice::>(&decoded) else { + return false; + }; + ["exp", "nbf", "iat"].iter().any(|name| { + claims + .get(*name) + .is_some_and(|value| !value.is_null() && value.as_i64().is_none()) + }) +} + fn issuer_from_untrusted_payload(token: &str) -> Option { let payload = token.split('.').nth(1)?; let decoded = URL_SAFE_NO_PAD.decode(payload).ok()?; @@ -1798,12 +1834,18 @@ pub enum OidcError { InvalidJwk, #[error("key set contains no usable keys")] EmptyKeySet, + #[error("static key set refused: {0}")] + StaticKeySet(#[from] StaticJwksError), #[error("token is expired")] TokenExpired, #[error("token is not yet valid")] TokenNotYetValid, #[error("token audience does not match")] AudienceMismatch, + /// A UserInfo response names another subject than the access token, or + /// the access token names none. + #[error("token subject does not match the access token")] + SubjectMismatch, #[error("token signature is invalid")] SignatureInvalid, #[error("token is invalid")] @@ -1840,10 +1882,12 @@ impl OidcEndpoint { #[cfg(test)] mod tests { use super::*; + use crate::static_jwks::tests::{keycloak_realm_jwks, KEYCLOAK_ENC_KID, KEYCLOAK_SIG_KID}; use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; use jsonwebtoken::{encode, EncodingKey, Header}; + use registry_platform_authcommon::FailedCheck; use serde_json::json; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use tokio::net::TcpListener; @@ -1927,6 +1971,33 @@ mod tests { .expect("IPv6 loopback keeps the same development behavior"); } + #[test] + fn issuer_loopback_follows_the_shared_definition() { + for issuer in [ + "http://127.0.0.1:8080", + "http://127.0.0.2:8080", + "http://[::1]:8080", + "http://[::ffff:127.0.0.1]:8080", + "http://localhost:8080", + "http://LOCALHOST:8080", + ] { + IssuerNetworkPolicy::new(issuer, false) + .unwrap_or_else(|error| panic!("{issuer}: {error:?}")); + } + for issuer in [ + "http://localhost.:8080", + "http://issuer.localhost:8080", + "http://0.0.0.0:8080", + "http://[::ffff:10.0.0.1]:8080", + ] { + let error = IssuerNetworkPolicy::new(issuer, false).expect_err(issuer); + assert!( + matches!(error, OidcError::InsecureHttpRequiresOptIn), + "{issuer}" + ); + } + } + #[test] fn a_cross_origin_jwks_must_use_https_even_under_the_http_opt_in() { let network = IssuerNetworkPolicy::new("http://93.184.216.34:8080", true).unwrap(); @@ -2409,7 +2480,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); TokenVerifier::new( TokenVerifierConfig { @@ -2484,9 +2555,36 @@ mod tests { validate_jwk_for_header(&rsa, Algorithm::RS256).expect("matching alg accepts"); assert!(matches!( validate_jwk_for_header(&rsa, Algorithm::RS384), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) + )); + assert!(matches!( + validate_jwk_for_header(&rsa, Algorithm::ES256), + Err(OidcError::AlgorithmNotAllowed) + )); + + let rsa_oaep: Jwk = serde_json::from_value(json!({ + "kty": "RSA", + "kid": "enc", + "alg": "RSA-OAEP", + "use": "enc", + "n": URL_SAFE_NO_PAD.encode(vec![0xff; 256]), + "e": "AQAB", + })) + .expect("RSA-OAEP JWK parses"); + assert!(matches!( + validate_jwk_for_header(&rsa_oaep, Algorithm::RS256), + Err(OidcError::AlgorithmNotAllowed) )); + let short = rsa_jwk_with_modulus_bytes("short", 128); + assert!( + matches!( + validate_jwk_for_header(&short, Algorithm::RS256), + Err(OidcError::InvalidJwk) + ), + "a key the source should not publish stays a key-source fault" + ); + let oct: Jwk = serde_json::from_value(json!({ "kty": "oct", "kid": "oct", @@ -2497,7 +2595,7 @@ mod tests { validate_jwk_for_header(&oct, Algorithm::HS256).expect("matching alg accepts"); assert!(matches!( validate_jwk_for_header(&oct, Algorithm::EdDSA), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) )); let p256: Jwk = serde_json::from_value(json!({ @@ -2510,10 +2608,154 @@ mod tests { validate_jwk_for_header(&p256, Algorithm::ES256).expect("matching curve accepts"); assert!(matches!( validate_jwk_for_header(&p256, Algorithm::ES384), - Err(OidcError::InvalidJwk) + Err(OidcError::AlgorithmNotAllowed) )); } + fn keycloak_realm_verifier() -> TokenVerifier { + let keys = parse_static_jwks(&keycloak_realm_jwks()).expect("a realm key set loads"); + TokenVerifier::new( + TokenVerifierConfig::access_token_profile( + "https://keycloak.example/realms/registry", + vec!["registry-api".to_string()], + vec![Algorithm::RS256, Algorithm::ES256], + vec!["at+jwt".to_string()], + ), + Arc::new(JwksFetcher::new_static(keys, jwks_test_config())), + ) + } + + #[tokio::test] + async fn a_header_the_named_key_cannot_serve_is_a_token_fault() { + let verifier = keycloak_realm_verifier(); + let claims = json!({ + "iss": "https://keycloak.example/realms/registry", + "aud": "registry-api", + "sub": "subject-1", + "exp": 4_102_444_800_i64, + }); + for (reason, alg, kid) in [ + ( + "an ES256 header naming the RSA signing key", + "ES256", + KEYCLOAK_SIG_KID, + ), + ( + "an RS256 header naming the RSA-OAEP encryption key", + "RS256", + KEYCLOAK_ENC_KID, + ), + ] { + let header = json!({"alg": alg, "typ": "at+jwt", "kid": kid}); + let token = unsigned_token(header, claims.clone()); + let error = verifier.verify(&token).await.expect_err(reason); + assert_eq!( + error.failed_check(), + FailedCheck::TokenAlgorithm, + "{reason}: {error:?}" + ); + assert!(!error.is_key_source_unavailable(), "{reason}"); + } + + let header = json!({"alg": "RS256", "typ": "at+jwt", "kid": KEYCLOAK_SIG_KID}); + let error = verifier + .verify(&unsigned_token(header, claims)) + .await + .expect_err("an unsigned token is refused"); + assert!( + matches!(error, OidcError::SignatureInvalid), + "the signing key reaches the signature check: {error:?}" + ); + } + + fn signed_hs256_value(kid: &str, claims: &Value, secret: &[u8]) -> String { + let mut header = Header::new(Algorithm::HS256); + header.kid = Some(kid.to_string()); + header.typ = Some("at+jwt".to_string()); + encode(&header, claims, &EncodingKey::from_secret(secret)).expect("sign HS256 test token") + } + + #[tokio::test] + async fn a_missing_or_malformed_claim_names_the_check_it_failed() { + let secret = b"registry-platform-oidc-claim-check-secret"; + let verifier = hs256_test_verifier( + "https://issuer.example", + vec!["registry-api".to_string()], + Vec::new(), + "kid", + secret, + ) + .await; + let base = json!({ + "iss": "https://issuer.example", + "aud": "registry-api", + "sub": "subject-1", + "exp": 4_102_444_800_i64, + }); + let without = |name: &str| { + let mut claims = base.clone(); + claims + .as_object_mut() + .expect("claims are an object") + .remove(name); + claims + }; + let with = |name: &str, value: Value| { + let mut claims = base.clone(); + claims[name] = value; + claims + }; + verifier + .verify(&signed_hs256_value("kid", &base, secret)) + .await + .expect("the base token verifies"); + + for (reason, claims, expected) in [ + ("no aud", without("aud"), FailedCheck::TokenAudience), + ("no iss", without("iss"), FailedCheck::TokenIssuer), + ("no exp", without("exp"), FailedCheck::TokenTime), + ( + "a string exp", + with("exp", json!("soon")), + FailedCheck::TokenTime, + ), + ( + "a fractional exp", + with("exp", json!(4_102_444_800.5_f64)), + FailedCheck::TokenTime, + ), + ( + "a negative exp", + with("exp", json!(-1)), + FailedCheck::TokenTime, + ), + ( + "a string nbf", + with("nbf", json!("now")), + FailedCheck::TokenTime, + ), + ( + "a negative nbf", + with("nbf", json!(-1)), + FailedCheck::TokenTime, + ), + ( + "a string iat", + with("iat", json!("now")), + FailedCheck::TokenTime, + ), + ( + "a numeric sub", + with("sub", json!(7)), + FailedCheck::CredentialMalformed, + ), + ] { + let token = signed_hs256_value("kid", &claims, secret); + let error = verifier.verify(&token).await.expect_err(reason); + assert_eq!(error.failed_check(), expected, "{reason}: {error:?}"); + } + } + fn verifier_for_header_tests() -> TokenVerifier { let fetcher = Arc::new(JwksFetcher::new( "http://127.0.0.1/jwks".to_string(), @@ -3271,7 +3513,13 @@ mod tests { .extra .insert("scope".to_string(), json!("record:read")); // Preserve the selected claim's explicit null; the generic test - // signer omits nulls to represent absent registered claims. + // signer omits nulls to represent absent registered claims. A + // null `nbf` is itself a malformed time claim, so it is omitted + // here and the refusal comes from the selected claim. + let mut claims = serde_json::to_value(claims).expect("claims serialize"); + if let Value::Object(map) = &mut claims { + map.retain(|name, value| name == "permissions" || !value.is_null()); + } let mut header = Header::new(Algorithm::HS256); header.kid = Some("kid".to_string()); header.typ = Some("at+jwt".to_string()); @@ -3325,7 +3573,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let verifier = TokenVerifier::new( TokenVerifierConfig::access_token_profile( @@ -3364,7 +3612,7 @@ mod tests { .verify(&missing_iat) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut missing_exp_claims = test_claims( Some("https://issuer.example"), @@ -3378,7 +3626,7 @@ mod tests { .verify(&missing_exp) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut non_positive_claims = test_claims( Some("https://issuer.example"), @@ -3392,7 +3640,7 @@ mod tests { .verify(&non_positive) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); let mut overlong_claims = test_claims( Some("https://issuer.example"), @@ -3406,7 +3654,7 @@ mod tests { .verify(&overlong) .await .expect_err("invalid time bounds are refused"); - assert_eq!(error.authentication_stage().label(), "time"); + assert_eq!(error.failed_check(), FailedCheck::TokenTime); } fn test_claims(issuer: Option<&str>, audience: Option<&str>, subject: Option<&str>) -> Claims { @@ -3625,17 +3873,31 @@ mod tests { secret, Some("JWT"), ); - assert!(matches!( - verifier - .verify_userinfo_jwt_with_claims_policy( - &wrong_subject, - &access, - &accepted_issuers, - &accepted_audiences, - ) - .await, - Err(OidcError::InvalidToken) - )); + let error = verifier + .verify_userinfo_jwt_with_claims_policy( + &wrong_subject, + &access, + &accepted_issuers, + &accepted_audiences, + ) + .await + .expect_err("a UserInfo response about another subject is refused"); + assert!(matches!(error, OidcError::SubjectMismatch), "{error:?}"); + assert_eq!(error.failed_check(), FailedCheck::TokenClaims, "{error:?}"); + + let mut access_without_subject = access.clone(); + access_without_subject.claims.sub = None; + let error = verifier + .verify_userinfo_jwt_with_claims_policy( + &valid, + &access_without_subject, + &accepted_issuers, + &accepted_audiences, + ) + .await + .expect_err("an access token without a subject matches no UserInfo response"); + assert!(matches!(error, OidcError::SubjectMismatch), "{error:?}"); + assert_eq!(error.failed_check(), FailedCheck::TokenClaims, "{error:?}"); } #[tokio::test] @@ -3954,7 +4216,7 @@ mod tests { OidcError::FetchUrl(FetchUrlError::SchemeDenied { .. }) )); - let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect("dev policy accepts loopback override"); assert_eq!(document.issuer, cfg.issuer); @@ -3978,7 +4240,7 @@ mod tests { OidcError::FetchUrl(FetchUrlError::SchemeDenied { .. }) )); - let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect_err("dev policy rejects returned private jwks_uri"); assert!(matches!( @@ -3998,17 +4260,22 @@ mod tests { max_doc_bytes: DEFAULT_DOC_BYTES, }; - let document = fetch_discovery_at_with_policy(&cfg, &transport, &FetchUrlPolicy::dev()) - .await - .expect("distinct discovery transport accepts exact issuer metadata"); + let document = + fetch_discovery_at_with_policy(&cfg, &transport, &FetchUrlPolicy::https_or_loopback()) + .await + .expect("distinct discovery transport accepts exact issuer metadata"); assert_eq!(document.issuer, canonical_issuer); assert_eq!(document.jwks_uri, jwks_uri); let (mismatched_transport, _) = serve_discovery_document("https://other-issuer.example").await; assert!(matches!( - fetch_discovery_at_with_policy(&cfg, &mismatched_transport, &FetchUrlPolicy::dev()) - .await, + fetch_discovery_at_with_policy( + &cfg, + &mismatched_transport, + &FetchUrlPolicy::https_or_loopback() + ) + .await, Err(OidcError::IssuerMismatch { .. }) )); } @@ -4025,7 +4292,7 @@ mod tests { fetch_discovery_at_with_policy( &cfg, "http://127.0.0.1/metadata", - &FetchUrlPolicy::dev() + &FetchUrlPolicy::https_or_loopback() ) .await, Err(OidcError::ConflictingEndpointConfiguration) @@ -4041,7 +4308,7 @@ mod tests { fetch_discovery_at_with_policy( &empty_issuer, "http://127.0.0.1/metadata", - &FetchUrlPolicy::dev() + &FetchUrlPolicy::https_or_loopback() ) .await, Err(OidcError::MissingIssuer) @@ -4054,7 +4321,8 @@ mod tests { max_doc_bytes: DEFAULT_DOC_BYTES, }; assert!(matches!( - fetch_discovery_at_with_policy(&cfg, "not a URL", &FetchUrlPolicy::dev()).await, + fetch_discovery_at_with_policy(&cfg, "not a URL", &FetchUrlPolicy::https_or_loopback()) + .await, Err(OidcError::InvalidUrl) )); } @@ -4110,7 +4378,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); // A readiness probe repeated every few seconds must not become an @@ -4131,7 +4399,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( "http://127.0.0.1:1/jwks".to_owned(), jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let error = fetcher @@ -4151,7 +4419,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let error = fetcher @@ -4190,8 +4458,11 @@ mod tests { let mut config = jwks_test_config(); config.cache_ttl = Duration::from_millis(50); config.outage_tolerance = Duration::from_secs(3600); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("held-kid") @@ -4242,8 +4513,11 @@ mod tests { let mut config = jwks_test_config(); config.cache_ttl = Duration::from_millis(20); config.outage_tolerance = Duration::from_millis(30); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("expiring-kid") @@ -4272,7 +4546,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4297,7 +4571,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4329,7 +4603,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4361,7 +4635,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let overlong_kid = "x".repeat(DEFAULT_MAX_KID_BYTES + 1); @@ -4409,7 +4683,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut tasks = Vec::new(); @@ -4439,7 +4713,7 @@ mod tests { let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( jwks_uri, config, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); fetcher @@ -4474,7 +4748,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( jwks_uri, jwks_test_config(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); fetcher @@ -4499,8 +4773,11 @@ mod tests { let mut config = jwks_test_config(); config.refresh_cooldown = Duration::from_millis(50); config.negative_cache_ttl = Duration::from_secs(3600); - let fetcher = - JwksFetcher::new_with_fetch_url_policy(jwks_uri, config, FetchUrlPolicy::dev()); + let fetcher = JwksFetcher::new_with_fetch_url_policy( + jwks_uri, + config, + FetchUrlPolicy::https_or_loopback(), + ); fetcher .key_for_kid("old-kid") @@ -4536,7 +4813,7 @@ mod tests { let fetcher = JwksFetcher::new_with_fetch_url_policy( "http://10.0.0.1/jwks".to_string(), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), ); let err = fetcher @@ -4560,7 +4837,7 @@ mod tests { discovery_timeout: Duration::from_secs(1), max_doc_bytes: DEFAULT_DOC_BYTES, }; - let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let err = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect_err("empty issuer with override must be rejected"); assert!( @@ -4580,13 +4857,22 @@ mod tests { discovery_timeout: Duration::from_secs(1), max_doc_bytes: DEFAULT_DOC_BYTES, }; - let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::dev()) + let document = fetch_discovery_with_policy(&cfg, &FetchUrlPolicy::https_or_loopback()) .await .expect("non-empty issuer with override succeeds under dev policy"); assert_eq!(document.issuer, "https://issuer.example"); assert_eq!(document.jwks_uri, "http://127.0.0.1/jwks"); } + #[test] + fn a_static_key_set_with_unknown_public_members_loads() { + let keys = parse_static_jwks( + br#"{"issuer":"x","keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA"],"x5t":"a","x5t#S256":"b","x5u":"https://x.example/c","use":"enc","future":1}]}"#, + ) + .expect("unknown public members are ignored"); + assert_eq!(keys.keys.len(), 1); + } + #[test] fn a_static_key_set_requires_unique_named_asymmetric_keys() { let keys = parse_static_jwks( @@ -4596,38 +4882,113 @@ mod tests { assert_eq!(keys.keys.len(), 2); for (reason, invalid, expected) in [ - ("no keys member", br#"{}"#.as_slice(), "parse"), - ("not JSON", b"not-json", "parse"), - ("an empty key set", br#"{"keys":[]}"#, "empty"), + ("no keys member", br#"{}"#.as_slice(), "static"), + ("not JSON", b"not-json", "static"), + ("an empty key set", br#"{"keys":[]}"#, "static"), ( "a symmetric key", br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#, - "jwk", + "static", ), ( "a key without kid", br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#, - "jwk", + "static", ), ( "an empty kid", br#"{"keys":[{"kty":"RSA","kid":"","n":"AQAB","e":"AQAB"}]}"#, - "jwk", + "static", ), ( "a repeated kid", br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, - "jwk", + "static", + ), + ( + "a private member", + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","d":"AA"}]}"#, + "static", + ), + ( + "an OKP key", + br#"{"keys":[{"kty":"OKP","kid":"one","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]}"#, + "static", ), ] { let error = parse_static_jwks(invalid).expect_err(reason); let kind = match error { - OidcError::Parse => "parse", - OidcError::EmptyKeySet => "empty", + OidcError::StaticKeySet(_) => "static", OidcError::InvalidJwk => "jwk", other => panic!("{reason}: unexpected {other:?}"), }; assert_eq!(kind, expected, "{reason}"); } } + + #[test] + fn an_okp_key_is_refused_with_its_position_and_the_remedy() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"OKP","kid":"two","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]}"#, + ) + .expect_err("an OKP key is refused"); + assert!( + matches!( + error, + OidcError::StaticKeySet(StaticJwksError::OctetKeyPair { key: 1, .. }) + ), + "{error:?}" + ); + let text = error.to_string(); + assert!( + text.contains(r#"key 1 (kid "two", crv "Ed25519") is an OKP key"#), + "{text}" + ); + assert!(text.contains("use an RSA or EC key"), "{text}"); + assert!(error.is_key_source_unavailable()); + } + + #[test] + fn an_okp_key_without_a_crv_is_named_by_kid_alone() { + let text = parse_static_jwks(br#"{"keys":[{"kty":"OKP","kid":"only","x":"AA"}]}"#) + .expect_err("an OKP key is refused") + .to_string(); + assert!( + text.contains(r#"key 0 (kid "only") is an OKP key"#), + "{text}" + ); + assert!(!text.contains("crv"), "{text}"); + } + + #[test] + fn an_okp_key_names_are_bounded_and_quoted() { + let long = "k".repeat(500); + let document = + format!(r#"{{"keys":[{{"kty":"OKP","kid":"{long}","crv":"a\nb","x":"AA"}}]}}"#); + let text = parse_static_jwks(document.as_bytes()) + .expect_err("an OKP key is refused") + .to_string(); + assert!(!text.contains(&long), "{text}"); + assert!(text.contains(r#"crv "a\nb""#), "{text}"); + assert!(text.len() < 400, "{}", text.len()); + } + + #[test] + fn a_key_of_the_wrong_shape_is_named_by_position() { + let error = parse_static_jwks( + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"two","n":5,"e":"AQAB"}]}"#, + ) + .expect_err("a key with a numeric modulus is refused"); + assert!( + matches!( + error, + OidcError::StaticKeySet(StaticJwksError::KeyShape { key: 1 }) + ), + "{error:?}" + ); + let text = error.to_string(); + assert!(text.contains("key 1 "), "{text}"); + assert!(!text.contains("two"), "{text}"); + assert!(error.is_key_source_unavailable()); + } } diff --git a/crates/registry-platform-oidc/src/static_jwks.rs b/crates/registry-platform-oidc/src/static_jwks.rs new file mode 100644 index 0000000000..3eb3e87b5c --- /dev/null +++ b/crates/registry-platform-oidc/src/static_jwks.rs @@ -0,0 +1,329 @@ +//! Public-key rule for operator-pinned JSON Web Key Sets. +//! +//! One rule for every product that loads a static key set. Members this +//! module does not name are ignored, as RFC 7517 sections 4 and 5 require, +//! apart from the strict JSON rule that applies to the whole document: no +//! repeated member name, and no integer a binary64 number cannot hold +//! exactly. A refusal names the position of the key and the rule it broke, +//! never a member value. The one refusal that also names a key's `kid` and +//! `crv` is [`StaticJwksError::OctetKeyPair`], for a key the verifier would +//! otherwise load: both are public labels, quoted and bounded. + +use std::collections::BTreeSet; + +use registry_platform_crypto::{parse_json_strict, PRIVATE_JWK_MEMBERS}; +use serde_json::Value; + +/// Why a static key set was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum StaticJwksError { + #[error("the document is not JSON, repeats a member name, or holds an integer that a 64-bit floating-point number cannot represent exactly")] + NotJson, + #[error("the document is not a JSON Web Key Set: it needs a top-level \"keys\" array")] + NotAKeySet, + #[error("the key set holds no keys")] + Empty, + #[error("key {key} is not a JSON object")] + KeyNotAnObject { key: usize }, + #[error( + "key {key} is a symmetric key (\"kty\": \"oct\"); a static key set holds public keys only" + )] + SymmetricKey { key: usize }, + #[error("key {key} has no \"kty\", or a key type that is not RSA, EC or OKP")] + UnsupportedKeyType { key: usize }, + #[error("key {key} carries the private-key member \"{member}\"; a static key set holds public keys only, so export the public key and replace this document")] + PrivateKeyMember { key: usize, member: &'static str }, + #[error("key {key} has no \"kid\"; give every key a non-empty \"kid\"")] + MissingKeyId { key: usize }, + #[error("key {key} repeats the \"kid\" of an earlier key; give every key its own \"kid\"")] + RepeatedKeyId { key: usize }, + #[error("key {key}{} is an OKP key (\"kty\": \"OKP\"), which the token verifier does not load; use an RSA or EC key", okp_labels(.kid, .crv))] + OctetKeyPair { + key: usize, + kid: Option, + crv: Option, + }, + #[error( + "key {key} is not a valid JSON Web Key: a member it needs is missing or has the wrong type" + )] + KeyShape { key: usize }, +} + +/// The longest `kid` or `crv` an OKP refusal repeats. +const MAX_LABEL_CHARS: usize = 64; + +/// ` (kid "...", crv "...")` for the labels a key has, quoted and cut to +/// [`MAX_LABEL_CHARS`], or nothing when it has neither. +fn okp_labels(kid: &Option, crv: &Option) -> String { + let labels: Vec = [("kid", kid), ("crv", crv)] + .into_iter() + .filter_map(|(name, value)| { + let value = value.as_deref()?; + let bounded: String = value.chars().take(MAX_LABEL_CHARS).collect(); + Some(format!("{name} {bounded:?}")) + }) + .collect(); + if labels.is_empty() { + String::new() + } else { + format!(" ({})", labels.join(", ")) + } +} + +/// Check that `bytes` is a JSON Web Key Set that holds public keys only. +/// Returns the parsed document. Apart from the strict JSON rule (no repeated +/// member name, no integer a binary64 number cannot hold exactly, anywhere in +/// the document), members this function does not name are not inspected. An +/// OKP key passes here; [`crate::parse_static_jwks`] refuses it for the token +/// verifier. The caller bounds the size of `bytes`. +pub fn public_jwks_document(bytes: &[u8]) -> Result { + let document = parse_json_strict(bytes).map_err(|_| StaticJwksError::NotJson)?; + let keys = document + .get("keys") + .and_then(Value::as_array) + .ok_or(StaticJwksError::NotAKeySet)?; + if keys.is_empty() { + return Err(StaticJwksError::Empty); + } + let mut key_ids = BTreeSet::new(); + for (key, member) in keys.iter().enumerate() { + let member = member + .as_object() + .ok_or(StaticJwksError::KeyNotAnObject { key })?; + match member.get("kty").and_then(Value::as_str) { + Some("oct") => return Err(StaticJwksError::SymmetricKey { key }), + Some("RSA" | "EC" | "OKP") => {} + _ => return Err(StaticJwksError::UnsupportedKeyType { key }), + } + if let Some(private) = PRIVATE_JWK_MEMBERS + .iter() + .find(|name| member.contains_key(**name)) + { + return Err(StaticJwksError::PrivateKeyMember { + key, + member: private, + }); + } + let kid = member + .get("kid") + .and_then(Value::as_str) + .filter(|kid| !kid.is_empty()) + .ok_or(StaticJwksError::MissingKeyId { key })?; + if !key_ids.insert(kid) { + return Err(StaticJwksError::RepeatedKeyId { key }); + } + } + Ok(document) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; + use base64::Engine; + use jsonwebtoken::jwk::{KeyAlgorithm, PublicKeyUse}; + use registry_platform_crypto::PRIVATE_JWK_MEMBERS; + use serde_json::json; + + const RSA: &str = r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}"#; + + /// The `kid` of the RS256 signing key in [`keycloak_realm_jwks`]. + pub(crate) const KEYCLOAK_SIG_KID: &str = "kXbJ0QJ3Yx3qhJpU0rT9d8nqk1Z6m2Vw4sFhL7cE5aA"; + /// The `kid` of the RSA-OAEP encryption key in [`keycloak_realm_jwks`]. + pub(crate) const KEYCLOAK_ENC_KID: &str = "Rz8tYp4WmQ1nV6bH2cL9xK3fJ7sD0gA5eU8iO2wN4qM"; + + /// A key set in the shape a Keycloak realm publishes at + /// `/realms//protocol/openid-connect/certs`: an RSA-OAEP `enc` key + /// listed before the RS256 `sig` key, each with a 2048-bit modulus, a + /// one-certificate `x5c` chain of a self-signed realm certificate's length, + /// `x5t` and `x5t#S256`. Every value is synthetic: the moduli are not real + /// keys and the certificates are filler bytes behind a DER sequence header. + pub(crate) fn keycloak_realm_jwks() -> Vec { + fn filler(seed: u8, len: usize) -> Vec { + (0..len) + .map(|index| (index as u8).wrapping_mul(167).wrapping_add(seed)) + .collect() + } + fn modulus(seed: u8) -> String { + let mut bytes = filler(seed, 256); + bytes[0] |= 0x80; + bytes[255] |= 0x01; + URL_SAFE_NO_PAD.encode(bytes) + } + fn certificate(seed: u8) -> String { + let mut der = vec![0x30, 0x82, 0x02, 0xa9]; + der.extend(filler(seed, 0x02a9)); + STANDARD.encode(der) + } + fn key(kid: &str, alg: &str, key_use: &str, seed: u8) -> Value { + json!({ + "kid": kid, + "kty": "RSA", + "alg": alg, + "use": key_use, + "n": modulus(seed), + "e": "AQAB", + "x5c": [certificate(seed)], + "x5t": URL_SAFE_NO_PAD.encode(filler(seed, 20)), + "x5t#S256": URL_SAFE_NO_PAD.encode(filler(seed, 32)), + }) + } + json!({"keys": [ + key(KEYCLOAK_ENC_KID, "RSA-OAEP", "enc", 0x5a), + key(KEYCLOAK_SIG_KID, "RS256", "sig", 0xa5), + ]}) + .to_string() + .into_bytes() + } + + fn set(keys: &str) -> Vec { + format!(r#"{{"keys":[{keys}]}}"#).into_bytes() + } + + fn refusal(bytes: &[u8]) -> StaticJwksError { + public_jwks_document(bytes).expect_err("document must be refused") + } + + #[test] + fn unknown_members_on_keys_and_on_the_set_are_ignored() { + let key = r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA"],"x5t":"a","x5t#S256":"b","x5u":"https://x.example/c","use":"sig","key_ops":["verify"],"future":{"a":1}}"#; + let bytes = format!(r#"{{"issuer":"x","keys":[{key}]}}"#); + let document = public_jwks_document(bytes.as_bytes()).expect("loads"); + assert_eq!(document["keys"].as_array().expect("keys").len(), 1); + } + + #[test] + fn a_keycloak_realm_set_loads_through_the_verifier_parser() { + let bytes = keycloak_realm_jwks(); + let keys = crate::parse_static_jwks(&bytes).expect("a realm key set loads"); + assert_eq!(keys.keys.len(), 2); + let sig = keys.find(KEYCLOAK_SIG_KID).expect("the signing key loads"); + assert_eq!(sig.common.public_key_use, Some(PublicKeyUse::Signature)); + assert_eq!(sig.common.key_algorithm, Some(KeyAlgorithm::RS256)); + let chain = sig.common.x509_chain.as_deref().expect("x5c is kept"); + assert!(chain[0].len() > 900, "the certificate has a realm length"); + let enc = keys + .find(KEYCLOAK_ENC_KID) + .expect("the encryption key loads"); + assert_eq!(enc.common.public_key_use, Some(PublicKeyUse::Encryption)); + assert_eq!(enc.common.key_algorithm, Some(KeyAlgorithm::RSA_OAEP)); + } + + #[test] + fn an_inexact_integer_anywhere_is_refused_and_the_text_says_so() { + let bytes = format!(r#"{{"keys":[{RSA}],"serial":9007199254740993}}"#); + let error = refusal(bytes.as_bytes()); + assert_eq!(error, StaticJwksError::NotJson); + assert!(error.to_string().contains("integer"), "{error}"); + public_jwks_document(format!(r#"{{"keys":[{RSA}],"serial":9007199254740992}}"#).as_bytes()) + .expect("an integer binary64 holds exactly is kept"); + } + + #[test] + fn every_private_member_is_refused_on_every_key_type() { + let shapes = [ + r#""kty":"RSA","n":"AQAB","e":"AQAB""#, + r#""kty":"EC","crv":"P-256","x":"AQAB","y":"AQAB""#, + r#""kty":"OKP","crv":"Ed25519","x":"AQAB""#, + ]; + for shape in shapes { + for member in PRIVATE_JWK_MEMBERS { + let bytes = set(&format!(r#"{{{shape},"kid":"one","{member}":"canary"}}"#)); + let error = refusal(&bytes); + assert_eq!( + error, + StaticJwksError::PrivateKeyMember { key: 0, member }, + "{shape} {member}" + ); + } + } + } + + #[test] + fn the_first_private_member_in_list_order_is_reported() { + let bytes = set(r#"{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","dq":"x","d":"y"}"#); + assert_eq!( + refusal(&bytes), + StaticJwksError::PrivateKeyMember { + key: 0, + member: "d" + } + ); + } + + #[test] + fn symmetric_and_unsupported_key_types_are_refused() { + assert_eq!( + refusal(&set(r#"{"kty":"oct","kid":"one","k":"AA"}"#)), + StaticJwksError::SymmetricKey { key: 0 } + ); + for key in [ + r#"{"kty":"DSA","kid":"one"}"#, + r#"{"kid":"one"}"#, + r#"{"kty":5,"kid":"one"}"#, + ] { + assert_eq!( + refusal(&set(key)), + StaticJwksError::UnsupportedKeyType { key: 0 }, + "{key}" + ); + } + } + + #[test] + fn structural_refusals() { + assert_eq!(refusal(b"not-json"), StaticJwksError::NotJson); + assert_eq!( + refusal(br#"{"keys":[],"keys":[]}"#), + StaticJwksError::NotJson + ); + assert_eq!( + refusal(br#"{"keys":[{"kty":"RSA","kty":"RSA","kid":"one"}]}"#), + StaticJwksError::NotJson + ); + assert_eq!(refusal(b"{}"), StaticJwksError::NotAKeySet); + assert_eq!(refusal(b"[]"), StaticJwksError::NotAKeySet); + assert_eq!(refusal(br#"{"keys":{}}"#), StaticJwksError::NotAKeySet); + assert_eq!(refusal(br#"{"keys":[]}"#), StaticJwksError::Empty); + assert_eq!( + refusal(&set(&format!("{RSA},3"))), + StaticJwksError::KeyNotAnObject { key: 1 } + ); + } + + #[test] + fn key_id_rules() { + assert_eq!( + refusal(&set(r#"{"kty":"RSA","n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(r#"{"kty":"RSA","kid":"","n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(r#"{"kty":"RSA","kid":7,"n":"AQAB","e":"AQAB"}"#)), + StaticJwksError::MissingKeyId { key: 0 } + ); + assert_eq!( + refusal(&set(&format!("{RSA},{RSA}"))), + StaticJwksError::RepeatedKeyId { key: 1 } + ); + } + + #[test] + fn refusal_text_carries_no_key_material_or_kid() { + let canary = "canary-secret-value"; + let documents = [ + json!({"keys":[{"kty":"RSA","kid":canary,"n":"AQAB","e":"AQAB","d":canary}]}), + json!({"keys":[{"kty":"oct","kid":canary,"k":canary}]}), + json!({"keys":[{"kty":canary,"kid":canary}]}), + json!({"keys":[{"kty":"RSA","kid":canary},{"kty":"RSA","kid":canary}]}), + ]; + for document in documents { + let text = refusal(document.to_string().as_bytes()).to_string(); + assert!(!text.contains(canary), "{text}"); + } + } +} diff --git a/crates/registry-platform-oidc/src/task_grant.rs b/crates/registry-platform-oidc/src/task_grant.rs index 0a79fc7746..1a6a851fe6 100644 --- a/crates/registry-platform-oidc/src/task_grant.rs +++ b/crates/registry-platform-oidc/src/task_grant.rs @@ -3,7 +3,7 @@ use crate::{GrantBounds, GrantClaims}; use registry_platform_httputil::{ client::{build_client, OutboundOptions, PrivateKeyJwt, ServiceBaseUrl, TokenProvider}, - read_bounded, validate_response_headers, + read_bounded, validate_response_headers, PeerPolicy, ResponseHeaderError, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -13,6 +13,10 @@ use uuid::Uuid; mod config; pub use config::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}; +/// Machine-readable code for a status answer refused because its peer declares +/// the development posture. +pub const DEVELOPMENT_PEER_CODE: &str = "platform.task-grant.development-peer"; + #[derive(Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TaskGrantStatusBinding { @@ -102,6 +106,19 @@ pub enum TaskGrantError { Unavailable, #[error("task authority status configuration is invalid")] Configuration, + #[error("task authority status peer declares the development posture")] + DevelopmentPeer, +} + +impl TaskGrantError { + /// The machine-readable code of a refusal that has one. + #[must_use] + pub const fn code(self) -> Option<&'static str> { + match self { + Self::DevelopmentPeer => Some(DEVELOPMENT_PEER_CODE), + Self::Refused | Self::Unavailable | Self::Configuration => None, + } + } } /// A status route appended to the service base's path, parsed from a template @@ -154,6 +171,7 @@ pub struct TaskGrantStatusClient { status_path: StatusPath, http: reqwest::Client, token: Arc, + peer_policy: PeerPolicy, } impl fmt::Debug for TaskGrantStatusClient { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -162,7 +180,9 @@ impl fmt::Debug for TaskGrantStatusClient { } impl TaskGrantStatusClient { /// `status_path` is the status route appended to `base`'s path: it starts - /// with `/` and has exactly one whole `{grantId}` segment. + /// with `/` and has exactly one whole `{grantId}` segment. `peer_policy` + /// decides whether a status answer from a development-posture peer is + /// accepted. pub fn new( source_issuer: String, resource: String, @@ -170,6 +190,7 @@ impl TaskGrantStatusClient { status_path: &str, token: Arc, trusted_roots: Option<&[u8]>, + peer_policy: PeerPolicy, ) -> Result { if !registry_platform_httputil::valid_resource_uri(&source_issuer) || !registry_platform_httputil::valid_resource_uri(&resource) @@ -192,8 +213,30 @@ impl TaskGrantStatusClient { status_path, http, token, + peer_policy, }) } + + /// [`Self::new`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn new_without_peer_policy( + source_issuer: String, + resource: String, + base: reqwest::Url, + status_path: &str, + token: Arc, + trusted_roots: Option<&[u8]>, + ) -> Result { + Self::new( + source_issuer, + resource, + base, + status_path, + token, + trusted_roots, + PeerPolicy::RefuseDevelopmentPeer, + ) + } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -236,8 +279,12 @@ impl TaskGrantStatusClient { .send() .await .map_err(|_| TaskGrantError::Unavailable)?; - validate_response_headers(response.headers()) - .map_err(|_| TaskGrantError::Unavailable)?; + validate_response_headers(response.headers(), self.peer_policy).map_err(|error| { + match error { + ResponseHeaderError::DevelopmentPeer => TaskGrantError::DevelopmentPeer, + _ => TaskGrantError::Unavailable, + } + })?; // A concealed or absent grant is a refusal. Rejected status-service // credentials do not establish inactive authority and remain unavailable. if response.status() == reqwest::StatusCode::NOT_FOUND { diff --git a/crates/registry-platform-oidc/src/task_grant/config.rs b/crates/registry-platform-oidc/src/task_grant/config.rs index 0f7eb0d9b8..bb0501ca76 100644 --- a/crates/registry-platform-oidc/src/task_grant/config.rs +++ b/crates/registry-platform-oidc/src/task_grant/config.rs @@ -3,6 +3,7 @@ use super::*; use registry_platform_config::{SecretReference, SecretResolver, TaskGrantStatusConfig}; use registry_platform_httputil::client::{validate_requested_scopes, PrivateKeyJwtConfig}; +use registry_platform_httputil::PeerPolicy; use registry_platform_yaml::{ExternalId, Url}; /// One operator-pinned status authority, as a runtime's `taskGrantStatus` @@ -109,10 +110,28 @@ impl TaskGrantStatusRegistry { Ok(()) } + /// [`Self::activate`] under [`PeerPolicy::RefuseDevelopmentPeer`], for a caller + /// that has no runtime peer policy yet. + pub fn activate_without_peer_policy( + configs: &[TaskGrantStatusEndpoint], + resource: &str, + secrets: &SecretResolver, + ) -> Result { + Self::activate( + configs, + resource, + secrets, + PeerPolicy::RefuseDevelopmentPeer, + ) + } + + /// `peer_policy` decides whether a status answer from a development-posture + /// peer is accepted. pub fn activate( configs: &[TaskGrantStatusEndpoint], resource: &str, secrets: &SecretResolver, + peer_policy: PeerPolicy, ) -> Result { Self::validate_configuration(configs, resource)?; let mut clients = BTreeMap::new(); @@ -155,6 +174,7 @@ impl TaskGrantStatusRegistry { &config.status_path, Arc::new(PrivateKeyJwt::new(token).map_err(|_| TaskGrantError::Configuration)?), ca.as_ref().map(|value| value.expose_secret()), + peer_policy, )?; if clients .insert(config.source_issuer.as_str().to_owned(), client) @@ -272,7 +292,7 @@ mod tests { let root = tempfile::tempdir().unwrap(); let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); assert!( - TaskGrantStatusRegistry::activate( + TaskGrantStatusRegistry::activate_without_peer_policy( std::slice::from_ref(&config), "urn:resource:test", &secrets @@ -282,7 +302,7 @@ mod tests { ); for resource in ["", "not-an-absolute-resource"] { TaskGrantStatusRegistry::validate_configuration(&[], resource).unwrap(); - TaskGrantStatusRegistry::activate(&[], resource, &secrets).unwrap(); + TaskGrantStatusRegistry::activate_without_peer_policy(&[], resource, &secrets).unwrap(); assert!(TaskGrantStatusRegistry::validate_configuration( std::slice::from_ref(&config), resource @@ -339,7 +359,7 @@ mod tests { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); let secrets = SecretResolver::new([SecretProvider::File], root.path()).unwrap(); let config = endpoint(); - let status = TaskGrantStatusRegistry::activate( + let status = TaskGrantStatusRegistry::activate_without_peer_policy( std::slice::from_ref(&config), "urn:resource:test", &secrets, @@ -349,13 +369,16 @@ mod tests { assert!(!status.contains("https://other.test")); let mut urn_authority = config.clone(); urn_authority.source_issuer = ExternalId::new("urn:authority:source").unwrap(); - let urn_status = - TaskGrantStatusRegistry::activate(&[urn_authority], "urn:resource:test", &secrets) - .unwrap(); + let urn_status = TaskGrantStatusRegistry::activate_without_peer_policy( + &[urn_authority], + "urn:resource:test", + &secrets, + ) + .unwrap(); assert!(urn_status.contains("urn:authority:source")); let mut duplicate = config.clone(); duplicate.base_url = Url::new("https://other-authority.test").unwrap(); - assert!(TaskGrantStatusRegistry::activate( + assert!(TaskGrantStatusRegistry::activate_without_peer_policy( &[config.clone(), duplicate], "urn:resource:test", &secrets @@ -366,15 +389,22 @@ mod tests { let mut invalid = config.clone(); invalid.base_url = Url::new(url).unwrap(); assert!( - TaskGrantStatusRegistry::activate(&[invalid], "urn:resource:test", &secrets) - .is_err(), + TaskGrantStatusRegistry::activate_without_peer_policy( + &[invalid], + "urn:resource:test", + &secrets + ) + .is_err(), "{url}" ); } let mut invalid = config; invalid.status_resource = ExternalId::new("not-an-absolute-resource").unwrap(); - assert!( - TaskGrantStatusRegistry::activate(&[invalid], "urn:resource:test", &secrets).is_err() - ); + assert!(TaskGrantStatusRegistry::activate_without_peer_policy( + &[invalid], + "urn:resource:test", + &secrets + ) + .is_err()); } } diff --git a/crates/registry-platform-oidc/src/task_grant/tests.rs b/crates/registry-platform-oidc/src/task_grant/tests.rs index 2072248dfd..773c54e73c 100644 --- a/crates/registry-platform-oidc/src/task_grant/tests.rs +++ b/crates/registry-platform-oidc/src/task_grant/tests.rs @@ -25,6 +25,7 @@ struct StateData { client_assertion_audience: String, requested: Arc>>, status_paths: Arc>>, + status_posture: Arc>>, } async fn token( State(state): State, @@ -57,7 +58,7 @@ async fn status( State(state): State, uri: Uri, headers: HeaderMap, -) -> Result, axum::http::StatusCode> { +) -> Result<(HeaderMap, Json), axum::http::StatusCode> { assert_eq!( headers.get("authorization").unwrap(), "Bearer synthetic-status-service" @@ -75,7 +76,11 @@ async fn status( if code != axum::http::StatusCode::OK { return Err(code); } - Ok(Json(state.response.lock().unwrap().clone())) + let mut answer_headers = HeaderMap::new(); + if let Some(posture) = *state.status_posture.lock().unwrap() { + answer_headers.insert("registry-posture", posture.parse().unwrap()); + } + Ok((answer_headers, Json(state.response.lock().unwrap().clone()))) } fn binding() -> TaskGrantStatusBinding { serde_json::from_value(serde_json::json!({"grantId":Uuid::new_v4().to_string(),"sourceIssuer":"https://authority.test","principal":"agent","client":"agent-client","resource":"urn:resource:test","purpose":"review","bounds":{"type":"breg","permissions":[{"collection":"records","operations":["get","patch"]}]},"subjects":{"subject_reference":"synthetic-subject","active":true},"expiresAt":chrono::Utc::now().timestamp()+900})).unwrap() @@ -90,6 +95,7 @@ fn state(response: Value, client_assertion_audience: String) -> StateData { client_assertion_audience, requested: Arc::default(), status_paths: Arc::default(), + status_posture: Arc::default(), } } /// Writes an owner-only private JWK as `status-key` under `root`. @@ -152,8 +158,12 @@ async fn status_client_requests_the_configured_scope_resource_and_status_path() endpoint.status_path = "/authority/grants/{grantId}/state".into(); endpoint.status_scope = ExternalId::new("grants:read-status").unwrap(); endpoint.status_resource = ExternalId::new("urn:authority:status").unwrap(); - let client = - TaskGrantStatusRegistry::activate(&[endpoint], "urn:resource:test", &secrets).unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); assert_eq!( *state.requested.lock().unwrap(), @@ -191,7 +201,12 @@ async fn activated_status_client_uses_the_configured_assertion_audience_and_chec let mut wrong = config.clone(); wrong.client_assertion_audience = registry_platform_yaml::ExternalId::new(format!("http://{address}/token")).unwrap(); - let wrong = TaskGrantStatusRegistry::activate(&[wrong], "urn:resource:test", &secrets).unwrap(); + let wrong = TaskGrantStatusRegistry::activate_without_peer_policy( + &[wrong], + "urn:resource:test", + &secrets, + ) + .unwrap(); assert_eq!( wrong.check(&binding).await, Err(TaskGrantError::Unavailable) @@ -199,8 +214,12 @@ async fn activated_status_client_uses_the_configured_assertion_audience_and_chec assert_eq!(state.rejected_token_calls.load(Ordering::SeqCst), 1); assert_eq!(state.status_calls.load(Ordering::SeqCst), 0); - let client = - TaskGrantStatusRegistry::activate(&[config], "urn:resource:test", &secrets).unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[config], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); *response.lock().unwrap() = serde_json::json!({"active":false}); assert_eq!(client.check(&binding).await, Err(TaskGrantError::Refused)); @@ -302,9 +321,12 @@ async fn fixed_bounds_without_disclosed_claims_still_require_exact_fresh_status( let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let root = tempfile::tempdir().unwrap(); let secrets = status_key_secrets(root.path()); - let client = - TaskGrantStatusRegistry::activate(&[endpoint(&issuer)], "urn:resource:test", &secrets) - .unwrap(); + let client = TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint(&issuer)], + "urn:resource:test", + &secrets, + ) + .unwrap(); client.check(&binding).await.unwrap(); let mut changed = serde_json::to_value(&binding).unwrap(); changed["subjects"] = serde_json::json!({"unexpected":"claim"}); @@ -368,3 +390,93 @@ fn the_shared_status_block_maps_onto_one_endpoint_member_for_member() { Some("secret:file/status-ca") ); } + +/// Serves an active status answer that declares `posture`, and returns the +/// registry activated under `peer` plus the server handle. +async fn registry_against_peer_declaring( + posture: &'static str, + peer: PeerPolicy, + transitional: bool, +) -> ( + TaskGrantStatusBinding, + TaskGrantStatusRegistry, + tokio::task::JoinHandle<()>, +) { + let binding = binding(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let state = state( + serde_json::json!({"active":true,"grant":binding}), + base.clone(), + ); + *state.status_posture.lock().unwrap() = Some(posture); + let app = Router::new() + .route("/token", post(token)) + .route("/v1/task-grants/{id}/status", get(status)) + .with_state(state); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let root = tempfile::tempdir().unwrap(); + let secrets = status_key_secrets(root.path()); + let registry = if transitional { + TaskGrantStatusRegistry::activate_without_peer_policy( + &[endpoint(&base)], + "urn:resource:test", + &secrets, + ) + } else { + TaskGrantStatusRegistry::activate(&[endpoint(&base)], "urn:resource:test", &secrets, peer) + } + .unwrap(); + (binding, registry, server) +} + +#[tokio::test] +async fn a_production_policy_refuses_a_status_answer_from_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::RefuseDevelopmentPeer, false) + .await; + assert_eq!( + registry.check(&binding).await, + Err(TaskGrantError::DevelopmentPeer) + ); + server.abort(); +} + +#[tokio::test] +async fn a_development_policy_accepts_a_status_answer_from_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::AcceptDevelopmentPeer, false) + .await; + registry.check(&binding).await.unwrap(); + server.abort(); +} + +#[tokio::test] +async fn the_transitional_activation_refuses_a_development_peer() { + let (binding, registry, server) = + registry_against_peer_declaring("development", PeerPolicy::AcceptDevelopmentPeer, true) + .await; + assert_eq!( + registry.check(&binding).await, + Err(TaskGrantError::DevelopmentPeer) + ); + server.abort(); +} + +#[tokio::test] +async fn a_production_policy_accepts_a_status_answer_declaring_production() { + let (binding, registry, server) = + registry_against_peer_declaring("production", PeerPolicy::RefuseDevelopmentPeer, false) + .await; + registry.check(&binding).await.unwrap(); + server.abort(); +} + +#[test] +fn the_development_peer_refusal_has_its_own_code() { + assert_eq!( + TaskGrantError::DevelopmentPeer.code(), + Some("platform.task-grant.development-peer") + ); + assert_eq!(TaskGrantError::Refused.code(), None); +} diff --git a/crates/registry-platform-posture/Cargo.toml b/crates/registry-platform-posture/Cargo.toml new file mode 100644 index 0000000000..0cd55218c5 --- /dev/null +++ b/crates/registry-platform-posture/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "registry-platform-posture" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The declared posture (development or production) and how a process reads it." +repository.workspace = true +readme = "README.md" +publish = false + +[lints] +workspace = true diff --git a/crates/registry-platform-posture/README.md b/crates/registry-platform-posture/README.md new file mode 100644 index 0000000000..6da66f01dc --- /dev/null +++ b/crates/registry-platform-posture/README.md @@ -0,0 +1,8 @@ +# Registry Platform Posture + +`registry-platform-posture` holds the declared posture of a process, `development` or `production`, and the rules for reading it. It depends on nothing outside `std`, so any platform crate can name the type. + +- `Posture`, `PostureSource` and `DeclaredPosture`. The accepted values are exactly `development` and `production`, case-sensitive, with no trimming. Neither the `--posture` flag nor the `REGISTRY_STACK_POSTURE` variable present means `production` with source `default`. +- `declared_from(flag, environment)` is pure and decides from the two inputs. A flag and a variable that are both present and equal give source `flag`. Different values are refused. +- `declared(flag)` reads the variable once. Call it only from `main` or a command dispatcher, and pass the result down as a value. +- `PostureError` has three cases with stable codes (`platform.posture.invalid-value`, `platform.posture.conflict`), value-free messages and a suggested action. The refusals happen before any file is read. diff --git a/crates/registry-platform-posture/src/lib.rs b/crates/registry-platform-posture/src/lib.rs new file mode 100644 index 0000000000..23a6a261e2 --- /dev/null +++ b/crates/registry-platform-posture/src/lib.rs @@ -0,0 +1,350 @@ +//! The declared posture of a process, `development` or `production`, and the +//! rules for reading it from the `--posture` flag and `REGISTRY_STACK_POSTURE`. +//! +//! The crate depends on nothing outside `std`, so any platform crate can name +//! the type. Reading the declaration performs no file access and never echoes +//! the value it was given. + +use std::ffi::OsStr; +use std::fmt; + +/// The environment variable that declares the posture of a process. +pub const POSTURE_ENV: &str = "REGISTRY_STACK_POSTURE"; +/// The long name of the command-line flag that declares the posture. +pub const POSTURE_FLAG: &str = "posture"; +/// The HTTP field name that marks a response with its posture. +pub const POSTURE_HEADER: &str = "registry-posture"; +/// The accepted spelling of [`Posture::Development`]. +pub const DEVELOPMENT: &str = "development"; +/// The accepted spelling of [`Posture::Production`]. +pub const PRODUCTION: &str = "production"; + +/// A posture a process declares for itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Posture { + Development, + Production, +} + +impl Posture { + /// The accepted spelling of this posture. + pub const fn as_str(self) -> &'static str { + match self { + Posture::Development => DEVELOPMENT, + Posture::Production => PRODUCTION, + } + } + + /// Parses an exact, case-sensitive spelling. No trimming. + pub fn parse(value: &str) -> Option { + match value { + DEVELOPMENT => Some(Posture::Development), + PRODUCTION => Some(Posture::Production), + _ => None, + } + } +} + +/// Where a declared posture came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PostureSource { + Flag, + Environment, + Default, +} + +/// A posture together with the source that declared it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DeclaredPosture { + pub posture: Posture, + pub source: PostureSource, +} + +/// A refusal made before any file is read. Messages never contain the value given. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PostureError { + /// The variable is set to an empty, non-UTF-8 or unknown value. + InvalidEnvironment, + /// The flag was given an unknown value. + InvalidFlag, + /// Two declarations disagree. + Conflict, +} + +impl PostureError { + /// The stable diagnostic code. + pub const fn code(self) -> &'static str { + match self { + PostureError::InvalidEnvironment | PostureError::InvalidFlag => { + "platform.posture.invalid-value" + } + PostureError::Conflict => "platform.posture.conflict", + } + } + + /// A value-free description of the refusal. + pub const fn message(self) -> &'static str { + match self { + PostureError::InvalidEnvironment => { + "REGISTRY_STACK_POSTURE is set to a value that is not a posture" + } + PostureError::InvalidFlag => "--posture was given a value that is not a posture", + PostureError::Conflict => { + "--posture and REGISTRY_STACK_POSTURE declare different postures" + } + } + } + + /// What the operator can do about it. + pub const fn suggested_action(self) -> &'static str { + match self { + PostureError::InvalidEnvironment => { + "Set it to development or production, or unset it for production." + } + PostureError::InvalidFlag => "Pass --posture development or --posture production.", + PostureError::Conflict => "Declare the posture once, or give both the same value.", + } + } +} + +impl fmt::Display for PostureError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.message()) + } +} + +impl std::error::Error for PostureError {} + +/// Decides the posture from the two inputs. Pure. +/// +/// A set variable is validated even when the flag is also present. When both +/// are invalid the variable is reported first. Neither input present gives +/// production with source [`PostureSource::Default`]. Both present and equal +/// gives source [`PostureSource::Flag`]. +pub fn declared_from( + flag: Option<&str>, + environment: Option<&OsStr>, +) -> Result { + let from_environment = match environment { + None => None, + Some(value) => Some( + value + .to_str() + .and_then(Posture::parse) + .ok_or(PostureError::InvalidEnvironment)?, + ), + }; + let from_flag = match flag { + None => None, + Some(value) => Some(Posture::parse(value).ok_or(PostureError::InvalidFlag)?), + }; + match (from_flag, from_environment) { + (Some(flag), Some(environment)) if flag != environment => Err(PostureError::Conflict), + (Some(posture), _) => Ok(DeclaredPosture { + posture, + source: PostureSource::Flag, + }), + (None, Some(posture)) => Ok(DeclaredPosture { + posture, + source: PostureSource::Environment, + }), + (None, None) => Ok(DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }), + } +} + +/// Reads [`POSTURE_ENV`] once and calls [`declared_from`]. Call it only from `main` +/// or a command dispatcher, so the process-global variable is read in one place. +pub fn declared(flag: Option<&str>) -> Result { + declared_from(flag, std::env::var_os(POSTURE_ENV).as_deref()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env(value: &str) -> Option<&OsStr> { + Some(OsStr::new(value)) + } + + fn ok(posture: Posture, source: PostureSource) -> Result { + Ok(DeclaredPosture { posture, source }) + } + + #[test] + fn flag_only() { + assert_eq!( + declared_from(Some("development"), None), + ok(Posture::Development, PostureSource::Flag) + ); + assert_eq!( + declared_from(Some("production"), None), + ok(Posture::Production, PostureSource::Flag) + ); + } + + #[test] + fn variable_only() { + assert_eq!( + declared_from(None, env("development")), + ok(Posture::Development, PostureSource::Environment) + ); + assert_eq!( + declared_from(None, env("production")), + ok(Posture::Production, PostureSource::Environment) + ); + } + + #[test] + fn both_equal_report_the_flag() { + assert_eq!( + declared_from(Some("development"), env("development")), + ok(Posture::Development, PostureSource::Flag) + ); + assert_eq!( + declared_from(Some("production"), env("production")), + ok(Posture::Production, PostureSource::Flag) + ); + } + + #[test] + fn both_different_conflict() { + assert_eq!( + declared_from(Some("development"), env("production")), + Err(PostureError::Conflict) + ); + assert_eq!( + declared_from(Some("production"), env("development")), + Err(PostureError::Conflict) + ); + } + + #[test] + fn neither_is_production_by_default() { + assert_eq!( + declared_from(None, None), + ok(Posture::Production, PostureSource::Default) + ); + } + + #[test] + fn empty_variable_is_refused() { + assert_eq!( + declared_from(None, env("")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn variable_is_exact_and_case_sensitive() { + for value in [ + "Development", + "PRODUCTION", + " production", + "production ", + "dev", + "prod", + ] { + assert_eq!( + declared_from(None, env(value)), + Err(PostureError::InvalidEnvironment), + "{value:?}" + ); + } + } + + #[cfg(unix)] + #[test] + fn non_utf8_variable_is_refused() { + use std::os::unix::ffi::OsStrExt; + let value = OsStr::from_bytes(b"production\xff"); + assert_eq!( + declared_from(None, Some(value)), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn bad_flag_is_refused() { + for value in ["", "Development", " production", "staging"] { + assert_eq!( + declared_from(Some(value), None), + Err(PostureError::InvalidFlag), + "{value:?}" + ); + } + } + + #[test] + fn bad_flag_is_refused_beside_a_valid_variable() { + assert_eq!( + declared_from(Some("staging"), env("production")), + Err(PostureError::InvalidFlag) + ); + } + + #[test] + fn bad_variable_is_refused_beside_a_valid_flag() { + assert_eq!( + declared_from(Some("production"), env("staging")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn bad_variable_is_reported_before_a_bad_flag() { + assert_eq!( + declared_from(Some("staging"), env("staging")), + Err(PostureError::InvalidEnvironment) + ); + } + + #[test] + fn error_codes_are_stable() { + assert_eq!( + PostureError::InvalidEnvironment.code(), + "platform.posture.invalid-value" + ); + assert_eq!( + PostureError::InvalidFlag.code(), + "platform.posture.invalid-value" + ); + assert_eq!(PostureError::Conflict.code(), "platform.posture.conflict"); + } + + #[test] + fn error_text_is_value_free_and_displayed() { + for error in [ + PostureError::InvalidEnvironment, + PostureError::InvalidFlag, + PostureError::Conflict, + ] { + assert_eq!(error.to_string(), error.message()); + assert!(!error.suggested_action().is_empty()); + } + assert_eq!( + PostureError::InvalidEnvironment.message(), + "REGISTRY_STACK_POSTURE is set to a value that is not a posture" + ); + assert_eq!( + PostureError::InvalidFlag.message(), + "--posture was given a value that is not a posture" + ); + assert_eq!( + PostureError::Conflict.message(), + "--posture and REGISTRY_STACK_POSTURE declare different postures" + ); + } + + #[test] + fn posture_spellings_round_trip() { + for posture in [Posture::Development, Posture::Production] { + assert_eq!(Posture::parse(posture.as_str()), Some(posture)); + } + assert_eq!(POSTURE_ENV, "REGISTRY_STACK_POSTURE"); + assert_eq!(POSTURE_FLAG, "posture"); + assert_eq!(POSTURE_HEADER, "registry-posture"); + } +} diff --git a/crates/registry-platform-provision/Cargo.toml b/crates/registry-platform-provision/Cargo.toml new file mode 100644 index 0000000000..8473cf6360 --- /dev/null +++ b/crates/registry-platform-provision/Cargo.toml @@ -0,0 +1,66 @@ +[package] +name = "registry-platform-provision" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Product-free PostgreSQL provisioning plans: roles, database, schemas and extensions for Registry Stack runtimes." +repository.workspace = true +publish = false + +[lints] +workspace = true + +[features] +default = [] +# Runs tests/postgres.rs against the disposable PostgreSQL superuser named by +# PROVISION_TEST_DATABASE_URL, over TLS verified with PROVISION_TEST_DATABASE_CA. +# It also needs PROVISION_TEST_OLD_DATABASE_URL, a server older than the floor. +# With the feature on, a missing variable fails the suite. With `cli` on too, +# src/cli.rs also runs the `provision` command against the first server. +postgres-test = [] +# Test helpers for the provision tests of the products that use this crate: +# a verified-TLS superuser session and the two PROVISION_TEST_DATABASE_* +# variables. Dev-dependencies only, never a runtime build. +test-support = [] + +# The shared `provision` command: clap arguments, the runner and the report. +cli = [ + "dep:clap", + "dep:registry-cli-report", + "dep:registry-platform-yaml", + "dep:serde", + "dep:serde_json", +] +# Renders the report's JSON Schema from its Rust type. +schema = ["cli", "dep:schemars", "registry-platform-yaml/schema"] + +[[test]] +name = "postgres" +required-features = ["postgres-test"] + +[[example]] +name = "provision-report-schema" +required-features = ["schema"] + +[dependencies] +clap = { workspace = true, optional = true } +postgres-protocol.workspace = true +registry-cli-report = { workspace = true, optional = true } +registry-platform-activation.workspace = true +registry-platform-yaml = { workspace = true, optional = true } +rustls.workspace = true +schemars = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } +thiserror.workspace = true +tokio = { workspace = true, features = ["rt", "time"] } +tokio-postgres.workspace = true +tokio-postgres-rustls.workspace = true +url.workspace = true +zeroize.workspace = true + +[dev-dependencies] +getrandom.workspace = true +tempfile.workspace = true +tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md new file mode 100644 index 0000000000..cf225c38ee --- /dev/null +++ b/crates/registry-platform-provision/README.md @@ -0,0 +1,64 @@ +# Registry Platform Provision + +`registry-platform-provision` turns what a product needs from an empty +PostgreSQL server into an ordered plan of statements: the migration and runtime +login roles, an isolated database that is closed to `PUBLIC`, the schema layout +the product's migrations expect, and the optional `btree_gist` and PostGIS +extensions. + +A product describes itself as data (`ProductDatabase`) and names its roles and +database (`ProvisionTarget`). The crate carries no product, schema or role +name. + +- `plan` builds the statements. A statement with a `Probe` runs only when its + object is absent. A grant, revoke or connection switch has no probe and is + safe to run again. A single-role target (one name for both roles) plans one + role. +- `render_script` prints the plan for an administrator to review and run with + `psql`. The script holds no password and no password verifier: each login + role is followed by a `\password` line, a statement that needs a superuser + is marked, and the script stops at the first error. A role or database name + with a control character, a backslash or a bidirectional formatting + character, a database name with `=` or one that starts with `postgresql://` + or `postgres://`, the role names `public`, `none` and `pg_*`, and the + databases `postgres`, `template0` and `template1` are refused when the plan + is built, so no name can start a `psql` meta-command or reach another + database. +- `verify_server_version` refuses a server below the shared PostgreSQL floor, + `registry_platform_activation::MINIMUM_SERVER_VERSION_NUM`. +- `sql` holds the statement builders and the identifier and literal quoting. +- `execute` and `execute_recording` run a plan against a server as an + administrator, and `verify_logins` opens a session as each product role. + They open network connections. `admin_config` accepts only a `postgres://` + URL naming one TCP host, and every connection uses TLS verified against + `caBundleRef` or the platform roots (`sslmode=verify-ca` is checked as + `verify-full`). In `Mode::Converge` the server version is checked before the + first statement, and an existing role, database, schema or extension in + another shape is refused and never altered: a role with other attributes, + a default for `role`, `search_path` or `session_authorization`, or a + membership the plan did not grant, a template database, a PostGIS installed + outside the plan's schema or without the bbox membership. + `execute_recording` keeps the outcomes of the statements that ran before a + failure. A session that cannot open in the new database after the + server-scope statements ran is reported as `database-connect-failed`, with + those statements listed. + +Passwords enter only through `RoleCredential`, whose `Debug` prints the name. +The executable text of a role statement carries a SCRAM-SHA-256 verifier +computed in the client, never the password. No API in this crate prints, +formats or logs a secret. + +## Features + +- `cli` adds the shared `provision` command (`cli::run_provision`): its clap + arguments, the runner and the report. A product supplies a loader that turns + its runtime file into a `ProvisionInput`. The runner reads role and database + names and passwords from the two product URLs, opens a connection only + outside `--print-sql`, and never prints a password, a verifier or a URL. +- `schema` renders the report's JSON Schema from its Rust type. +- `test-support` adds `test_support`, a verified-TLS superuser session and the + two `PROVISION_TEST_DATABASE_*` variables, for the provision tests of the + products that use this crate, and `Mode::Fresh`, which skips the probes. + Only their dev-dependencies enable it. +- `postgres-test` runs `tests/postgres.rs` against a disposable server. Its + header names the three variables it needs. diff --git a/crates/registry-platform-provision/example/provision-report.json b/crates/registry-platform-provision/example/provision-report.json new file mode 100644 index 0000000000..c51a030d17 --- /dev/null +++ b/crates/registry-platform-provision/example/provision-report.json @@ -0,0 +1,38 @@ +{ + "ok": true, + "command": "provision", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1", + "kind": "PlatformCliDatabaseProvisionReport", + "version": "0.49.0", + "product": "casework", + "executed": true, + "roleMode": "split", + "database": "casework", + "migrationRole": "casework_migration", + "runtimeRole": "casework_runtime", + "statements": [ + { + "step": "role.migration", + "scope": "server", + "needs": "createrole", + "outcome": "created", + "sql": "CREATE ROLE \"casework_migration\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS" + }, + { + "step": "database.create", + "scope": "server", + "needs": "createdb", + "outcome": "present", + "sql": "CREATE DATABASE \"casework\" WITH ALLOW_CONNECTIONS false" + }, + { + "step": "database.revoke-public", + "scope": "server", + "needs": "database-owner", + "outcome": "applied", + "sql": "REVOKE ALL ON DATABASE \"casework\" FROM PUBLIC" + } + ], + "diagnostics": [] +} diff --git a/crates/registry-platform-provision/examples/provision-report-schema.rs b/crates/registry-platform-provision/examples/provision-report-schema.rs new file mode 100644 index 0000000000..5034db380e --- /dev/null +++ b/crates/registry-platform-provision/examples/provision-report-schema.rs @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 + +#[cfg(feature = "schema")] +fn main() -> std::process::ExitCode { + let usage = "usage: provision-report-schema --output "; + let mut arguments = std::env::args_os().skip(1); + let (Some(flag), Some(output), None) = (arguments.next(), arguments.next(), arguments.next()) + else { + eprintln!("{usage}"); + return std::process::ExitCode::from(2); + }; + if flag != "--output" { + eprintln!("{usage}"); + return std::process::ExitCode::from(2); + } + let output = std::path::PathBuf::from(output); + let document = match registry_platform_provision::cli::report_schema_document() { + Ok(document) => document, + Err(error) => { + eprintln!("provision report schema generation failed: {error}"); + return std::process::ExitCode::FAILURE; + } + }; + let written = match output.parent() { + Some(parent) => std::fs::create_dir_all(parent), + None => Ok(()), + } + .and_then(|()| std::fs::write(&output, document)); + if let Err(error) = written { + eprintln!("provision report schema generation failed: {error}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS +} + +#[cfg(not(feature = "schema"))] +fn main() -> std::process::ExitCode { + eprintln!("provision-report-schema requires the schema feature"); + std::process::ExitCode::from(2) +} diff --git a/crates/registry-platform-provision/schema/provision-report.schema.json b/crates/registry-platform-provision/schema/provision-report.schema.json new file mode 100644 index 0000000000..c27832dfc8 --- /dev/null +++ b/crates/registry-platform-provision/schema/provision-report.schema.json @@ -0,0 +1,331 @@ +{ + "$defs": { + "CheckScope": { + "additionalProperties": false, + "description": "A source file relative to the project and the resource path a check reports.", + "properties": { + "file": { + "minLength": 1, + "type": "string" + }, + "path": { + "description": "A pointer whose list positions use existing unique identifiers when available.", + "type": "string" + } + }, + "required": [ + "file", + "path" + ], + "type": "object" + }, + "Diagnostic": { + "additionalProperties": false, + "description": "One problem, in the shape every checking command reports (CFG-DIAG-1).\n\nMessages name keys, paths, accepted values, bounds, and the expected\nenvelope without repeating rejected scalar values (CFG-SEC-3). Warning\nacceptance metadata separately identifies the resource and carries the\nproject's deliberately authored reason.", + "properties": { + "acceptedReason": { + "description": "The project's reason for accepting this advisory warning.", + "type": [ + "string", + "null" + ] + }, + "artifact": { + "description": "The document's `kind`, or the expected kind when the document's own is\nabsent or wrong and the reader expected exactly one.", + "type": [ + "string", + "null" + ] + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "RFC 6901 JSON pointer into the document as written; `\"\"` is the root.", + "type": "string" + }, + "related": { + "items": { + "$ref": "#/$defs/Related" + }, + "type": "array" + }, + "scope": { + "anyOf": [ + { + "$ref": "#/$defs/CheckScope" + }, + { + "type": "null" + } + ], + "description": "Project-relative identity copied into a check acceptance." + }, + "severity": { + "$ref": "#/$defs/Severity" + }, + "source": { + "anyOf": [ + { + "$ref": "#/$defs/Source" + }, + { + "type": "null" + } + ] + }, + "suggestedAction": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "path", + "message", + "suggestedAction" + ], + "type": "object" + }, + "Related": { + "additionalProperties": false, + "description": "A second place that explains a diagnostic, such as the first occurrence\nof a duplicate. Human output prints it as a `note:` line.", + "properties": { + "column": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "file", + "path", + "message" + ], + "type": "object" + }, + "ReportNeeds": { + "enum": [ + "createrole", + "createdb", + "database-owner", + "superuser" + ], + "type": "string" + }, + "ReportOutcome": { + "enum": [ + "created", + "present", + "applied", + "not-run" + ], + "type": "string" + }, + "ReportScope": { + "enum": [ + "server", + "database" + ], + "type": "string" + }, + "ReportStatement": { + "additionalProperties": false, + "description": "One planned statement. `sql` is the printable form, never a password or a\nverifier.", + "properties": { + "needs": { + "$ref": "#/$defs/ReportNeeds" + }, + "outcome": { + "$ref": "#/$defs/ReportOutcome", + "description": "`not-run` for a statement the run did not reach, the one that failed\nincluded. After `platform.provision.effect-unconfirmed` the statement\nthe diagnostic names was sent and may have taken effect." + }, + "scope": { + "$ref": "#/$defs/ReportScope" + }, + "sql": { + "type": "string" + }, + "step": { + "type": "string" + } + }, + "required": [ + "step", + "scope", + "needs", + "outcome", + "sql" + ], + "type": "object" + }, + "ReportStatus": { + "description": "Result class of a run, as in every other verb's report.", + "enum": [ + "complete", + "domain-refusal", + "usage-error", + "operational-failure" + ], + "type": "string" + }, + "RoleMode": { + "enum": [ + "split", + "single" + ], + "type": "string" + }, + "Severity": { + "description": "Whether a diagnostic refuses the input.", + "enum": [ + "error", + "warning" + ], + "type": "string" + }, + "Source": { + "additionalProperties": false, + "description": "Where a diagnostic points. `file` is the path exactly as the caller gave\nit; `line` and `column` are 1-based and absent when the problem concerns\nthe file as a whole.", + "properties": { + "column": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 18446744073709551615, + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "file" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Machine-readable result of `provision` for every database-backed tool.\nThe identity members are absent when the run stopped before the product's\nruntime file could name them.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1" + }, + "command": { + "const": "provision" + }, + "database": { + "type": [ + "string", + "null" + ] + }, + "diagnostics": { + "items": { + "$ref": "#/$defs/Diagnostic" + }, + "type": "array" + }, + "executed": { + "description": "Whether a statement could have been sent to the server: false for a\nprint-mode run and for a run that stopped before the first statement.\nTrue whenever a statement is listed as run.", + "type": "boolean" + }, + "kind": { + "const": "PlatformCliDatabaseProvisionReport" + }, + "migrationRole": { + "type": [ + "string", + "null" + ] + }, + "ok": { + "type": "boolean" + }, + "product": { + "type": [ + "string", + "null" + ] + }, + "roleMode": { + "anyOf": [ + { + "$ref": "#/$defs/RoleMode" + }, + { + "type": "null" + } + ] + }, + "runtimeRole": { + "type": [ + "string", + "null" + ] + }, + "statements": { + "items": { + "$ref": "#/$defs/ReportStatement" + }, + "type": "array" + }, + "status": { + "$ref": "#/$defs/ReportStatus" + }, + "version": { + "type": "string" + } + }, + "required": [ + "ok", + "command", + "status", + "apiVersion", + "kind", + "version", + "executed", + "statements", + "diagnostics" + ], + "title": "Registry Stack CLI database provision report", + "type": "object" +} diff --git a/crates/registry-platform-provision/src/admin.rs b/crates/registry-platform-provision/src/admin.rs new file mode 100644 index 0000000000..9b922a171c --- /dev/null +++ b/crates/registry-platform-provision/src/admin.rs @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The administrator connection: URL rules, verified TLS and bounded sessions. +//! +//! Nothing in this module echoes the URL, the password or a driver message +//! into an error. Errors name the rule that failed or the SQLSTATE. + +use std::{future::Future, str::FromStr, time::Duration}; + +use rustls::pki_types::{pem::PemObject as _, CertificateDer}; +use tokio_postgres::{ + config::{Host, SslMode}, + Client, Config, +}; +use tokio_postgres_rustls::MakeRustlsConnect; +use url::Url; + +pub(crate) const CONNECTION_TIMEOUT: Duration = Duration::from_secs(10); +pub(crate) const STATEMENT_TIMEOUT: Duration = Duration::from_secs(10); +pub(crate) const OPERATION_TIMEOUT: Duration = Duration::from_secs(15); +const KEEPALIVE_IDLE: Duration = Duration::from_secs(30); +const DEFAULT_PORT: u16 = 5432; + +/// A validated administrator endpoint with its TLS settings. `Debug` prints +/// the host, port, user and database only. +#[derive(Clone)] +pub struct AdminConfig { + config: Config, + tls: MakeRustlsConnect, + host: String, + port: u16, +} + +/// Why an administrator URL or CA file was refused. Each message names the +/// rule, never the URL. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum AdminConfigError { + #[error("the PostgreSQL admin URL is not a parseable URL")] + NotParseable, + #[error("the PostgreSQL admin URL must be an absolute postgres:// or postgresql:// URL")] + NotAPostgresUrl, + #[error("the PostgreSQL admin URL must include an explicit host, user, and password")] + MissingEndpointOrCredentials, + #[error("the PostgreSQL admin URL must include one explicit database name")] + MissingDatabase, + #[error("the PostgreSQL admin URL must not override its endpoint or credentials in the query")] + QueryOverridesEndpoint, + #[error( + "the PostgreSQL admin URL sslmode must be require, verify-ca, or verify-full; \ + provisioning always uses verified TLS" + )] + UnsupportedSslMode, + #[error("the PostgreSQL admin URL must not set sslrootcert; pass the CA PEM file instead")] + SslRootCertInUrl, + #[error( + "the PostgreSQL admin URL has a query parameter that is not supported; \ + only connect_timeout and application_name are" + )] + UnsupportedQueryParameter, + #[error("the PostgreSQL admin URL has an invalid query parameter value")] + InvalidQueryValue, + #[error("the PostgreSQL admin URL must name one TCP host, user, password, and database")] + NotOneTcpEndpoint, + #[error("the PostgreSQL CA PEM is invalid or holds no certificate")] + CaInvalid, + #[error("cannot initialize the PostgreSQL TLS provider")] + TlsProvider, + #[error("cannot load native roots for PostgreSQL TLS")] + NativeRoots, +} + +impl AdminConfigError { + /// The diagnostic code of the report. + pub fn code(&self) -> &'static str { + match self { + Self::CaInvalid | Self::TlsProvider | Self::NativeRoots => { + "platform.provision.admin-ca-invalid" + } + _ => "platform.provision.admin-url-invalid", + } + } +} + +/// Validates an administrator URL and builds its verified-TLS settings. +/// +/// With `ca_pem`, the server certificate must chain to it. Without, the +/// platform's native roots are used. The connection always requires TLS. +pub fn admin_config(url: &str, ca_pem: Option<&[u8]>) -> Result { + let parsed = Url::parse(url).map_err(|_| AdminConfigError::NotParseable)?; + if !matches!(parsed.scheme(), "postgres" | "postgresql") + || parsed.cannot_be_a_base() + || parsed.fragment().is_some() + { + return Err(AdminConfigError::NotAPostgresUrl); + } + if parsed.username().is_empty() + || parsed.password().is_none_or(str::is_empty) + || parsed.host().is_none() + { + return Err(AdminConfigError::MissingEndpointOrCredentials); + } + let database = parsed.path().strip_prefix('/').unwrap_or_default(); + if database.is_empty() || database.contains('/') { + return Err(AdminConfigError::MissingDatabase); + } + if parsed.query_pairs().any(|(key, _)| { + matches!( + key.as_ref(), + "host" | "hostaddr" | "port" | "user" | "password" | "dbname" + ) + }) { + return Err(AdminConfigError::QueryOverridesEndpoint); + } + for (key, value) in parsed.query_pairs() { + match key.as_ref() { + "sslmode" => { + if !matches!(value.as_ref(), "require" | "verify-ca" | "verify-full") { + return Err(AdminConfigError::UnsupportedSslMode); + } + } + "sslrootcert" => return Err(AdminConfigError::SslRootCertInUrl), + "connect_timeout" | "application_name" => {} + _ => return Err(AdminConfigError::UnsupportedQueryParameter), + } + } + + // tokio-postgres does not parse verify-ca or verify-full, and provisioning + // sets its own TLS mode, so the checked sslmode is not passed on. + let mut sanitized = parsed.clone(); + let kept: Vec<(String, String)> = parsed + .query_pairs() + .filter(|(key, _)| key != "sslmode") + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect(); + if kept.is_empty() { + sanitized.set_query(None); + } else { + sanitized.query_pairs_mut().clear().extend_pairs(kept); + } + let mut config = + Config::from_str(sanitized.as_str()).map_err(|_| AdminConfigError::InvalidQueryValue)?; + config.keepalives_idle(KEEPALIVE_IDLE); + config.ssl_mode(SslMode::Require); + if config.get_hosts().len() != 1 + || !matches!(config.get_hosts().first(), Some(Host::Tcp(_))) + || !config.get_hostaddrs().is_empty() + || config.get_user().is_none_or(str::is_empty) + || config.get_password().is_none_or(<[u8]>::is_empty) + || config.get_dbname().is_none_or(str::is_empty) + { + return Err(AdminConfigError::NotOneTcpEndpoint); + } + apply_session_options(&mut config); + + let host = match config.get_hosts().first() { + Some(Host::Tcp(host)) => host.clone(), + _ => return Err(AdminConfigError::NotOneTcpEndpoint), + }; + let port = config.get_ports().first().copied().unwrap_or(DEFAULT_PORT); + Ok(AdminConfig { + config, + tls: tls_connector(ca_pem)?, + host, + port, + }) +} + +impl AdminConfig { + pub fn host(&self) -> &str { + &self.host + } + + pub fn port(&self) -> u16 { + self.port + } + + pub fn user(&self) -> &str { + self.config.get_user().unwrap_or_default() + } + + /// The database the administrator URL names. + pub fn database(&self) -> &str { + self.config.get_dbname().unwrap_or_default() + } + + /// Opens a session to `database` as the administrator. + pub(crate) async fn connect(&self, database: Option<&str>) -> Result { + let mut config = self.config.clone(); + if let Some(database) = database { + config.dbname(database); + } + Session::open(&config, &self.tls).await + } + + /// Opens a session to `database` as another role, over the same endpoint. + pub(crate) async fn connect_as( + &self, + database: &str, + role: &str, + password: &str, + ) -> Result { + let mut config = self.config.clone(); + config.dbname(database).user(role).password(password); + Session::open(&config, &self.tls).await + } +} + +#[cfg(feature = "test-support")] +impl AdminConfig { + /// Opens a session to `database` whose connection task runs on the current + /// runtime for as long as the client lives. The failure is the driver's, + /// which carries neither the URL nor the password. + pub(crate) async fn connect_detached( + &self, + database: Option<&str>, + ) -> Result { + let mut config = self.config.clone(); + if let Some(database) = database { + config.dbname(database); + } + let (client, connection) = config.connect(self.tls.clone()).await?; + tokio::spawn(connection); + Ok(client) + } +} + +impl std::fmt::Debug for AdminConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AdminConfig") + .field("host", &self.host) + .field("port", &self.port) + .field("user", &self.user()) + .field("database", &self.database()) + .finish_non_exhaustive() + } +} + +/// Startup options for every administrator session: the statement deadline and +/// the CREATEROLE self-grant. The comma in the self-grant value is not a +/// separator for the server's startup option parser, which splits on spaces. +fn apply_session_options(config: &mut Config) { + let added = format!( + "-c statement_timeout={} -c createrole_self_grant={}", + STATEMENT_TIMEOUT.as_millis(), + crate::sql::CREATEROLE_SELF_GRANT + ); + if let Some(existing) = config.get_options().filter(|value| !value.is_empty()) { + config.options(format!("{existing} {added}")); + } else { + config.options(added); + } +} + +fn tls_connector(ca_pem: Option<&[u8]>) -> Result { + let provider = rustls::crypto::ring::default_provider(); + if provider.install_default().is_err() + && rustls::crypto::CryptoProvider::get_default().is_none() + { + return Err(AdminConfigError::TlsProvider); + } + + if let Some(pem) = ca_pem { + let mut roots = rustls::RootCertStore::empty(); + let mut count = 0usize; + for certificate in CertificateDer::pem_slice_iter(pem) { + let certificate = certificate.map_err(|_| AdminConfigError::CaInvalid)?; + roots + .add(certificate) + .map_err(|_| AdminConfigError::CaInvalid)?; + count += 1; + } + if count == 0 { + return Err(AdminConfigError::CaInvalid); + } + let config = rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(MakeRustlsConnect::new(config)) + } else { + MakeRustlsConnect::with_native_certs() + .map(|value| value.0) + .map_err(|_| AdminConfigError::NativeRoots) + } +} + +/// Why a session could not be opened. Carries the SQLSTATE when the server +/// answered, never the driver's message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ConnectFailure { + pub sqlstate: Option, +} + +/// One open session. Dropping it ends the connection task. +pub(crate) struct Session { + pub client: Client, + task: tokio::task::JoinHandle>, +} + +impl Session { + async fn open(config: &Config, tls: &MakeRustlsConnect) -> Result { + let attempt = tokio::time::timeout(CONNECTION_TIMEOUT, config.connect(tls.clone())).await; + match attempt { + Ok(Ok((client, connection))) => Ok(Self { + client, + task: tokio::spawn(connection), + }), + Ok(Err(error)) => Err(ConnectFailure { + sqlstate: error.code().map(|code| code.code().to_owned()), + }), + Err(_) => Err(ConnectFailure { sqlstate: None }), + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// How one database call ended, without the driver's message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum CallFailure { + /// The server answered with this SQLSTATE. + Server { sqlstate: String }, + /// The deadline passed or the connection broke: whether the server + /// applied the call is unknown. + Unconfirmed, +} + +impl CallFailure { + pub(crate) fn lacks_privilege(&self) -> bool { + matches!(self, Self::Server { sqlstate } if sqlstate == "42501") + } +} + +pub(crate) async fn bounded_call( + future: impl Future>, +) -> Result { + match tokio::time::timeout(OPERATION_TIMEOUT, future).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(match error.as_db_error() { + Some(db) => CallFailure::Server { + sqlstate: db.code().code().to_owned(), + }, + None => CallFailure::Unconfirmed, + }), + Err(_) => Err(CallFailure::Unconfirmed), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const URL: &str = "postgresql://admin:secret-pw@db.example:5433/postgres"; + + /// A throwaway self-signed CA certificate. Only its structure matters here. + fn test_ca_pem() -> &'static str { + "-----BEGIN CERTIFICATE-----\n\ + MIIDGzCCAgOgAwIBAgIUXGhkX0Z058UoUVAxJidqxKazAaQwDQYJKoZIhvcNAQEL\n\ + BQAwHTEbMBkGA1UEAwwSbTMtczIgdGhyb3dhd2F5IENBMB4XDTI2MTEyNzAwMzA1\n\ + NVoXDTI2MTEyOTAwMzA1NVowHTEbMBkGA1UEAwwSbTMtczIgdGhyb3dhd2F5IENB\n\ + MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKgPCAb1XWG8zeCpVIrg\n\ + IkAHtIqq7KlkqgGhTDBLTwFMoyBlnHUT+3qd87+0scqpv0IJA38DthaVVOo3UUkg\n\ + pPUBZySYSljOAfkDvBdJ3ev40Ww8uFl9br/XlWrrskfwC1HAjswdAzRUMSqnV/wH\n\ + In5Sb++75rnZbfUUYBbHcvT2MLlULWX98wDFGQXbEMvWbPsDlzFmYga3K98XUQDr\n\ + clbDEFACakpK2SpKFPS2azvfnRehN28eOauBlRbRHnZcS1gLDeqmnRviJoYsoOvE\n\ + tYIMN+YZCaSNZUpuD7bN1iHGOeTBDatT7ZSwArKDBV0yJHbhi/6nfPka/M3e8b1/\n\ + xQIDAQABo1MwUTAdBgNVHQ4EFgQUeaMUxXla07H5aYfj7dYnVJlTKHYwHwYDVR0j\n\ + BBgwFoAUeaMUxXla07H5aYfj7dYnVJlTKHYwDwYDVR0TAQH/BAUwAwEB/zANBgkq\n\ + hkiG9w0BAQsFAAOCAQEACC7s1MOYnU7322I3dvweCuwJvZ7a1T6KO0GyaMsw1uZZ\n\ + 2vvaTrJgQBDi5n4/pNOgx9ZzQxyBQR7QvVEV/z20x/gVOH1uQq9gQnMGAA+rFdHR\n\ + LgoNLe1zY6THUkD4l+KWQgraUKtAf0Ko1ruLrrMbH4tq3w6bJX7KeHrWsKDY04/d\n\ + /HyACVlWnoGeuyPppd6009SuMwQvKMUDz+UU55Jj49FLHWAH9V9AbuLmHkbdKQ1x\n\ + qE5kizB4UytufC/y99522L3p2bD0pAvHSxDIXYtAlC3Fx4XyFbT+5/JY3hYRwbfs\n\ + 6NlpU4TdevxbiVlIM5anyYHY+yhBKdIQH1D+0lOfvw==\n\ + -----END CERTIFICATE-----\n" + } + + fn refused(url: &str) -> AdminConfigError { + admin_config(url, Some(b"")).expect_err("the URL should be refused") + } + + #[test] + fn url_rules_are_named_and_never_echo_the_url() { + let cases: [(&str, AdminConfigError); 9] = [ + ("not a url", AdminConfigError::NotParseable), + ("mysql://a:b@h/db", AdminConfigError::NotAPostgresUrl), + ( + "postgresql://h/db", + AdminConfigError::MissingEndpointOrCredentials, + ), + ( + "postgresql://a:secret-pw@h/", + AdminConfigError::MissingDatabase, + ), + ( + "postgresql://a:secret-pw@h/db?port=1", + AdminConfigError::QueryOverridesEndpoint, + ), + ( + "postgresql://a:secret-pw@h/db?sslmode=disable", + AdminConfigError::UnsupportedSslMode, + ), + ( + "postgresql://a:secret-pw@h/db?sslrootcert=/x", + AdminConfigError::SslRootCertInUrl, + ), + ( + "postgresql://a:secret-pw@h/db?options=x", + AdminConfigError::UnsupportedQueryParameter, + ), + ( + "postgresql://a:secret-pw@h/db?connect_timeout=soon", + AdminConfigError::InvalidQueryValue, + ), + ]; + for (url, expected) in cases { + let error = refused(url); + // The CA is checked after the URL, so a URL rule is what fires first. + assert_eq!(error, expected, "{url}"); + assert_eq!(error.code(), "platform.provision.admin-url-invalid"); + assert!(!error.to_string().contains("secret-pw")); + assert!(!format!("{error:?}").contains("secret-pw")); + } + } + + #[test] + fn a_ca_without_certificates_is_refused_with_its_own_code() { + let error = admin_config(URL, Some(b"")).unwrap_err(); + assert_eq!(error, AdminConfigError::CaInvalid); + assert_eq!(error.code(), "platform.provision.admin-ca-invalid"); + let error = admin_config(URL, Some(b"not a certificate")).unwrap_err(); + assert_eq!(error, AdminConfigError::CaInvalid); + } + + #[test] + fn debug_prints_the_endpoint_and_no_password() { + let ca = test_ca_pem(); + let config = admin_config(URL, Some(ca.as_bytes())).expect("valid administrator URL"); + let printed = format!("{config:?}"); + assert!(printed.contains("db.example")); + assert!(printed.contains("5433")); + assert!(!printed.contains("secret-pw")); + assert_eq!(config.host(), "db.example"); + assert_eq!(config.port(), 5433); + assert_eq!(config.user(), "admin"); + assert_eq!(config.database(), "postgres"); + } + + #[test] + fn session_options_carry_the_deadline_and_the_self_grant() { + let ca = test_ca_pem(); + let config = admin_config(URL, Some(ca.as_bytes())).expect("valid administrator URL"); + let options = config.config.get_options().expect("options are set"); + assert!(options.contains("statement_timeout=10000")); + assert!(options.contains("createrole_self_grant=set,inherit")); + } + + #[test] + fn the_port_defaults_to_5432() { + let ca = test_ca_pem(); + let config = admin_config("postgresql://a:secret-pw@h/db", Some(ca.as_bytes())) + .expect("valid administrator URL"); + assert_eq!(config.port(), 5432); + } +} diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs new file mode 100644 index 0000000000..1c7ff221ab --- /dev/null +++ b/crates/registry-platform-provision/src/cli.rs @@ -0,0 +1,2655 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The `provision` command every database-backed tool shares: its arguments, +//! its runner and its report. +//! +//! A product supplies a loader that turns its runtime file into a +//! [`ProvisionInput`]. The runner takes role and database names and passwords +//! from the two product URLs, so each credential is stored once. It never +//! prints a password, a verifier or a URL. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::str::FromStr; + +use registry_platform_yaml::Diagnostic; +use serde::Serialize; +use tokio_postgres::config::Host; +use tokio_postgres::Config; +use url::Url; +use zeroize::Zeroizing; + +use crate::{ + admin_config, execute_recording, render_script, verify_logins, AdminConfig, AdminConfigError, + Failure, Mode, Needs, Outcome, Plan, PlanError, ProductDatabase, ProvisionError, + ProvisionTarget, RoleCredential, Scope, StatementOutcome, +}; + +pub const REPORT_API_VERSION: &str = + "id.registrystack.org/formats/platform/cli-database-provision-report/v1alpha1"; +pub const REPORT_KIND: &str = "PlatformCliDatabaseProvisionReport"; + +/// How the command writes its result. A tool maps its own global `--format` +/// (`human | json`) onto this. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum OutputFormat { + #[default] + Human, + Json, +} + +/// The flags of ` provision`. The output format is the tool's own global +/// `--format` flag, passed to [`run_provision`]. +#[derive(clap::Args, Debug, Clone)] +pub struct ProvisionArgs { + /// Runtime configuration file, the one the service runs with + #[arg(long, value_name = "FILE")] + pub runtime_config: PathBuf, + /// File holding the administrator PostgreSQL URL + #[arg( + long, + value_name = "ADMIN_URL_FILE", + conflicts_with_all = ["admin_url_env", "print_sql"], + required_unless_present_any = ["admin_url_env", "print_sql"] + )] + pub admin_url_file: Option, + /// Name of the environment variable holding the administrator PostgreSQL URL + #[arg( + long, + value_name = "ADMIN_URL_ENV", + conflicts_with = "print_sql", + required_unless_present_any = ["admin_url_file", "print_sql"] + )] + pub admin_url_env: Option, + /// Print the SQL script and connect to nothing + #[arg(long)] + pub print_sql: bool, + /// Declared posture: development or production. Unset means production. + #[arg(long = "posture", value_name = "POSTURE")] + pub posture: Option, +} + +/// What a product's loader hands the runner. A loader refuses with one +/// diagnostic, boxed because the diagnostic is large. +pub struct ProvisionInput { + pub product: ProductDatabase, + pub migration_url: Zeroizing, + pub runtime_url: Zeroizing, + /// The CA behind `database.caBundleRef`, for the administrator connection. + pub ca_pem: Option>, +} + +/// Result class of a run, as in every other verb's report. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportStatus { + Complete, + DomainRefusal, + UsageError, + OperationalFailure, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum RoleMode { + Split, + Single, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportScope { + Server, + Database, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum ReportNeeds { + #[serde(rename = "createrole")] + CreateRole, + #[serde(rename = "createdb")] + CreateDb, + #[serde(rename = "database-owner")] + DatabaseOwner, + #[serde(rename = "superuser")] + Superuser, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReportOutcome { + Created, + Present, + Applied, + NotRun, +} + +/// One planned statement. `sql` is the printable form, never a password or a +/// verifier. +#[derive(Clone, Debug, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] +pub struct ReportStatement { + pub step: String, + pub scope: ReportScope, + pub needs: ReportNeeds, + /// `not-run` for a statement the run did not reach, the one that failed + /// included. After `platform.provision.effect-unconfirmed` the statement + /// the diagnostic names was sent and may have taken effect. + pub outcome: ReportOutcome, + pub sql: String, +} + +/// Machine-readable result of `provision` for every database-backed tool. +/// The identity members are absent when the run stopped before the product's +/// runtime file could name them. +#[derive(Clone, Debug, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] +pub struct PlatformCliDatabaseProvisionReport { + pub ok: bool, + pub command: String, + pub status: ReportStatus, + pub api_version: String, + pub kind: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option, + /// Whether a statement could have been sent to the server: false for a + /// print-mode run and for a run that stopped before the first statement. + /// True whenever a statement is listed as run. + pub executed: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub role_mode: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub database: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub migration_role: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_role: Option, + pub statements: Vec, + pub diagnostics: Vec, +} + +/// Runs the plan and then checks that each product role can log in. A test +/// replaces it, so the report logic needs no server. +type Backend<'a> = &'a dyn Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result; + +/// The most bytes read from the administrator URL file. +const MAXIMUM_ADMIN_URL_BYTES: u64 = 8192; +const DEFAULT_PORT: u16 = 5432; + +/// A product URL reduced to what provisioning takes from it. +struct Endpoint { + user: String, + password: Zeroizing, + database: String, + host: String, + port: u16, +} + +/// The query keys that would change which server, role or database a URL names. +const ENDPOINT_QUERY_KEYS: [&str; 6] = ["host", "hostaddr", "port", "user", "password", "dbname"]; + +/// Reads the role, password, database and endpoint out of a product URL. +/// The query is dropped after the keys that override the endpoint are refused: +/// the product's own reader validates the rest (`sslmode` and so on). +fn parse_endpoint(url: &str) -> Option { + let parsed = Url::parse(url).ok()?; + if !matches!(parsed.scheme(), "postgres" | "postgresql") + || parsed.cannot_be_a_base() + || parsed.fragment().is_some() + || parsed + .query_pairs() + .any(|(key, _)| ENDPOINT_QUERY_KEYS.contains(&key.as_ref())) + { + return None; + } + let mut bare = parsed; + bare.set_query(None); + let config = Config::from_str(bare.as_str()).ok()?; + let host = match config.get_hosts() { + [Host::Tcp(host)] => host.clone(), + _ => return None, + }; + let user = config.get_user().filter(|user| !user.is_empty())?; + let password = config + .get_password() + .filter(|password| !password.is_empty()) + .and_then(|password| String::from_utf8(password.to_vec()).ok())?; + let database = config.get_dbname().filter(|name| !name.is_empty())?; + Some(Endpoint { + user: user.to_owned(), + password: Zeroizing::new(password), + database: database.to_owned(), + host, + port: config.get_ports().first().copied().unwrap_or(DEFAULT_PORT), + }) +} + +/// How a run ended before any report could be written. +struct Refusal { + status: ReportStatus, + diagnostic: Box, +} + +fn refuse( + status: ReportStatus, + code: &str, + path: &str, + message: impl Into, + action: impl Into, +) -> Refusal { + Refusal { + status, + diagnostic: Box::new(Diagnostic::error(code, path, message, action)), + } +} + +fn target_invalid_with(message: &str, action: &str) -> Refusal { + refuse( + ReportStatus::UsageError, + "platform.provision.target-invalid", + "", + message, + action, + ) +} + +fn target_invalid(message: &str) -> Refusal { + target_invalid_with( + message, + "Correct database.migrationUrlRef and database.runtimeUrlRef in the runtime file, then \ + run provision again.", + ) +} + +/// A name the plan refuses. The action names the URL member to correct and +/// never quotes its value. +fn plan_refusal(error: &PlanError) -> Refusal { + let rule = "A role name must not hold a control character, a backslash or a bidirectional \ + formatting character, and must not be public, none or start with pg_."; + let action = match error { + PlanError::InvalidName { + what: "database name", + } => "Change the database name, the path of database.migrationUrlRef and \ + database.runtimeUrlRef. It must not hold a control character, a backslash, a \ + bidirectional formatting character or =, must not start with postgresql:// or \ + postgres://, and must not be postgres, template0 or template1." + .to_owned(), + PlanError::InvalidName { + what: "migration role name", + } => format!("Change the user in the migration URL (database.migrationUrlRef). {rule}"), + PlanError::InvalidName { + what: "runtime role name", + } => format!("Change the user in the runtime URL (database.runtimeUrlRef). {rule}"), + _ => "Correct database.migrationUrlRef and database.runtimeUrlRef in the runtime file, \ + then run provision again." + .to_owned(), + }; + target_invalid_with(&error.to_string(), &action) +} + +fn target_mismatch(message: String) -> Refusal { + refuse( + ReportStatus::DomainRefusal, + "platform.provision.target-mismatch", + "", + message, + "Point the URLs at one server and one database, then run provision again.", + ) +} + +/// The first of host, port and database that two endpoints disagree on. +fn first_difference(left: &Endpoint, right: &Endpoint) -> Option<&'static str> { + if !left.host.eq_ignore_ascii_case(&right.host) { + Some("host") + } else if left.port != right.port { + Some("port") + } else if left.database != right.database { + Some("database") + } else { + None + } +} + +fn read_admin_url(args: &ProvisionArgs) -> Result, Refusal> { + let unusable = |message: String, action: &str| { + refuse( + ReportStatus::UsageError, + "platform.provision.admin-url-invalid", + "", + message, + action, + ) + }; + let raw = match (&args.admin_url_file, &args.admin_url_env) { + (Some(path), None) => { + // The check before the open keeps a named pipe from blocking it. + let read = std::fs::metadata(path).and_then(|metadata| { + if metadata.is_file() { + std::fs::File::open(path) + } else { + Err(std::io::Error::other("not a regular file")) + } + }); + let read = read.and_then(|file| { + if !file.metadata()?.is_file() { + return Err(std::io::Error::other("not a regular file")); + } + let mut text = String::new(); + file.take(MAXIMUM_ADMIN_URL_BYTES + 1) + .read_to_string(&mut text) + .map(|_| text) + }); + match read { + Ok(text) if text.len() as u64 <= MAXIMUM_ADMIN_URL_BYTES => Zeroizing::new(text), + Ok(_) => { + return Err(unusable( + "the administrator URL file is larger than 8 KiB".to_owned(), + "Put only the administrator PostgreSQL URL in the file.", + )) + } + Err(_) => { + return Err(unusable( + "the administrator URL file could not be read".to_owned(), + "Check that --admin-url-file names a readable file holding the \ + administrator PostgreSQL URL.", + )) + } + } + } + (None, Some(name)) => match std::env::var(name) { + Ok(value) => Zeroizing::new(value), + Err(_) => { + return Err(unusable( + format!("the environment variable {name} is not set or is not UTF-8 text"), + "Export the administrator PostgreSQL URL in the variable that \ + --admin-url-env names.", + )) + } + }, + _ => { + return Err(unusable( + "exactly one administrator URL source is required".to_owned(), + "Pass --admin-url-file or --admin-url-env, or --print-sql.", + )) + } + }; + let url = raw.trim(); + if url.is_empty() { + return Err(unusable( + "the administrator URL is empty".to_owned(), + "Put the administrator PostgreSQL URL in the file or variable.", + )); + } + Ok(Zeroizing::new(url.to_owned())) +} + +fn admin_refusal(error: AdminConfigError) -> Refusal { + let url_rule = error.code() == "platform.provision.admin-url-invalid"; + refuse( + if url_rule { + ReportStatus::UsageError + } else { + ReportStatus::DomainRefusal + }, + error.code(), + "", + error.to_string(), + if url_rule { + "Correct the administrator URL, then run provision again." + } else { + "Correct database.caBundleRef in the runtime file, or install the CA in the system \ + trust store, then run provision again." + }, + ) +} + +/// What the report says about a refusal from the executor, with the exit +/// class of its code. +fn execution_refusal(tool: &str, error: &ProvisionError) -> Refusal { + use ProvisionError as E; + let (status, action) = match error { + E::AdminConnectFailed { sqlstate } if sqlstate.as_deref() == Some("3D000") => ( + ReportStatus::OperationalFailure, + "The database the administrator URL names does not exist. Name one that does, such \ + as postgres, then run provision again." + .to_owned(), + ), + E::AdminConnectFailed { .. } => ( + ReportStatus::OperationalFailure, + "Check the host, port, credentials and TLS certificate of the administrator URL, \ + then run provision again." + .to_owned(), + ), + E::DatabaseConnectFailed { .. } => ( + ReportStatus::OperationalFailure, + "The administrator opened a session on the server, and the statements listed as run \ + took effect. Check that the administrator role's CONNECTION LIMIT leaves room for a \ + second session and that pg_hba.conf admits it to the new database, then run \ + provision again." + .to_owned(), + ), + E::UnsupportedPostgres => ( + ReportStatus::DomainRefusal, + "Provision a PostgreSQL 17 or newer server, then run provision again.".to_owned(), + ), + E::StatementNeedsPrivilege { .. } => ( + ReportStatus::DomainRefusal, + format!( + "run this statement as a role that has it, or run \"{tool} provision \ + --print-sql\" and give the script to the database administrator, then run \ + provision again" + ), + ), + E::RoleAttributesDiffer { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or correct the role as an administrator, \ + then run provision again." + .to_owned(), + ), + E::RoleSettingsDiffer { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or reset the role's role, search_path \ + and session_authorization defaults as an administrator, then run provision again." + .to_owned(), + ), + E::RoleMembershipDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Use another role name in the product URLs, or revoke the role's memberships as an \ + administrator, then run provision again." + .to_owned(), + ), + E::DatabaseIsTemplate { .. } => ( + ReportStatus::DomainRefusal, + "Use another database name in the product URLs, then run provision again.".to_owned(), + ), + E::ExtensionIncomplete { .. } => ( + ReportStatus::DomainRefusal, + "As a superuser, run every statement of the extension.postgis step, which \ + provision --print-sql prints, after dropping a PostGIS installed in another \ + schema, then run provision again." + .to_owned(), + ), + E::DatabaseOwnerDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Use another database name, or run provision as the database owner or a role that \ + can act as it." + .to_owned(), + ), + E::SchemaOwnerDiffers { .. } => ( + ReportStatus::DomainRefusal, + "Make the migration role the owner of the schema as an administrator, or use \ + another database, then run provision again." + .to_owned(), + ), + E::ExtensionTooOld { .. } => ( + ReportStatus::DomainRefusal, + "Upgrade the extension as a superuser, then run provision again.".to_owned(), + ), + E::RoleLoginFailed { sqlstate, .. } => match sqlstate.as_deref() { + Some("28P01") => ( + ReportStatus::DomainRefusal, + "The role exists with a different password. Set its password to the one in \ + its product URL as an administrator, or correct the URL, then run provision \ + again." + .to_owned(), + ), + Some("28000") => ( + ReportStatus::DomainRefusal, + "The server refused the role. Check that the role can log in and that \ + pg_hba.conf lets it connect over TLS from this host, then run provision \ + again." + .to_owned(), + ), + Some("53300") => ( + ReportStatus::OperationalFailure, + "The role or the server has reached its connection limit. Raise the role's \ + CONNECTION LIMIT or free a connection, then run provision again." + .to_owned(), + ), + Some(_) => ( + ReportStatus::DomainRefusal, + "Read the PostgreSQL server log for the refused login, fix the cause, then run \ + provision again." + .to_owned(), + ), + None => ( + ReportStatus::OperationalFailure, + "Check that the server accepts connections from this host, then run provision \ + again." + .to_owned(), + ), + }, + E::EffectUnconfirmed { .. } => ( + ReportStatus::OperationalFailure, + "Run provision again.".to_owned(), + ), + E::StatementFailed { .. } => ( + ReportStatus::OperationalFailure, + "Read the PostgreSQL server log for that statement, fix the cause, then run \ + provision again." + .to_owned(), + ), + }; + refuse( + status, + error.code(), + error.step().unwrap_or(""), + error.to_string(), + action, + ) +} + +const fn exit_code(status: ReportStatus) -> u8 { + match status { + ReportStatus::Complete => 0, + ReportStatus::DomainRefusal => 1, + ReportStatus::UsageError => 2, + ReportStatus::OperationalFailure => 3, + } +} + +fn report_scope(scope: Scope) -> ReportScope { + match scope { + Scope::Server => ReportScope::Server, + Scope::Database => ReportScope::Database, + } +} + +fn report_needs(needs: Needs) -> ReportNeeds { + match needs { + Needs::CreateRole => ReportNeeds::CreateRole, + Needs::CreateDb => ReportNeeds::CreateDb, + Needs::DatabaseOwner => ReportNeeds::DatabaseOwner, + Needs::Superuser => ReportNeeds::Superuser, + } +} + +fn report_outcome(outcome: StatementOutcome) -> ReportOutcome { + match outcome { + StatementOutcome::Created => ReportOutcome::Created, + StatementOutcome::Present => ReportOutcome::Present, + StatementOutcome::Applied => ReportOutcome::Applied, + } +} + +fn outcome_word(outcome: ReportOutcome) -> &'static str { + match outcome { + ReportOutcome::Created => "created", + ReportOutcome::Present => "present", + ReportOutcome::Applied => "applied", + ReportOutcome::NotRun => "not-run", + } +} + +/// The plan's statements with the outcome of each statement the executor +/// reached, and `not-run` for the rest. +fn report_statements( + plan: &Plan, + reached: &[(&'static str, StatementOutcome)], +) -> Vec { + plan.statements() + .iter() + .enumerate() + .map(|(index, statement)| ReportStatement { + step: statement.step.to_owned(), + scope: report_scope(statement.scope), + needs: report_needs(statement.needs), + outcome: reached + .get(index) + .map_or(ReportOutcome::NotRun, |(_, outcome)| { + report_outcome(*outcome) + }), + sql: statement.printable.clone(), + }) + .collect() +} + +/// Writes the finished report and returns the exit code. +struct Output<'a> { + format: OutputFormat, + version: &'static str, + stdout: &'a mut dyn Write, + stderr: &'a mut dyn Write, +} + +impl Output<'_> { + /// Last resort when the streams themselves fail: the exit code carries it. + fn write_failed(&mut self, ok: bool) -> u8 { + if ok { + 0 + } else { + let _ = writeln!(self.stderr, "provision could not write its output"); + 3 + } + } + + fn json(&mut self, report: &PlatformCliDatabaseProvisionReport) -> bool { + let Ok(value) = serde_json::to_value(report) else { + return false; + }; + let Ok(envelope) = registry_cli_report::Report::new(&value, self.version) else { + return false; + }; + serde_json::to_writer_pretty(&mut *self.stdout, &envelope).is_ok() + && writeln!(self.stdout).is_ok() + } + + /// A refusal: the JSON report on stdout, or the diagnostics on stderr. + fn refusal(&mut self, report: &PlatformCliDatabaseProvisionReport) -> u8 { + let written = match self.format { + OutputFormat::Json => self.json(report), + OutputFormat::Human => { + // A run that stopped part-way shows what it had already done. + let ran = report + .statements + .iter() + .filter(|statement| statement.outcome != ReportOutcome::NotRun) + .all(|statement| { + writeln!( + self.stderr, + "{} {}", + outcome_word(statement.outcome), + statement.step + ) + .is_ok() + }); + ran && report + .diagnostics + .iter() + .all(|diagnostic| write!(self.stderr, "{}", diagnostic.render_human()).is_ok()) + } + }; + let exit = exit_code(report.status); + match self.write_failed(written) { + 0 => exit, + failed => failed, + } + } +} + +// The runner's inputs are independent (identity, arguments, format, loader, +// backend, two streams) and each is a test seam, so they stay positional. +#[allow(clippy::too_many_arguments)] +fn run_with( + tool: &'static str, + version: &'static str, + args: &ProvisionArgs, + format: OutputFormat, + load: impl FnOnce(&Path) -> Result>, + backend: Backend<'_>, + stdout: &mut dyn Write, + stderr: &mut dyn Write, +) -> u8 { + let mut output = Output { + format, + version, + stdout, + stderr, + }; + let mut report = PlatformCliDatabaseProvisionReport { + ok: false, + command: "provision".to_owned(), + status: ReportStatus::DomainRefusal, + api_version: REPORT_API_VERSION.to_owned(), + kind: REPORT_KIND.to_owned(), + version: version.to_owned(), + product: None, + executed: false, + role_mode: None, + database: None, + migration_role: None, + runtime_role: None, + statements: Vec::new(), + diagnostics: Vec::new(), + }; + let refused = |report: &mut PlatformCliDatabaseProvisionReport, refusal: Refusal| { + report.status = refusal.status; + report.diagnostics = vec![*refusal.diagnostic]; + }; + + let input = match load(&args.runtime_config) { + Ok(input) => input, + Err(diagnostic) => { + refused( + &mut report, + Refusal { + status: ReportStatus::DomainRefusal, + diagnostic, + }, + ); + return output.refusal(&report); + } + }; + report.product = Some(input.product.product.to_owned()); + let (Some(migration), Some(runtime)) = ( + parse_endpoint(&input.migration_url), + parse_endpoint(&input.runtime_url), + ) else { + refused( + &mut report, + target_invalid( + "the migration and runtime URLs must each be a postgres:// URL with a host, \ + role, password and database, and no host, port, user, password or dbname \ + in the query", + ), + ); + return output.refusal(&report); + }; + report.database = Some(migration.database.clone()); + report.migration_role = Some(migration.user.clone()); + report.runtime_role = Some(runtime.user.clone()); + report.role_mode = Some(if migration.user == runtime.user { + RoleMode::Single + } else { + RoleMode::Split + }); + if let Some(what) = first_difference(&migration, &runtime) { + refused( + &mut report, + target_mismatch(format!( + "the migration and runtime URLs name different {what}s" + )), + ); + return output.refusal(&report); + } + + let target = ProvisionTarget { + database: migration.database.clone(), + migration: RoleCredential::new(migration.user.as_str(), migration.password.as_str()), + runtime: RoleCredential::new(runtime.user.as_str(), runtime.password.as_str()), + }; + let plan = match crate::plan(&input.product, &target) { + Ok(plan) => plan, + Err(error) => { + // A refused name is not repeated in the report. + report.role_mode = None; + report.database = None; + report.migration_role = None; + report.runtime_role = None; + refused(&mut report, plan_refusal(&error)); + return output.refusal(&report); + } + }; + report.statements = report_statements(&plan, &[]); + + if args.print_sql { + report.ok = true; + report.status = ReportStatus::Complete; + let written = match format { + OutputFormat::Human => output + .stdout + .write_all(render_script(&plan).as_bytes()) + .is_ok(), + OutputFormat::Json => output.json(&report), + }; + return output.write_failed(written); + } + + let admin_url = match read_admin_url(args) { + Ok(url) => url, + Err(refusal) => { + refused(&mut report, refusal); + return output.refusal(&report); + } + }; + let admin = match admin_config(&admin_url, input.ca_pem.as_deref()) { + Ok(admin) => admin, + Err(error) => { + refused(&mut report, admin_refusal(error)); + return output.refusal(&report); + } + }; + let admin_endpoint = Endpoint { + user: admin.user().to_owned(), + password: Zeroizing::new(String::new()), + database: migration.database.clone(), + host: admin.host().to_owned(), + port: admin.port(), + }; + if let Some(what) = first_difference(&admin_endpoint, &migration) { + refused( + &mut report, + target_mismatch(format!( + "the administrator URL names a different {what} than the product URLs" + )), + ); + return output.refusal(&report); + } + + if admin.database() == target.database { + refused( + &mut report, + target_invalid_with( + "the administrator URL names the product database, which provision creates", + "Point the administrator URL at the postgres maintenance database or another \ + existing database, then run provision again.", + ), + ); + return output.refusal(&report); + } + + match backend(&admin, &plan, &target) { + Ok(outcome) => { + report.executed = true; + report.ok = true; + report.status = ReportStatus::Complete; + report.statements = report_statements(&plan, &outcome.statements); + let written = match format { + OutputFormat::Json => output.json(&report), + OutputFormat::Human => write_summary(output.stdout, &report, outcome.single_role), + }; + output.write_failed(written) + } + Err(failure) => { + report.executed = + !failure.reached.is_empty() || failure.error.may_have_run_statements(); + report.statements = report_statements(&plan, &failure.reached); + refused(&mut report, execution_refusal(tool, &failure.error)); + output.refusal(&report) + } + } +} + +/// One line per statement, then the roles and the database. +fn write_summary( + out: &mut dyn Write, + report: &PlatformCliDatabaseProvisionReport, + single_role: bool, +) -> bool { + let mut text = String::new(); + for statement in &report.statements { + text.push_str(&format!( + "{} {}\n", + outcome_word(statement.outcome), + statement.step + )); + } + let name = |value: &Option| value.clone().unwrap_or_default(); + text.push_str(&format!("database: {}\n", name(&report.database))); + if single_role { + text.push_str(&format!("role: {}\n", name(&report.migration_role))); + text.push_str(registry_platform_activation::SINGLE_ROLE_STATEMENT); + text.push('\n'); + } else { + text.push_str(&format!( + "migration role: {}\n", + name(&report.migration_role) + )); + text.push_str(&format!("runtime role: {}\n", name(&report.runtime_role))); + } + out.write_all(text.as_bytes()).is_ok() +} + +/// Converges the server, then opens a session as each product role. +fn server_backend( + runtime: &tokio::runtime::Runtime, +) -> impl Fn(&AdminConfig, &Plan, &ProvisionTarget) -> Result + '_ { + move |admin, plan, target| { + runtime.block_on(async { + let outcome = execute_recording(admin, plan, Mode::Converge).await?; + match verify_logins(admin, target).await { + Ok(()) => Ok(outcome), + Err(error) => Err(Failure { + error, + reached: outcome.statements, + }), + } + }) + } +} + +/// Runs ` provision`. `version` is the tool's own build version and goes +/// into the report. The exit code is 0 on success, 1 for a refusal, 2 for a +/// usage error and 3 for an operational failure. +pub fn run_provision( + tool: &'static str, + version: &'static str, + args: &ProvisionArgs, + format: OutputFormat, + load: impl FnOnce(&Path) -> Result>, +) -> ExitCode { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => { + eprintln!("{tool} provision could not start its async runtime"); + return ExitCode::from(3); + } + }; + let exit = run_with( + tool, + version, + args, + format, + load, + &server_backend(&runtime), + &mut std::io::stdout().lock(), + &mut std::io::stderr().lock(), + ); + ExitCode::from(exit) +} + +/// The JSON Schema of [`PlatformCliDatabaseProvisionReport`]. +#[cfg(feature = "schema")] +pub fn report_schema_document() -> Result { + const SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/cli-database-provision-report/cli-database-provision-report.v1alpha1.schema.json"; + let mut settings = schemars::generate::SchemaSettings::draft2020_12(); + settings.contract = schemars::generate::Contract::Serialize; + let schema = settings + .into_generator() + .into_root_schema_for::(); + let mut value = serde_json::to_value(schema)?; + value["$id"] = serde_json::Value::String(SCHEMA_ID.to_owned()); + value["title"] = + serde_json::Value::String("Registry Stack CLI database provision report".to_owned()); + value["properties"]["apiVersion"] = serde_json::json!({"const": REPORT_API_VERSION}); + value["properties"]["kind"] = serde_json::json!({"const": REPORT_KIND}); + value["properties"]["command"] = serde_json::json!({"const": "provision"}); + close_direct_output_structs(&mut value); + state_native_integer_bounds(&mut value); + Ok(serde_json::to_string_pretty(&value)? + "\n") +} + +/// Close the structs this module emits directly and the shared diagnostic DTOs. +#[cfg(feature = "schema")] +fn close_direct_output_structs(schema: &mut serde_json::Value) { + use serde_json::Value; + fn close(node: &mut Value) { + let Value::Object(object) = node else { + return; + }; + if object.get("type") == Some(&Value::String("object".to_owned())) + && object.contains_key("properties") + && !object.contains_key("additionalProperties") + { + object.insert("additionalProperties".to_owned(), Value::Bool(false)); + } + } + if let Some(Value::Object(definitions)) = schema.get_mut("$defs") { + definitions.values_mut().for_each(close); + } + close(schema); +} + +/// State the native range of the `usize` positions a diagnostic's source carries. +#[cfg(feature = "schema")] +fn state_native_integer_bounds(schema: &mut serde_json::Value) { + use serde_json::Value; + match schema { + Value::Object(object) => { + let bounds = object + .get("format") + .and_then(Value::as_str) + .and_then(native_integer_bounds); + if let Some((minimum, maximum)) = bounds { + object.entry("minimum").or_insert(minimum); + object.entry("maximum").or_insert(maximum); + } + object.values_mut().for_each(state_native_integer_bounds); + } + Value::Array(items) => items.iter_mut().for_each(state_native_integer_bounds), + _ => {} + } +} + +#[cfg(feature = "schema")] +fn native_integer_bounds(format: &str) -> Option<(serde_json::Value, serde_json::Value)> { + use serde_json::Value; + match format { + "uint" => Some((Value::from(0), Value::from(usize::MAX as u64))), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{SchemaLayout, Spatial}; + use clap::Parser; + use serde_json::Value; + + const MIGRATION_PASSWORD: &str = "mig-secret-7f3a"; + const RUNTIME_PASSWORD: &str = "run-secret-91bc"; + const ADMIN_PASSWORD: &str = "adm-secret-55de"; + + #[derive(Parser)] + struct Harness { + #[command(flatten)] + args: ProvisionArgs, + } + + /// Splits a test's `--format human|json` off the verb's own flags, as the + /// tool's global flag does. + pub(super) fn split_format<'a>(arguments: &[&'a str]) -> (Vec<&'a str>, OutputFormat) { + let mut rest = Vec::new(); + let mut format = OutputFormat::Human; + let mut iter = arguments.iter().copied(); + while let Some(argument) = iter.next() { + if argument == "--format" { + format = match iter.next() { + Some("json") => OutputFormat::Json, + Some("human") => OutputFormat::Human, + other => panic!("test format {other:?} is not human or json"), + }; + } else { + rest.push(argument); + } + } + (rest, format) + } + + fn parse(arguments: &[&str]) -> Result { + Harness::try_parse_from(std::iter::once("tool").chain(arguments.iter().copied())) + .map(|harness| harness.args) + } + + fn input_with(migration: &str, runtime: &str, product: ProductDatabase) -> ProvisionInput { + ProvisionInput { + product, + migration_url: Zeroizing::new(migration.to_owned()), + runtime_url: Zeroizing::new(runtime.to_owned()), + ca_pem: None, + } + } + + fn owned_product() -> ProductDatabase { + ProductDatabase { + product: "casework", + layout: SchemaLayout::Owned(vec!["casework".to_owned()]), + btree_gist: true, + spatial: None, + } + } + + fn split_input() -> ProvisionInput { + input_with( + &format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example:5432/app?sslmode=verify-full"), + &format!("postgres://app_runtime:{RUNTIME_PASSWORD}@db.example:5432/app?sslmode=verify-full"), + owned_product(), + ) + } + + fn admin_url(host: &str, port: u16) -> String { + format!("postgres://admin:{ADMIN_PASSWORD}@{host}:{port}/postgres?sslmode=verify-full") + } + + struct Run { + exit: u8, + stdout: String, + stderr: String, + } + + impl Run { + fn json(&self) -> Value { + serde_json::from_str(&self.stdout).expect("stdout is one JSON report") + } + fn all_output(&self) -> String { + format!("{}{}", self.stdout, self.stderr) + } + } + + fn execute_run( + arguments: &[&str], + admin_file: Option<&str>, + input: Result>, + backend: Backend<'_>, + ) -> Run { + let directory = tempfile::tempdir().expect("scratch directory"); + let (arguments, format) = split_format(arguments); + let mut full: Vec = arguments.iter().map(|s| (*s).to_owned()).collect(); + if let Some(contents) = admin_file { + let path = directory.path().join("admin.url"); + std::fs::write(&path, contents).expect("admin file"); + full.push("--admin-url-file".to_owned()); + full.push(path.display().to_string()); + } + full.push("--runtime-config".to_owned()); + full.push("runtime.yaml".to_owned()); + let refs: Vec<&str> = full.iter().map(String::as_str).collect(); + let args = parse(&refs).expect("arguments parse"); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1.2.3-test", + &args, + format, + |_| input, + backend, + &mut stdout, + &mut stderr, + ); + Run { + exit, + stdout: String::from_utf8(stdout).expect("utf-8"), + stderr: String::from_utf8(stderr).expect("utf-8"), + } + } + + fn created_everything( + _: &AdminConfig, + plan: &Plan, + _: &ProvisionTarget, + ) -> Result { + Ok(Outcome { + statements: plan + .statements() + .iter() + .map(|statement| { + let outcome = if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }; + (statement.step, outcome) + }) + .collect(), + single_role: plan.single_role(), + }) + } + + fn must_not_run(_: &AdminConfig, _: &Plan, _: &ProvisionTarget) -> Result { + panic!("the backend must not run"); + } + + #[cfg(feature = "schema")] + #[test] + fn checked_in_schema_matches_the_owning_type() { + assert_eq!( + report_schema_document().expect("the report schema renders"), + include_str!("../schema/provision-report.schema.json"), + "regenerate with: cargo run --locked -p registry-platform-provision --features schema --example provision-report-schema -- --output crates/registry-platform-provision/schema/provision-report.schema.json" + ); + } + + // ---- flags ---- + + #[test] + fn posture_is_an_optional_unvalidated_flag() { + let unset = parse(&["--runtime-config", "r", "--print-sql"]).expect("arguments parse"); + assert_eq!(unset.posture, None); + for value in ["development", "production", "Production"] { + let args = parse(&["--runtime-config", "r", "--print-sql", "--posture", value]) + .expect("the shared posture crate validates the value, not clap"); + assert_eq!(args.posture.as_deref(), Some(value)); + } + } + + #[test] + fn print_sql_conflicts_with_both_admin_flags() { + for admin in [["--admin-url-file", "a"], ["--admin-url-env", "A"]] { + let error = parse(&["--runtime-config", "r", "--print-sql", admin[0], admin[1]]) + .expect_err("print conflicts with an admin flag"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + assert_eq!(error.exit_code(), 2); + } + } + + #[test] + fn the_two_admin_flags_conflict() { + let error = parse(&[ + "--runtime-config", + "r", + "--admin-url-file", + "a", + "--admin-url-env", + "A", + ]) + .expect_err("two sources conflict"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + } + + #[test] + fn executing_needs_exactly_one_admin_flag() { + let error = parse(&["--runtime-config", "r"]).expect_err("no administrator source"); + assert_eq!( + error.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + assert_eq!(error.exit_code(), 2); + assert!(parse(&["--runtime-config", "r", "--admin-url-file", "a"]).is_ok()); + assert!(parse(&["--runtime-config", "r", "--admin-url-env", "A"]).is_ok()); + assert!(parse(&["--runtime-config", "r", "--print-sql"]).is_ok()); + } + + /// A tool declares `--format human|json` globally and mounts the verb + /// beneath it. clap refuses a verb flag that reuses a global flag's name. + #[test] + fn the_verb_mounts_under_a_tool_with_a_global_format_flag() { + #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] + enum ToolFormat { + Human, + Json, + } + let tool = clap::Command::new("tool") + .arg( + clap::Arg::new("format") + .long("format") + .global(true) + .value_parser(clap::value_parser!(ToolFormat)) + .default_value("human"), + ) + .subcommand(::augment_args( + clap::Command::new("provision"), + )); + tool.clone().debug_assert(); + let matches = tool + .try_get_matches_from([ + "tool", + "provision", + "--runtime-config", + "r", + "--print-sql", + "--format", + "json", + ]) + .expect("the verb parses under the global format flag"); + let verb = matches.subcommand_matches("provision").expect("verb"); + assert_eq!( + verb.get_one::("format"), + Some(&ToolFormat::Json) + ); + } + + #[test] + fn the_verb_has_no_format_flag_of_its_own() { + let error = parse(&["--runtime-config", "r", "--print-sql", "--format", "json"]) + .expect_err("format belongs to the tool"); + assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument); + } + + #[test] + fn the_runtime_config_is_required() { + assert!(parse(&["--print-sql"]).is_err()); + assert!(parse(&["--runtime-config", "r", "--print-sql"]).is_ok()); + } + + // ---- print mode ---- + + #[test] + fn print_mode_writes_only_the_script_to_stdout() { + let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.stderr, ""); + assert!(run.stdout.starts_with("-- "), "{}", run.stdout); + assert!(run.stdout.contains("CREATE ROLE \"app_migration\"")); + assert!(run.stdout.contains("\\password \"app_migration\"")); + assert!(run.stdout.contains("\\password \"app_runtime\"")); + assert!(run.stdout.contains("\\connect \"app\"")); + for (label, secret) in [ + ("the migration password", MIGRATION_PASSWORD), + ("the runtime password", RUNTIME_PASSWORD), + ("a SCRAM verifier", "SCRAM-SHA-256$"), + ("a connection URL", "postgres://"), + ] { + assert!(!run.stdout.contains(secret), "the script holds {label}"); + } + assert!(!run.stdout.contains("PASSWORD '")); + } + + #[test] + fn print_mode_json_reports_every_statement_as_not_run() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["ok"], true); + assert_eq!(report["command"], "provision"); + assert_eq!(report["status"], "complete"); + assert_eq!(report["apiVersion"], REPORT_API_VERSION); + assert_eq!(report["kind"], REPORT_KIND); + assert_eq!(report["version"], "1.2.3-test"); + assert_eq!(report["product"], "casework"); + assert_eq!(report["executed"], false); + assert_eq!(report["roleMode"], "split"); + assert_eq!(report["database"], "app"); + assert_eq!(report["migrationRole"], "app_migration"); + assert_eq!(report["runtimeRole"], "app_runtime"); + assert_eq!(report["diagnostics"], serde_json::json!([])); + let statements = report["statements"].as_array().unwrap(); + assert!(statements.len() > 5); + for statement in statements { + assert_eq!(statement["outcome"], "not-run"); + assert!(statement["sql"].as_str().is_some_and(|sql| !sql.is_empty())); + } + assert_eq!(statements[0]["step"], "role.migration"); + assert_eq!(statements[0]["scope"], "server"); + assert_eq!(statements[0]["needs"], "createrole"); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!run.stdout.contains(secret)); + } + } + + #[test] + fn print_mode_marks_the_statement_that_needs_a_superuser() { + let product = ProductDatabase { + product: "breg", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: "app_bbox".to_owned(), + minimum_postgis: (3, 5), + }), + }; + let input = input_with( + &format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app_runtime:{RUNTIME_PASSWORD}@db.example/app"), + product, + ); + let text = execute_run(&["--print-sql"], None, Ok(input), &must_not_run); + assert_eq!(text.exit, 0); + assert!(text.stdout.contains("-- needs a superuser")); + } + + #[test] + fn print_mode_does_not_compare_against_an_administrator() { + let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); + assert_eq!(run.exit, 0); + } + + // ---- complete runs ---- + + #[test] + fn a_complete_run_reports_each_outcome() { + let admin = admin_url("db.example", 5432); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &created_everything, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["ok"], true); + assert_eq!(report["status"], "complete"); + assert_eq!(report["executed"], true); + assert_eq!(report["roleMode"], "split"); + let statements = report["statements"].as_array().unwrap(); + assert_eq!(statements[0]["outcome"], "created"); + assert!(statements.iter().any(|s| s["outcome"] == "applied")); + assert!(statements.iter().all(|s| s["outcome"] != "not-run")); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + ADMIN_PASSWORD, + "SCRAM-SHA-256$", + "postgres://", + ] { + assert!(!run.all_output().contains(secret)); + } + } + + #[test] + fn a_complete_text_run_lists_statements_roles_and_database() { + let admin = admin_url("db.example", 5432); + let run = execute_run(&[], Some(&admin), Ok(split_input()), &created_everything); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.stderr, ""); + assert!( + run.stdout.contains("created role.migration\n"), + "{}", + run.stdout + ); + assert!(run.stdout.contains("applied database.revoke-public\n")); + assert!(run.stdout.contains("database: app\n")); + assert!(run.stdout.contains("migration role: app_migration\n")); + assert!(run.stdout.contains("runtime role: app_runtime\n")); + assert!(!run.stdout.contains("single-role mode")); + } + + #[test] + fn single_role_mode_says_so() { + let input = input_with( + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + owned_product(), + ); + let admin = admin_url("db.example", 5432); + let run = execute_run(&[], Some(&admin), Ok(input), &created_everything); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert!(run + .stdout + .contains(registry_platform_activation::SINGLE_ROLE_STATEMENT)); + let input = input_with( + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + &format!("postgres://app:{MIGRATION_PASSWORD}@db.example/app"), + owned_product(), + ); + let json = execute_run( + &["--format", "json"], + Some(&admin), + Ok(input), + &created_everything, + ); + assert_eq!(json.json()["roleMode"], "single"); + } + + // ---- refusals from the executor ---- + + fn refusal_json(error: ProvisionError) -> (u8, Value) { + let admin = admin_url("db.example", 5432); + let backend = + move |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| Err(error.clone().into()); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.stderr, ""); + for secret in [ + MIGRATION_PASSWORD, + RUNTIME_PASSWORD, + ADMIN_PASSWORD, + "postgres://", + ] { + assert!(!run.stdout.contains(secret)); + } + let report = run.json(); + (run.exit, report) + } + + #[test] + fn each_executor_refusal_has_its_code_status_and_path() { + use ProvisionError as E; + let cases: Vec<(E, &str, &str, u8, Option<&str>)> = vec![ + ( + E::AdminConnectFailed { sqlstate: None }, + "platform.provision.admin-connect-failed", + "operational-failure", + 3, + None, + ), + ( + E::UnsupportedPostgres, + "platform.provision.unsupported-postgres", + "domain-refusal", + 1, + None, + ), + ( + E::StatementNeedsPrivilege { + step: "extension.postgis", + needs: Needs::Superuser, + scope: Scope::Database, + database: "app".to_owned(), + }, + "platform.provision.statement-needs-privilege", + "domain-refusal", + 1, + Some("extension.postgis"), + ), + ( + E::RoleAttributesDiffer { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-attributes-differ", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseOwnerDiffers { + database: "app".to_owned(), + }, + "platform.provision.database-owner-differs", + "domain-refusal", + 1, + Some("database.create"), + ), + ( + E::SchemaOwnerDiffers { + step: "schema.owned", + schema: "casework".to_owned(), + database: "app".to_owned(), + }, + "platform.provision.schema-owner-differs", + "domain-refusal", + 1, + Some("schema.owned"), + ), + ( + E::ExtensionTooOld { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + "platform.provision.extension-too-old", + "domain-refusal", + 1, + Some("extension.postgis"), + ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("28P01".to_owned()), + }, + "platform.provision.role-login-failed", + "domain-refusal", + 1, + None, + ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: None, + }, + "platform.provision.role-login-failed", + "operational-failure", + 3, + None, + ), + ( + E::RoleMembershipDiffers { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-membership-differs", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseIsTemplate { + database: "app".to_owned(), + }, + "platform.provision.database-is-template", + "domain-refusal", + 1, + Some("database.create"), + ), + ( + E::ExtensionIncomplete { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + "platform.provision.extension-incomplete", + "domain-refusal", + 1, + Some("extension.postgis"), + ), + ( + E::RoleSettingsDiffer { + step: "role.runtime", + role: "app_runtime".to_owned(), + }, + "platform.provision.role-settings-differ", + "domain-refusal", + 1, + Some("role.runtime"), + ), + ( + E::DatabaseConnectFailed { + database: "app".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + "platform.provision.database-connect-failed", + "operational-failure", + 3, + None, + ), + ( + E::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + "platform.provision.role-login-failed", + "operational-failure", + 3, + None, + ), + ( + E::EffectUnconfirmed { + step: "database.create", + }, + "platform.provision.effect-unconfirmed", + "operational-failure", + 3, + Some("database.create"), + ), + ( + E::StatementFailed { + step: "role.migration", + sqlstate: "23505".to_owned(), + }, + "platform.provision.statement-failed", + "operational-failure", + 3, + Some("role.migration"), + ), + ]; + for (error, code, status, exit, step) in cases { + let (actual_exit, report) = refusal_json(error); + assert_eq!(actual_exit, exit, "{code}"); + assert_eq!(report["ok"], false, "{code}"); + assert_eq!(report["status"], status, "{code}"); + let ran = !matches!( + code, + "platform.provision.admin-connect-failed" + | "platform.provision.unsupported-postgres" + ); + assert_eq!(report["executed"], ran, "{code}"); + let diagnostics = report["diagnostics"].as_array().unwrap(); + assert_eq!(diagnostics.len(), 1, "{code}"); + let diagnostic = &diagnostics[0]; + assert_eq!(diagnostic["severity"], "error"); + assert_eq!(diagnostic["code"], code); + assert_eq!(diagnostic["path"], step.unwrap_or(""), "{code}"); + assert!(!diagnostic["message"].as_str().unwrap().is_empty()); + assert!(!diagnostic["suggestedAction"].as_str().unwrap().is_empty()); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{code}"); + } + } + } + + #[test] + fn a_failure_part_way_reports_what_ran_before_it() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + let reached = plan + .statements() + .iter() + .take(3) + .map(|statement| { + let outcome = if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }; + (statement.step, outcome) + }) + .collect(); + Err(Failure { + error: ProvisionError::StatementNeedsPrivilege { + step: "database.revoke-public", + needs: Needs::DatabaseOwner, + scope: Scope::Server, + database: "app".to_owned(), + }, + reached, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["executed"], true); + let outcomes: Vec<&str> = report["statements"] + .as_array() + .unwrap() + .iter() + .map(|statement| statement["outcome"].as_str().unwrap()) + .collect(); + assert_eq!(&outcomes[..3], ["created", "created", "created"]); + assert!(outcomes[3..].iter().all(|outcome| *outcome == "not-run")); + } + + #[test] + fn a_login_check_failure_keeps_the_outcomes_of_the_run_that_preceded_it() { + let admin = admin_url("db.example", 5432); + let backend = |admin: &AdminConfig, plan: &Plan, target: &ProvisionTarget| { + let outcome = created_everything(admin, plan, target)?; + Err(Failure { + error: ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("28P01".to_owned()), + }, + reached: outcome.statements, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["executed"], true); + assert!(report["statements"] + .as_array() + .unwrap() + .iter() + .all(|statement| statement["outcome"] != "not-run")); + } + + #[test] + fn a_login_refusal_blames_the_password_only_for_a_password_failure() { + let action_for = |sqlstate: Option<&str>| { + let (_, report) = refusal_json(ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: sqlstate.map(str::to_owned), + }); + report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap() + .to_owned() + }; + assert!(action_for(Some("28P01")).contains("different password")); + for other in [Some("28000"), Some("53300"), None] { + assert!( + !action_for(other).contains("different password"), + "{other:?}" + ); + } + assert!(action_for(Some("28000")).contains("pg_hba.conf")); + } + + #[test] + fn a_connect_failure_in_the_new_database_reports_what_ran_and_names_the_database() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + let reached = plan + .statements() + .iter() + .take(3) + .map(|statement| (statement.step, StatementOutcome::Created)) + .collect(); + Err(Failure { + error: ProvisionError::DatabaseConnectFailed { + database: "app".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + reached, + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.exit, 3, "{}", run.all_output()); + let report = run.json(); + assert_eq!(report["executed"], true); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["code"], + "platform.provision.database-connect-failed" + ); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!( + action.contains("CONNECTION LIMIT") && action.contains("pg_hba.conf"), + "{action}" + ); + assert!( + !action.contains("administrator URL"), + "the URL was proved right: {action}" + ); + assert_eq!(report["statements"][0]["outcome"], "created"); + } + + #[test] + fn statements_that_ran_mean_executed_whatever_the_error() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + Err(Failure { + error: ProvisionError::AdminConnectFailed { sqlstate: None }, + reached: vec![(plan.statements()[0].step, StatementOutcome::Created)], + }) + }; + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &backend, + ); + assert_eq!(run.json()["executed"], true); + } + + #[test] + fn a_text_refusal_lists_the_statements_that_ran_before_it() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, plan: &Plan, _: &ProvisionTarget| { + Err(Failure { + error: ProvisionError::StatementFailed { + step: "database.create", + sqlstate: "42501".to_owned(), + }, + reached: plan + .statements() + .iter() + .take(2) + .map(|statement| (statement.step, StatementOutcome::Created)) + .collect(), + }) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert_eq!(run.exit, 3); + assert_eq!(run.stdout, ""); + let ran = run + .stderr + .find("created role.migration\ncreated role.runtime\n") + .unwrap_or_else(|| panic!("{}", run.stderr)); + let refusal = run + .stderr + .find("error[platform.provision.statement-failed]") + .unwrap_or_else(|| panic!("{}", run.stderr)); + assert!(ran < refusal, "{}", run.stderr); + assert!(!run.stderr.contains("not-run"), "{}", run.stderr); + } + + #[test] + fn a_refusal_before_any_statement_lists_no_statements() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::UnsupportedPostgres.into()) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert!(!run.stderr.contains("created"), "{}", run.stderr); + assert!(run.stderr.starts_with("error["), "{}", run.stderr); + } + + #[test] + fn a_login_refusal_for_a_connection_limit_is_operational() { + let (exit, report) = refusal_json(ProvisionError::RoleLoginFailed { + role: "app_runtime".to_owned(), + sqlstate: Some("53300".to_owned()), + }); + assert_eq!(exit, 3); + let action = report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap(); + assert!(action.contains("CONNECTION LIMIT"), "{action}"); + } + + #[test] + fn a_missing_administrator_database_gets_its_own_action() { + let (exit, report) = refusal_json(ProvisionError::AdminConnectFailed { + sqlstate: Some("3D000".to_owned()), + }); + assert_eq!(exit, 3); + let action = report["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap(); + assert!(action.contains("does not exist"), "{action}"); + assert!(!action.contains("host, port"), "{action}"); + } + + #[test] + fn the_privilege_refusal_names_the_statement_and_offers_print_mode() { + let (_, report) = refusal_json(ProvisionError::StatementNeedsPrivilege { + step: "extension.postgis", + needs: Needs::Superuser, + scope: Scope::Database, + database: "app".to_owned(), + }); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["message"], + "the administrator role cannot run CREATE EXTENSION postgis in database \"app\"; it needs a superuser" + ); + assert_eq!( + diagnostic["suggestedAction"], + "run this statement as a role that has it, or run \"casectl provision --print-sql\" \ + and give the script to the database administrator, then run provision again" + ); + } + + #[test] + fn a_text_refusal_goes_to_stderr_and_stdout_stays_empty() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::UnsupportedPostgres.into()) + }; + let run = execute_run(&[], Some(&admin), Ok(split_input()), &backend); + assert_eq!(run.exit, 1); + assert_eq!(run.stdout, ""); + assert!(run + .stderr + .contains("error[platform.provision.unsupported-postgres]")); + } + + // ---- refusals before any statement ---- + + fn first_diagnostic(run: &Run) -> Value { + run.json()["diagnostics"][0].clone() + } + + #[test] + fn a_bad_administrator_url_is_a_usage_error_that_names_the_rule() { + let run = execute_run( + &["--format", "json"], + Some(&format!( + "http://admin:{ADMIN_PASSWORD}@db.example/postgres" + )), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2); + let report = run.json(); + assert_eq!(report["status"], "usage-error"); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid" + ); + assert!(!run.stdout.contains(ADMIN_PASSWORD)); + assert!(!run.stdout.contains("http://")); + } + + #[test] + fn plaintext_and_weak_sslmode_in_the_administrator_url_are_refused() { + let run = execute_run( + &["--format", "json"], + Some(&format!( + "postgres://admin:{ADMIN_PASSWORD}@db.example/postgres?sslmode=disable" + )), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid" + ); + } + + #[test] + fn an_unreadable_administrator_file_is_an_admin_url_refusal() { + let args = parse(&[ + "--runtime-config", + "r", + "--admin-url-file", + "/nonexistent-provision-admin-url", + ]) + .unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + assert!(!String::from_utf8(stdout).unwrap().contains("nonexistent")); + } + + #[cfg(unix)] + #[test] + fn an_administrator_file_that_is_a_named_pipe_is_refused_without_opening_it() { + let directory = tempfile::tempdir().expect("scratch directory"); + let pipe = directory.path().join("admin.url"); + let made = std::process::Command::new("mkfifo") + .arg(&pipe) + .status() + .expect("mkfifo runs"); + assert!(made.success()); + let pipe = pipe.display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", &pipe]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + } + + #[test] + fn an_unset_administrator_variable_is_an_admin_url_refusal_that_names_the_variable() { + let args = parse(&[ + "--runtime-config", + "r", + "--admin-url-env", + "PROVISION_TEST_UNSET_ADMIN_URL", + ]) + .unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "platform.provision.admin-url-invalid"); + assert!(diagnostic["message"] + .as_str() + .unwrap() + .contains("PROVISION_TEST_UNSET_ADMIN_URL")); + } + + #[test] + fn an_invalid_ca_bundle_is_refused_with_the_ca_code() { + let mut input = split_input(); + input.ca_pem = Some(b"not a certificate".to_vec()); + let run = execute_run( + &["--format", "json"], + Some(&admin_url("db.example", 5432)), + Ok(input), + &must_not_run, + ); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-ca-invalid" + ); + assert_eq!(run.exit, 1); + assert_eq!(run.json()["status"], "domain-refusal"); + } + + #[test] + fn product_urls_naming_different_targets_are_a_mismatch() { + let variants = [ + ( + "postgres://m:pw1@db-a.example/app", + "postgres://r:pw2@db-b.example/app", + "host", + ), + ( + "postgres://m:pw1@db.example:5432/app", + "postgres://r:pw2@db.example:5433/app", + "port", + ), + ( + "postgres://m:pw1@db.example/app", + "postgres://r:pw2@db.example/other", + "database", + ), + ]; + for (migration, runtime, what) in variants { + let run = execute_run( + &["--format", "json"], + Some(&admin_url("db.example", 5432)), + Ok(input_with(migration, runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 1, "{what}"); + let diagnostic = first_diagnostic(&run); + assert_eq!( + diagnostic["code"], "platform.provision.target-mismatch", + "{what}" + ); + assert!(diagnostic["message"].as_str().unwrap().contains(what)); + assert!( + !run.stdout.contains("db-a.example"), + "no host values: {what}" + ); + } + } + + #[test] + fn a_mismatch_between_the_product_urls_is_refused_in_print_mode_too() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + "postgres://m:pw1@db.example/app", + "postgres://r:pw2@db.example/other", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 1); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-mismatch" + ); + } + + #[test] + fn an_administrator_on_another_host_or_port_is_a_mismatch() { + for (host, port, what) in [ + ("other.example", 5432, "host"), + ("db.example", 6543, "port"), + ] { + let run = execute_run( + &["--format", "json"], + Some(&admin_url(host, port)), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 1, "{what}"); + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-mismatch"); + assert!(diagnostic["message"] + .as_str() + .unwrap() + .contains("administrator")); + assert!(diagnostic["message"].as_str().unwrap().contains(what)); + } + } + + #[test] + fn the_host_comparison_ignores_case() { + let run = execute_run( + &["--format", "json"], + Some(&admin_url("DB.Example", 5432)), + Ok(split_input()), + &created_everything, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + } + + #[test] + fn a_product_url_that_cannot_name_a_target_is_refused_without_echoing_it() { + let cases = [ + "not a url at all, pw", + "mysql://m:pw@db.example/app", + "postgres://m@db.example/app", + "postgres://m:pw@db.example", + "postgres://m:pw@db.example/app?host=other.example", + ]; + for bad in cases { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + bad, + "postgres://r:pw2@db.example/app", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{bad}"); + assert_eq!(run.json()["status"], "usage-error"); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains("other.example"), "{bad}"); + assert!(!run.stdout.contains(bad), "{bad}"); + } + } + + #[test] + fn one_role_name_with_two_passwords_is_refused() { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with( + "postgres://app:pw1@db.example/app", + "postgres://app:pw2@db.example/app", + owned_product(), + )), + &must_not_run, + ); + assert_eq!(run.exit, 2); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains("pw1") && !run.stdout.contains("pw2")); + } + + #[test] + fn a_percent_encoded_role_name_and_password_are_decoded() { + let input = input_with( + "postgres://app%5Fmigration:p%40ss@db.example/app", + "postgres://app%5Fruntime:p%40ss2@db.example/app", + owned_product(), + ); + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input), + &must_not_run, + ); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert_eq!(run.json()["migrationRole"], "app_migration"); + } + + #[test] + fn the_loader_diagnostic_is_reported_as_given() { + let diagnostic = Diagnostic::error( + "platform.runtime-config.unsafe-file", + "", + "the runtime file is unsafe", + "Fix the file.", + ); + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Err(Box::new(diagnostic)), + &must_not_run, + ); + assert_eq!(run.exit, 1); + let report = run.json(); + assert_eq!(report["status"], "domain-refusal"); + assert_eq!(report["executed"], false); + assert_eq!(report["statements"], serde_json::json!([])); + assert!(report.get("product").is_none()); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.runtime-config.unsafe-file" + ); + } + + #[test] + fn a_control_character_in_a_role_name_is_refused_in_print_mode_with_no_script() { + let migration = format!("postgres://app_migration:{MIGRATION_PASSWORD}@db.example/app"); + let runtime = + format!("postgres://app_runtime%0A%5C!%20id:{RUNTIME_PASSWORD}@db.example/app"); + for format in [["--format", "human"], ["--format", "json"]] { + let mut arguments = vec!["--print-sql"]; + arguments.extend(format); + let run = execute_run( + &arguments, + None, + Ok(input_with(&migration, &runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{}", run.all_output()); + let output = run.all_output(); + for script in [ + "CREATE ROLE", + "\\password", + "\\connect", + "\\!", + "-- provision script", + ] { + assert!(!output.contains(script), "{format:?}: {output}"); + } + assert!(!output.contains(RUNTIME_PASSWORD), "{output}"); + if format[1] == "json" { + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-invalid"); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!( + action.contains("user") && action.contains("runtime"), + "{action}" + ); + assert!(!action.contains("\\!"), "{action}"); + assert!(run.json().get("runtimeRole").is_none()); + } else { + assert!( + output.contains("platform.provision.target-invalid"), + "{output}" + ); + } + } + } + + #[test] + fn each_refused_url_member_is_named_in_the_action_and_never_quoted() { + let cases = [ + ( + "postgres://app_migration%0A:pw1@db.example/app", + "postgres://app_runtime:pw2@db.example/app", + "migration URL", + ), + ( + "postgres://app_migration:pw1@db.example/app%0Ax", + "postgres://app_runtime:pw2@db.example/app%0Ax", + "database name", + ), + ( + "postgres://app_migration:pw1@db.example/host%3Dattacker", + "postgres://app_runtime:pw2@db.example/host%3Dattacker", + "database name", + ), + ]; + for (migration, runtime, member) in cases { + let run = execute_run( + &["--print-sql", "--format", "json"], + None, + Ok(input_with(migration, runtime, owned_product())), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{migration}"); + let diagnostic = first_diagnostic(&run); + assert_eq!(diagnostic["code"], "platform.provision.target-invalid"); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!(action.contains(member), "{member}: {action}"); + assert!(!run.stdout.contains("attacker"), "{}", run.stdout); + } + } + + #[test] + fn the_administrators_own_database_cannot_be_the_product_database() { + let admin = + format!("postgres://admin:{ADMIN_PASSWORD}@db.example:5432/app?sslmode=verify-full"); + let run = execute_run( + &["--format", "json"], + Some(&admin), + Ok(split_input()), + &must_not_run, + ); + assert_eq!(run.exit, 2, "{}", run.all_output()); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.target-invalid" + ); + assert!(!run.stdout.contains(ADMIN_PASSWORD)); + } + + fn admin_file_run(contents: &[u8]) -> Run { + let directory = tempfile::tempdir().expect("scratch directory"); + let path = directory.path().join("admin.url"); + std::fs::write(&path, contents).expect("admin file"); + let path = path.display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", path.as_str()]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + Run { + exit, + stdout: String::from_utf8(stdout).expect("utf-8"), + stderr: String::from_utf8(stderr).expect("utf-8"), + } + } + + #[test] + fn an_unusable_administrator_file_is_a_usage_error() { + let oversized = vec![b'a'; 9000]; + let cases: [(&str, &[u8]); 4] = [ + ("larger than 8 KiB", &oversized), + ("empty", b""), + ("whitespace only", b" \n\t\n"), + ("not UTF-8", &[0xff, 0xfe, 0xfd]), + ]; + for (what, contents) in cases { + let run = admin_file_run(contents); + assert_eq!(run.exit, 2, "{what}: {}", run.all_output()); + assert_eq!( + first_diagnostic(&run)["code"], + "platform.provision.admin-url-invalid", + "{what}" + ); + } + } + + #[test] + fn an_administrator_path_that_is_not_a_regular_file_is_a_usage_error() { + let directory = tempfile::tempdir().expect("scratch directory"); + let path = directory.path().display().to_string(); + let args = parse(&["--runtime-config", "r", "--admin-url-file", path.as_str()]).unwrap(); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1", + &args, + OutputFormat::Json, + |_| Ok(split_input()), + &must_not_run, + &mut stdout, + &mut stderr, + ); + assert_eq!(exit, 2); + let report: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "platform.provision.admin-url-invalid" + ); + } + + #[test] + fn no_output_ever_holds_a_password_verifier_or_url() { + let admin = admin_url("db.example", 5432); + let backend = |_: &AdminConfig, _: &Plan, _: &ProvisionTarget| { + Err(ProvisionError::StatementFailed { + step: "role.migration", + sqlstate: "42710".to_owned(), + } + .into()) + }; + for format in [["--format", "human"], ["--format", "json"]] { + let run = execute_run(&format, Some(&admin), Ok(split_input()), &backend); + let output = run.all_output(); + for (label, secret) in [ + ("the migration password", MIGRATION_PASSWORD), + ("the runtime password", RUNTIME_PASSWORD), + ("the administrator password", ADMIN_PASSWORD), + ("a SCRAM verifier", "SCRAM-SHA-256$"), + ("a connection URL", "postgres://"), + ] { + assert!(!output.contains(secret), "{format:?} output holds {label}"); + } + } + } +} + +/// Runs the command against the disposable server named by +/// `PROVISION_TEST_DATABASE_URL` (a superuser, over TLS) and its CA file in +/// `PROVISION_TEST_DATABASE_CA`. A missing variable fails the test. +#[cfg(all(test, feature = "postgres-test"))] +mod postgres_tests { + use super::*; + use crate::SchemaLayout; + use serde_json::Value; + + fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) + } + + fn random_hex(bytes: usize) -> String { + let mut buffer = vec![0_u8; bytes]; + getrandom::fill(&mut buffer).expect("random bytes"); + buffer.iter().map(|byte| format!("{byte:02x}")).collect() + } + + /// Drops what the test created, even when an assertion failed. + struct Cleanup { + admin: AdminConfig, + database: String, + roles: Vec, + } + + impl Drop for Cleanup { + fn drop(&mut self) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("cleanup runtime"); + runtime.block_on(async { + let session = self.admin.connect(None).await.expect("cleanup session"); + session + .client + .batch_execute(&format!( + "DROP DATABASE IF EXISTS \"{}\" WITH (FORCE)", + self.database + )) + .await + .expect("drop database"); + for role in &self.roles { + session + .client + .batch_execute(&format!("DROP ROLE IF EXISTS \"{role}\"")) + .await + .expect("drop role"); + } + }); + } + } + + fn run_command( + arguments: &[&str], + admin_file: &Path, + input: ProvisionInput, + backend: Backend<'_>, + ) -> (u8, String, String) { + let admin_file = admin_file.display().to_string(); + let mut full = vec![ + "--runtime-config", + "runtime.yaml", + "--admin-url-file", + admin_file.as_str(), + ]; + let (arguments, format) = tests::split_format(arguments); + full.extend_from_slice(&arguments); + let args = { + use clap::Parser; + #[derive(Parser)] + struct Harness { + #[command(flatten)] + args: ProvisionArgs, + } + Harness::try_parse_from(std::iter::once("tool").chain(full)) + .expect("arguments parse") + .args + }; + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let exit = run_with( + "casectl", + "1.2.3-test", + &args, + format, + |_| Ok(input), + backend, + &mut stdout, + &mut stderr, + ); + ( + exit, + String::from_utf8(stdout).expect("utf-8"), + String::from_utf8(stderr).expect("utf-8"), + ) + } + + #[test] + fn provision_converges_a_real_server_and_refuses_a_changed_password() { + let admin_url = required("PROVISION_TEST_DATABASE_URL"); + let ca = std::fs::read(required("PROVISION_TEST_DATABASE_CA")).expect("CA file"); + let endpoint = parse_endpoint(&admin_url).expect("administrator URL"); + let suffix = random_hex(6); + let (database, migration, runtime_role) = ( + format!("s3_{suffix}_db"), + format!("s3_{suffix}_mig"), + format!("s3_{suffix}_run"), + ); + let (migration_password, runtime_password) = (random_hex(16), random_hex(16)); + let (host, port) = (endpoint.host.as_str(), endpoint.port); + let input = |runtime_password: &str| ProvisionInput { + product: ProductDatabase { + product: "casework", + layout: SchemaLayout::Owned(vec!["casework".to_owned()]), + btree_gist: true, + spatial: None, + }, + migration_url: Zeroizing::new(format!( + "postgres://{migration}:{migration_password}@{host}:{port}/{database}" + )), + runtime_url: Zeroizing::new(format!( + "postgres://{runtime_role}:{runtime_password}@{host}:{port}/{database}" + )), + ca_pem: Some(ca.clone()), + }; + let _cleanup = Cleanup { + admin: admin_config(&admin_url, Some(&ca)).expect("administrator config"), + database: database.clone(), + roles: vec![migration.clone(), runtime_role.clone()], + }; + let directory = tempfile::tempdir().expect("scratch directory"); + let admin_file = directory.path().join("admin.url"); + std::fs::write(&admin_file, &admin_url).expect("admin file"); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let backend = server_backend(&runtime); + + let (exit, stdout, stderr) = run_command( + &["--format", "json"], + &admin_file, + input(&runtime_password), + &backend, + ); + assert_eq!(exit, 0, "{stdout}{stderr}"); + let first: Value = serde_json::from_str(&stdout).expect("JSON report"); + let outcome = |report: &Value, step: &str| { + report["statements"] + .as_array() + .expect("statements") + .iter() + .find(|statement| statement["step"] == step) + .map(|statement| statement["outcome"].clone()) + }; + assert_eq!(outcome(&first, "role.migration"), Some("created".into())); + assert_eq!(outcome(&first, "database.create"), Some("created".into())); + assert_eq!(outcome(&first, "schema.owned"), Some("created".into())); + assert_eq!(first["executed"], true); + + let (exit, stdout, stderr) = run_command( + &["--format", "json"], + &admin_file, + input(&runtime_password), + &backend, + ); + assert_eq!(exit, 0, "{stdout}{stderr}"); + let second: Value = serde_json::from_str(&stdout).expect("JSON report"); + assert_eq!(outcome(&second, "role.migration"), Some("present".into())); + assert_eq!(outcome(&second, "database.create"), Some("present".into())); + assert_eq!(outcome(&second, "schema.owned"), Some("present".into())); + for secret in [ + migration_password.as_str(), + runtime_password.as_str(), + "postgres://", + ] { + assert!(!stdout.contains(secret), "the report leaked a secret"); + } + + let (exit, stdout, _) = run_command( + &["--format", "json"], + &admin_file, + input(&random_hex(16)), + &backend, + ); + assert_eq!(exit, 1, "{stdout}"); + let refused: Value = serde_json::from_str(&stdout).expect("JSON report"); + assert_eq!( + refused["diagnostics"][0]["code"], + "platform.provision.role-login-failed" + ); + + let (exit, stdout, stderr) = + run_command(&[], &admin_file, input(&runtime_password), &backend); + assert_eq!(exit, 0, "{stdout}{stderr}"); + assert!(stdout.contains("present role.migration\n"), "{stdout}"); + } +} diff --git a/crates/registry-platform-provision/src/execute.rs b/crates/registry-platform-provision/src/execute.rs new file mode 100644 index 0000000000..c3bd444210 --- /dev/null +++ b/crates/registry-platform-provision/src/execute.rs @@ -0,0 +1,781 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs a [`Plan`] against a server as an administrator. +//! +//! Every statement runs on its own, so a refusal names exactly one step. No +//! error carries statement text, a URL, a password, a verifier or a driver +//! message: errors name the step, the object and the SQLSTATE. + +use std::fmt; + +use crate::{ + admin::{bounded_call, AdminConfig, CallFailure, ConnectFailure, Session}, + plan::{verify_server_version, Needs, Plan, Probe, ProvisionTarget, Scope, Statement}, +}; + +/// How [`execute`] treats objects that already exist. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// Probe the catalog first, create only what is absent, and refuse what + /// exists in a different shape. Every `*ctl provision` uses this. + Converge, + /// The server is known to be empty: no floor check and no probes. Only + /// the products' test helpers and the PostgreSQL suite use it. + #[cfg(any(feature = "test-support", feature = "postgres-test"))] + Fresh, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StatementOutcome { + /// The statement ran and its object did not exist before. + Created, + /// The object already existed in the expected shape, so nothing ran. + Present, + /// A grant, revoke or connection setting ran. It is a no-op when it + /// already held. + Applied, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Outcome { + /// One entry per planned statement, in plan order. + pub statements: Vec<(&'static str, StatementOutcome)>, + pub single_role: bool, +} + +/// Why provisioning stopped. `code` is the diagnostic code of the report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProvisionError { + AdminConnectFailed { + sqlstate: Option, + }, + /// The administrator opened a session on the server, then could not open + /// one in the database the plan provisions, so the server-scope + /// statements before it ran. + DatabaseConnectFailed { + database: String, + sqlstate: Option, + }, + UnsupportedPostgres, + StatementNeedsPrivilege { + step: &'static str, + needs: Needs, + scope: Scope, + database: String, + }, + RoleAttributesDiffer { + step: &'static str, + role: String, + }, + /// An existing product role carries a setting that redirects its sessions: + /// a `role`, `search_path` or `session_authorization` default, for every + /// database or for the provisioned one. + RoleSettingsDiffer { + step: &'static str, + role: String, + }, + /// An existing product role is a member of a role the plan did not grant it. + RoleMembershipDiffers { + step: &'static str, + role: String, + }, + DatabaseOwnerDiffers { + database: String, + }, + DatabaseIsTemplate { + database: String, + }, + SchemaOwnerDiffers { + step: &'static str, + schema: String, + database: String, + }, + ExtensionTooOld { + step: &'static str, + extension: String, + }, + /// The extension exists, but not in the schema or with the role + /// membership its statement block sets up. + ExtensionIncomplete { + step: &'static str, + extension: String, + }, + /// `sqlstate` is the server's answer, `None` when none came (a timeout or + /// a lost connection). + RoleLoginFailed { + role: String, + sqlstate: Option, + }, + EffectUnconfirmed { + step: &'static str, + }, + StatementFailed { + step: &'static str, + sqlstate: String, + }, +} + +impl ProvisionError { + pub fn code(&self) -> &'static str { + match self { + Self::AdminConnectFailed { .. } => "platform.provision.admin-connect-failed", + Self::DatabaseConnectFailed { .. } => "platform.provision.database-connect-failed", + Self::UnsupportedPostgres => "platform.provision.unsupported-postgres", + Self::StatementNeedsPrivilege { .. } => "platform.provision.statement-needs-privilege", + Self::RoleAttributesDiffer { .. } => "platform.provision.role-attributes-differ", + Self::RoleSettingsDiffer { .. } => "platform.provision.role-settings-differ", + Self::RoleMembershipDiffers { .. } => "platform.provision.role-membership-differs", + Self::DatabaseOwnerDiffers { .. } => "platform.provision.database-owner-differs", + Self::DatabaseIsTemplate { .. } => "platform.provision.database-is-template", + Self::SchemaOwnerDiffers { .. } => "platform.provision.schema-owner-differs", + Self::ExtensionTooOld { .. } => "platform.provision.extension-too-old", + Self::ExtensionIncomplete { .. } => "platform.provision.extension-incomplete", + Self::RoleLoginFailed { .. } => "platform.provision.role-login-failed", + Self::EffectUnconfirmed { .. } => "platform.provision.effect-unconfirmed", + Self::StatementFailed { .. } => "platform.provision.statement-failed", + } + } + + /// Whether any statement could have been sent before this error. + pub fn may_have_run_statements(&self) -> bool { + !matches!( + self, + Self::AdminConnectFailed { .. } | Self::UnsupportedPostgres + ) + } + + /// The step of the plan the error belongs to, the report's `path`. + pub fn step(&self) -> Option<&'static str> { + match self { + Self::StatementNeedsPrivilege { step, .. } + | Self::RoleAttributesDiffer { step, .. } + | Self::RoleSettingsDiffer { step, .. } + | Self::RoleMembershipDiffers { step, .. } + | Self::SchemaOwnerDiffers { step, .. } + | Self::ExtensionTooOld { step, .. } + | Self::ExtensionIncomplete { step, .. } + | Self::EffectUnconfirmed { step } + | Self::StatementFailed { step, .. } => Some(step), + Self::DatabaseOwnerDiffers { .. } | Self::DatabaseIsTemplate { .. } => { + Some("database.create") + } + Self::AdminConnectFailed { .. } + | Self::DatabaseConnectFailed { .. } + | Self::UnsupportedPostgres + | Self::RoleLoginFailed { .. } => None, + } + } +} + +fn statement_kind(step: &str) -> &str { + match step { + "role.migration" | "role.runtime" | "role.spatial-bbox" => "CREATE ROLE", + "database.create" => "CREATE DATABASE", + "database.revoke-public" => "REVOKE on the database", + "database.grant-connect" => "GRANT CONNECT on the database", + "database.grant-create" => "GRANT CREATE on the database", + "database.allow-connections" => "ALTER DATABASE", + "extension.btree-gist" => "CREATE EXTENSION btree_gist", + "extension.postgis" => "CREATE EXTENSION postgis", + "schema.owned" => "CREATE SCHEMA", + "schema.public" => "GRANT on schema public", + other => other, + } +} + +fn needed(needs: Needs) -> &'static str { + match needs { + Needs::CreateRole => "CREATEROLE", + Needs::CreateDb => "CREATEDB", + Needs::DatabaseOwner => "ownership of the database", + Needs::Superuser => "a superuser", + } +} + +impl fmt::Display for ProvisionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AdminConnectFailed { sqlstate: None } => { + f.write_str("cannot open a session with the administrator URL") + } + Self::AdminConnectFailed { + sqlstate: Some(sqlstate), + } => write!( + f, + "cannot open a session with the administrator URL (SQLSTATE {sqlstate})" + ), + Self::DatabaseConnectFailed { database, sqlstate } => { + write!( + f, + "the administrator role cannot open a session in database \"{database}\"" + )?; + match sqlstate { + Some(sqlstate) => write!(f, " (SQLSTATE {sqlstate})"), + None => Ok(()), + } + } + Self::UnsupportedPostgres => fmt::Display::fmt(&crate::plan::UnsupportedPostgres, f), + Self::StatementNeedsPrivilege { + step, + needs, + scope, + database, + } => { + let place = match scope { + Scope::Server => "the server".to_owned(), + Scope::Database => format!("database \"{database}\""), + }; + write!( + f, + "the administrator role cannot run {} in {place}; it needs {}", + statement_kind(step), + needed(*needs) + ) + } + Self::RoleAttributesDiffer { role, .. } => write!( + f, + "the role \"{role}\" already exists with attributes other than provisioning \ + creates it with. It is not altered: use another name or correct the role as \ + an administrator" + ), + Self::RoleSettingsDiffer { role, .. } => write!( + f, + "the role \"{role}\" already exists with a default for role, search_path or \ + session_authorization. It is not altered: use another name or reset the \ + setting as an administrator" + ), + Self::RoleMembershipDiffers { role, .. } => write!( + f, + "the role \"{role}\" already exists and is a member of a role provisioning did \ + not grant it. It is not altered: use another name or revoke the membership as \ + an administrator" + ), + Self::DatabaseIsTemplate { database } => write!( + f, + "the database \"{database}\" is a template database and is not adopted" + ), + Self::DatabaseOwnerDiffers { database } => write!( + f, + "the database \"{database}\" already exists under an owner the administrator \ + role cannot act as" + ), + Self::SchemaOwnerDiffers { + schema, database, .. + } => write!( + f, + "the schema \"{schema}\" in database \"{database}\" already exists under a role \ + other than the migration role" + ), + Self::ExtensionTooOld { extension, .. } => write!( + f, + "the extension \"{extension}\" is installed below the version this product needs" + ), + Self::ExtensionIncomplete { extension, .. } => write!( + f, + "the extension \"{extension}\" exists outside the schema or without the role \ + membership its prerequisites set up" + ), + Self::RoleLoginFailed { + role, + sqlstate: None, + } => write!( + f, + "the role \"{role}\" cannot open a session with its configured credential" + ), + Self::RoleLoginFailed { + role, + sqlstate: Some(sqlstate), + } => write!( + f, + "the role \"{role}\" cannot open a session with its configured credential \ + (SQLSTATE {sqlstate})" + ), + Self::EffectUnconfirmed { step } => write!( + f, + "the outcome of step {step} is unknown after a timeout or a lost connection; \ + run provision again" + ), + Self::StatementFailed { step, sqlstate } => { + write!(f, "step {step} failed on the server (SQLSTATE {sqlstate})") + } + } + } +} + +impl std::error::Error for ProvisionError {} + +fn connect_failed(failure: ConnectFailure) -> ProvisionError { + ProvisionError::AdminConnectFailed { + sqlstate: failure.sqlstate, + } +} + +/// A row that did not have the shape the query selects: not a server error, +/// reported as the internal-error SQLSTATE. +fn unreadable(step: &'static str) -> ProvisionError { + ProvisionError::StatementFailed { + step, + sqlstate: "XX000".to_owned(), + } +} + +fn call_error(step: &'static str, failure: CallFailure) -> ProvisionError { + match failure { + CallFailure::Unconfirmed => ProvisionError::EffectUnconfirmed { step }, + CallFailure::Server { sqlstate } => ProvisionError::StatementFailed { step, sqlstate }, + } +} + +/// Why a run stopped, with the statements that had already run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Failure { + pub error: ProvisionError, + /// The outcome of each statement before the one that failed, in plan order. + pub reached: Vec<(&'static str, StatementOutcome)>, +} + +impl From for Failure { + fn from(error: ProvisionError) -> Self { + Self { + error, + reached: Vec::new(), + } + } +} + +/// Runs every statement of `plan` as the administrator `admin`. +/// +/// In [`Mode::Converge`] the server version is checked against the shared +/// floor before the first statement. A statement with a probe runs only when +/// its object is absent, and a statement without one is re-applied. An +/// existing object in another shape is refused and never altered. +pub async fn execute( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, +) -> Result { + execute_recording(admin, plan, mode) + .await + .map_err(|failure| failure.error) +} + +/// [`execute`] that keeps the outcomes of the statements that ran before a +/// failure, so a report can say what changed on the server. +pub async fn execute_recording( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, +) -> Result { + let mut statements = Vec::with_capacity(plan.statements().len()); + match run_plan(admin, plan, mode, &mut statements).await { + Ok(()) => Ok(Outcome { + statements, + single_role: plan.single_role(), + }), + Err(error) => Err(Failure { + error, + reached: statements, + }), + } +} + +async fn run_plan( + admin: &AdminConfig, + plan: &Plan, + mode: Mode, + statements: &mut Vec<(&'static str, StatementOutcome)>, +) -> Result<(), ProvisionError> { + let server = admin.connect(None).await.map_err(connect_failed)?; + if mode == Mode::Converge { + verify_floor(&server).await?; + } + let mut database: Option = None; + for statement in plan.statements() { + let session = match statement.scope { + Scope::Server => &server, + Scope::Database => match &mut database { + Some(session) => session, + empty => empty.insert(admin.connect(Some(plan.database())).await.map_err( + |failure| ProvisionError::DatabaseConnectFailed { + database: plan.database().to_owned(), + sqlstate: failure.sqlstate, + }, + )?), + }, + }; + let outcome = run_statement(session, plan, statement, mode).await?; + statements.push((statement.step, outcome)); + } + Ok(()) +} + +async fn verify_floor(server: &Session) -> Result<(), ProvisionError> { + const STEP: &str = "server.version"; + let row = bounded_call(server.client.query_one( + "SELECT pg_catalog.current_setting('server_version_num')::int4", + &[], + )) + .await + .map_err(|failure| call_error(STEP, failure))?; + let version: i32 = row.try_get(0).map_err(|_| unreadable(STEP))?; + verify_server_version(version).map_err(|_| ProvisionError::UnsupportedPostgres) +} + +async fn run_statement( + session: &Session, + plan: &Plan, + statement: &Statement, + mode: Mode, +) -> Result { + if mode == Mode::Converge { + if let Some(probe) = &statement.probe { + if probe_is_satisfied(session, plan, statement, probe).await? { + return Ok(StatementOutcome::Present); + } + } + } + apply(session, plan, statement).await?; + Ok(if statement.probe.is_some() { + StatementOutcome::Created + } else { + StatementOutcome::Applied + }) +} + +async fn apply( + session: &Session, + plan: &Plan, + statement: &Statement, +) -> Result<(), ProvisionError> { + bounded_call(session.client.batch_execute(statement.executable())) + .await + .map_err(|failure| { + if failure.lacks_privilege() { + ProvisionError::StatementNeedsPrivilege { + step: statement.step, + needs: statement.needs, + scope: statement.scope, + database: plan.database().to_owned(), + } + } else { + call_error(statement.step, failure) + } + }) +} + +/// Whether the probed object already exists in the shape the plan creates. +/// An object that exists in another shape is an error, not `false`. +async fn probe_is_satisfied( + session: &Session, + plan: &Plan, + statement: &Statement, + probe: &Probe, +) -> Result { + let step = statement.step; + match probe { + Probe::Role { + name, + login, + member_of, + } => { + // Columns 1 to 6 are attributes that must be false: the six + // flags. Column 7 is a default for `role`, `search_path` or + // `session_authorization` set for the role in every database or + // in the provisioned one. Column 8 is membership of any role + // other than `member_of` granted as the plan grants it. + let row = bounded_call(session.client.query_opt( + "SELECT r.rolcanlogin, r.rolsuper, r.rolcreatedb, r.rolcreaterole, \ + r.rolinherit, r.rolbypassrls, r.rolreplication, \ + EXISTS (SELECT 1 FROM pg_catalog.pg_db_role_setting s, \ + unnest(s.setconfig) AS c \ + WHERE s.setrole = r.oid \ + AND (s.setdatabase = 0 \ + OR s.setdatabase = (SELECT d.oid \ + FROM pg_catalog.pg_database d \ + WHERE d.datname = $3)) \ + AND lower(split_part(c, '=', 1)) \ + IN ('role', 'search_path', 'session_authorization')), \ + EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m \ + JOIN pg_catalog.pg_roles g ON g.oid = m.roleid \ + WHERE m.member = r.oid \ + AND NOT (coalesce(g.rolname = $2::text, false) \ + AND NOT m.inherit_option \ + AND m.set_option \ + AND NOT m.admin_option)) \ + FROM pg_catalog.pg_roles r WHERE r.rolname = $1", + &[name, member_of, &plan.database()], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let Some(row) = row else { + return Ok(false); + }; + let can_login: bool = row.try_get(0).map_err(|_| unreadable(step))?; + let mut others = false; + for column in 1..7 { + let flag: bool = row.try_get(column).map_err(|_| unreadable(step))?; + others |= flag; + } + if can_login != *login || others { + return Err(ProvisionError::RoleAttributesDiffer { + step, + role: name.clone(), + }); + } + let redirected: bool = row.try_get(7).map_err(|_| unreadable(step))?; + if redirected { + return Err(ProvisionError::RoleSettingsDiffer { + step, + role: name.clone(), + }); + } + let other_membership: bool = row.try_get(8).map_err(|_| unreadable(step))?; + if other_membership { + return Err(ProvisionError::RoleMembershipDiffers { + step, + role: name.clone(), + }); + } + Ok(true) + } + Probe::Database { name } => { + // Ownership privileges follow membership with INHERIT, which is + // what `pg_has_role(..., 'USAGE')` tests, and are held by every + // superuser. + let row = bounded_call(session.client.query_opt( + "SELECT pg_catalog.pg_has_role(current_user, datdba, 'USAGE'), datistemplate \ + FROM pg_catalog.pg_database WHERE datname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + match row { + None => Ok(false), + Some(row) => { + let can_act: bool = row.try_get(0).map_err(|_| unreadable(step))?; + let template: bool = row.try_get(1).map_err(|_| unreadable(step))?; + if template { + Err(ProvisionError::DatabaseIsTemplate { + database: name.clone(), + }) + } else if can_act { + Ok(true) + } else { + Err(ProvisionError::DatabaseOwnerDiffers { + database: name.clone(), + }) + } + } + } + } + Probe::Extension { + name, + minimum_version, + setup, + } => { + let row = bounded_call(session.client.query_opt( + "SELECT extversion::text FROM pg_catalog.pg_extension WHERE extname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let Some(row) = row else { + return Ok(false); + }; + let installed: String = row.try_get(0).map_err(|_| unreadable(step))?; + if let Some(minimum) = minimum_version { + if !version_at_least(&installed, *minimum) { + return Err(ProvisionError::ExtensionTooOld { + step, + extension: name.clone(), + }); + } + } + if let Some(setup) = setup { + let row = bounded_call(session.client.query_one( + "SELECT coalesce((SELECT e.extnamespace = to_regnamespace($1::text)::oid \ + FROM pg_catalog.pg_extension e WHERE e.extname = $2), \ + false), \ + pg_catalog.pg_has_role($3::text::name, $4::text::name, 'SET')", + &[&setup.schema, name, &setup.member, &setup.role], + )) + .await + .map_err(|failure| call_error(step, failure))?; + let in_schema: bool = row.try_get(0).map_err(|_| unreadable(step))?; + let can_set: bool = row.try_get(1).map_err(|_| unreadable(step))?; + if !in_schema || !can_set { + return Err(ProvisionError::ExtensionIncomplete { + step, + extension: name.clone(), + }); + } + } + Ok(true) + } + Probe::Schema { name, owner } => { + let row = bounded_call(session.client.query_opt( + "SELECT pg_catalog.pg_get_userbyid(nspowner)::text \ + FROM pg_catalog.pg_namespace WHERE nspname = $1", + &[name], + )) + .await + .map_err(|failure| call_error(step, failure))?; + match row { + None => Ok(false), + Some(row) => { + let actual: String = row.try_get(0).map_err(|_| unreadable(step))?; + if actual == *owner { + Ok(true) + } else { + Err(ProvisionError::SchemaOwnerDiffers { + step, + schema: name.clone(), + database: plan.database().to_owned(), + }) + } + } + } + } + } +} + +/// Compares the leading `major.minor` of an extension version such as +/// `3.5.2` or `3.6.0dev`. +fn version_at_least(version: &str, minimum: (u32, u32)) -> bool { + let mut parts = version.split('.').map(|part| { + part.chars() + .take_while(char::is_ascii_digit) + .collect::() + .parse::() + .ok() + }); + match (parts.next().flatten(), parts.next().flatten()) { + (Some(major), Some(minor)) => (major, minor) >= minimum, + _ => false, + } +} + +/// Opens one session per product role, in the provisioned database, and asks +/// each who it is. A role that already existed keeps its stored password, so +/// this is what tells an operator that the configured credential does not +/// open a session. The administrator URL supplies only the endpoint and TLS. +pub async fn verify_logins( + admin: &AdminConfig, + target: &ProvisionTarget, +) -> Result<(), ProvisionError> { + let mut roles = vec![&target.migration]; + if target.runtime.name != target.migration.name { + roles.push(&target.runtime); + } + for role in roles { + let failed = |sqlstate: Option| ProvisionError::RoleLoginFailed { + role: role.name.clone(), + sqlstate, + }; + let session = admin + .connect_as(&target.database, &role.name, role.password()) + .await + .map_err(|failure| failed(failure.sqlstate))?; + let row = bounded_call(session.client.query_one("SELECT current_user::text", &[])) + .await + .map_err(|failure| { + failed(match failure { + CallFailure::Server { sqlstate } => Some(sqlstate), + CallFailure::Unconfirmed => None, + }) + })?; + let current: String = row.try_get(0).map_err(|_| failed(None))?; + if current != role.name { + return Err(failed(None)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extension_versions_compare_by_major_and_minor() { + assert!(version_at_least("3.5.2", (3, 5))); + assert!(version_at_least("3.6.0dev", (3, 5))); + assert!(version_at_least("4.0.0", (3, 5))); + assert!(!version_at_least("3.4.9", (3, 5))); + assert!(!version_at_least("3", (3, 5))); + assert!(!version_at_least("not a version", (3, 5))); + } + + #[test] + fn every_code_is_distinct_and_in_the_provision_family() { + let errors = [ + ProvisionError::AdminConnectFailed { sqlstate: None }, + ProvisionError::UnsupportedPostgres, + ProvisionError::StatementNeedsPrivilege { + step: "database.create", + needs: Needs::CreateDb, + scope: Scope::Server, + database: "d".to_owned(), + }, + ProvisionError::RoleAttributesDiffer { + step: "role.migration", + role: "r".to_owned(), + }, + ProvisionError::RoleSettingsDiffer { + step: "role.runtime", + role: "r".to_owned(), + }, + ProvisionError::DatabaseConnectFailed { + database: "d".to_owned(), + sqlstate: Some("53300".to_owned()), + }, + ProvisionError::RoleMembershipDiffers { + step: "role.runtime", + role: "r".to_owned(), + }, + ProvisionError::DatabaseOwnerDiffers { + database: "d".to_owned(), + }, + ProvisionError::DatabaseIsTemplate { + database: "d".to_owned(), + }, + ProvisionError::SchemaOwnerDiffers { + step: "schema.owned", + schema: "s".to_owned(), + database: "d".to_owned(), + }, + ProvisionError::ExtensionTooOld { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + ProvisionError::ExtensionIncomplete { + step: "extension.postgis", + extension: "postgis".to_owned(), + }, + ProvisionError::RoleLoginFailed { + role: "r".to_owned(), + sqlstate: Some("28P01".to_owned()), + }, + ProvisionError::EffectUnconfirmed { + step: "role.runtime", + }, + ProvisionError::StatementFailed { + step: "role.runtime", + sqlstate: "42710".to_owned(), + }, + ]; + let mut codes: Vec<&str> = errors.iter().map(ProvisionError::code).collect(); + assert!(codes + .iter() + .all(|code| code.starts_with("platform.provision."))); + codes.sort_unstable(); + codes.dedup(); + assert_eq!(codes.len(), errors.len()); + } + + #[test] + fn the_floor_error_uses_the_ledger_sentence() { + assert!(ProvisionError::UnsupportedPostgres + .to_string() + .starts_with("PostgreSQL 17 or newer is required")); + } +} diff --git a/crates/registry-platform-provision/src/lib.rs b/crates/registry-platform-provision/src/lib.rs new file mode 100644 index 0000000000..cb2fe564bf --- /dev/null +++ b/crates/registry-platform-provision/src/lib.rs @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Product-free PostgreSQL provisioning for Registry Stack runtimes. +//! +//! A product describes what it needs from an empty server as data +//! ([`ProductDatabase`]) and names its roles and database ([`ProvisionTarget`]). +//! [`plan`] turns those into an ordered list of statements. [`render_script`] +//! prints that list for an administrator to review and run with `psql`. The +//! printed script never holds a password or a password verifier. +//! +//! [`execute`] runs the same plan against a server as an administrator over +//! verified TLS ([`admin_config`]). It checks the server version first, creates +//! only what is absent, refuses what exists in another shape, and names the one +//! statement an administrator role lacks the privilege for. Role passwords +//! reach the server as SCRAM-SHA-256 verifiers and never reach an error or a +//! report. [`verify_logins`] then opens a session as each product role. + +mod admin; +#[cfg(feature = "cli")] +pub mod cli; +mod execute; +mod plan; +pub mod sql; +#[cfg(feature = "test-support")] +#[doc(hidden)] +pub mod test_support; + +pub use admin::{admin_config, AdminConfig, AdminConfigError}; +pub use execute::{ + execute, execute_recording, verify_logins, Failure, Mode, Outcome, ProvisionError, + StatementOutcome, +}; + +pub use plan::{ + plan, render_script, verify_server_version, ExtensionSetup, Needs, Plan, PlanError, Probe, + ProductDatabase, ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, Statement, + UnsupportedPostgres, +}; + +#[cfg(feature = "cli")] +pub use cli::{run_provision, ProvisionArgs, ProvisionInput}; diff --git a/crates/registry-platform-provision/src/plan.rs b/crates/registry-platform-provision/src/plan.rs new file mode 100644 index 0000000000..9304ebd74b --- /dev/null +++ b/crates/registry-platform-provision/src/plan.rs @@ -0,0 +1,1171 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The provisioning plan: which statements a product needs, in order, and the +//! rules that make running them again safe. + +use std::fmt; + +use zeroize::Zeroizing; + +use crate::sql; + +/// What one product needs from an empty server. Built by the product, never by +/// this crate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProductDatabase { + /// Names the product in reports only. + pub product: &'static str, + pub layout: SchemaLayout, + pub btree_gist: bool, + pub spatial: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaLayout { + /// Tables live in `public`. The migration role gets USAGE and CREATE on it. + PublicForMigration, + /// Named schemas, each created with AUTHORIZATION the migration role. + Owned(Vec), + /// `apply` creates the schema. The migration role gets CREATE on the database. + CreatedByApply, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Spatial { + /// Schema holding PostGIS. Written unquoted, so it must be a plain lower-case identifier. + pub schema: String, + pub bbox_role: String, + pub minimum_postgis: (u32, u32), +} + +/// A role name and its password. `Debug` prints the name only. +pub struct RoleCredential { + pub name: String, + password: Zeroizing, +} + +impl RoleCredential { + pub fn new(name: impl Into, password: impl Into) -> Self { + Self { + name: name.into(), + password: Zeroizing::new(password.into()), + } + } + + /// For the login check, which opens a session as this role. + pub(crate) fn password(&self) -> &str { + &self.password + } +} + +impl fmt::Debug for RoleCredential { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RoleCredential") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + +/// Role names, database name and passwords. +#[derive(Debug)] +pub struct ProvisionTarget { + pub database: String, + pub migration: RoleCredential, + /// The same name as `migration` means single-role mode. + pub runtime: RoleCredential, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope { + Server, + Database, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Needs { + CreateRole, + CreateDb, + DatabaseOwner, + Superuser, +} + +/// The catalog fact that tells a converging run the object already exists. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Probe { + Role { + name: String, + login: bool, + /// The one role this plan itself grants to the role, with + /// `INHERIT FALSE, SET TRUE, ADMIN FALSE`. Membership of any other + /// role is refused: it would carry privileges the plan did not grant. + member_of: Option, + }, + Database { + name: String, + }, + Extension { + name: String, + minimum_version: Option<(u32, u32)>, + /// What the same statement block sets up beside the extension. An + /// extension present without it was installed outside the plan. + setup: Option, + }, + Schema { + name: String, + owner: String, + }, +} + +/// The schema an extension must live in and the role membership the +/// extension's statement block grants. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExtensionSetup { + pub schema: String, + /// `member` must be able to `SET ROLE` to `role`. + pub member: String, + pub role: String, +} + +pub struct Statement { + pub step: &'static str, + pub scope: Scope, + pub needs: Needs, + /// Never holds a password or a verifier. + pub printable: String, + /// `None`: re-applied on every run, a no-op when already true. + pub probe: Option, + /// The role the printed script asks the administrator to set a password for. + pub password_for: Option, + executable: Zeroizing, +} + +impl Statement { + /// The text an executor sends. Holds the SCRAM verifier, so it is never printed. + pub(crate) fn executable(&self) -> &str { + &self.executable + } +} + +impl fmt::Debug for Statement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Statement") + .field("step", &self.step) + .field("scope", &self.scope) + .field("needs", &self.needs) + .field("printable", &self.printable) + .field("probe", &self.probe) + .finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub struct Plan { + product: &'static str, + database: String, + single_role: bool, + statements: Vec, +} + +impl Plan { + pub fn product(&self) -> &'static str { + self.product + } + pub fn database(&self) -> &str { + &self.database + } + pub fn single_role(&self) -> bool { + self.single_role + } + pub fn statements(&self) -> &[Statement] { + &self.statements + } +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum PlanError { + /// Names the field, never its value. + #[error("invalid {what}")] + InvalidName { what: &'static str }, + #[error("an owned schema layout needs at least one schema")] + NoSchemas, + #[error("single-role mode needs one password for the one role")] + SingleRolePasswordsDiffer, +} + +/// The sentence is the activation ledger's own, so every product refuses an +/// old server in the same words. +#[derive(Debug, PartialEq, Eq)] +pub struct UnsupportedPostgres; + +impl fmt::Display for UnsupportedPostgres { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(®istry_platform_activation::Error::UnsupportedPostgres, f) + } +} + +impl std::error::Error for UnsupportedPostgres {} + +/// Refuses a `server_version_num` below the shared PostgreSQL floor. +pub fn verify_server_version(version_num: i32) -> Result<(), UnsupportedPostgres> { + if version_num < registry_platform_activation::MINIMUM_SERVER_VERSION_NUM { + return Err(UnsupportedPostgres); + } + Ok(()) +} + +const MAX_NAME_BYTES: usize = 63; + +/// Databases a product must never be provisioned into: PostgreSQL's own. +const RESERVED_DATABASES: [&str; 3] = ["postgres", "template0", "template1"]; + +/// A name reaches the printed `psql` script, where a line break would end a +/// meta-command and a backslash would start one, and a bidirectional override +/// would make a reviewed line read differently from what runs. So no control +/// character (C0, DEL or C1), backslash or bidirectional formatting character +/// is allowed in any name. +fn check_name(what: &'static str, name: &str) -> Result<(), PlanError> { + let unsafe_char = |c: char| { + c.is_control() + || c == '\\' + || matches!( + c, + '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' + ) + }; + if name.is_empty() || name.len() > MAX_NAME_BYTES || name.chars().any(unsafe_char) { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// `public` and `none` are keywords in a `GRANT` list, and `pg_` names belong +/// to PostgreSQL. +fn check_role_name(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + let lower = name.to_ascii_lowercase(); + if lower == "public" || lower == "none" || lower.starts_with("pg_") { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// `\connect` reads a database name holding `=`, or starting with a URI +/// scheme, as a connection string and so can reach another server. +fn check_database_name(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + let lower = name.to_ascii_lowercase(); + if name.contains('=') + || lower.starts_with("postgresql://") + || lower.starts_with("postgres://") + || RESERVED_DATABASES.contains(&name) + { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +/// The PostGIS schema is written unquoted in the statement text. +fn check_plain_identifier(what: &'static str, name: &str) -> Result<(), PlanError> { + check_name(what, name)?; + let mut bytes = name.bytes(); + let first_ok = bytes + .next() + .is_some_and(|b| b.is_ascii_lowercase() || b == b'_'); + if !first_ok || !bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') { + return Err(PlanError::InvalidName { what }); + } + Ok(()) +} + +fn statement( + step: &'static str, + scope: Scope, + needs: Needs, + printable: String, + probe: Option, +) -> Statement { + Statement { + step, + scope, + needs, + executable: Zeroizing::new(printable.clone()), + printable, + probe, + password_for: None, + } +} + +fn login_role( + step: &'static str, + credential: &RoleCredential, + member_of: Option<&str>, +) -> Statement { + let verifier = Zeroizing::new(postgres_protocol::password::scram_sha_256( + credential.password.as_bytes(), + )); + let mut statement = statement( + step, + Scope::Server, + Needs::CreateRole, + sql::create_role_printable_sql(&credential.name), + Some(Probe::Role { + name: credential.name.clone(), + login: true, + member_of: member_of.map(str::to_owned), + }), + ); + statement.executable = Zeroizing::new(sql::create_role_sql(&credential.name, &verifier)); + statement.password_for = Some(credential.name.clone()); + statement +} + +/// Builds the ordered statements one product needs on an empty server. +/// +/// A statement with a `probe` runs only when its object is absent. One +/// without is a grant, revoke or connection switch that is a no-op when it +/// already holds, so it runs every time. Passwords reach only the private +/// executable text, as SCRAM verifiers. +pub fn plan(product: &ProductDatabase, target: &ProvisionTarget) -> Result { + check_database_name("database name", &target.database)?; + check_role_name("migration role name", &target.migration.name)?; + check_role_name("runtime role name", &target.runtime.name)?; + let single_role = target.migration.name == target.runtime.name; + if single_role && *target.migration.password != *target.runtime.password { + return Err(PlanError::SingleRolePasswordsDiffer); + } + if let SchemaLayout::Owned(schemas) = &product.layout { + if schemas.is_empty() { + return Err(PlanError::NoSchemas); + } + for schema in schemas { + check_name("schema name", schema)?; + } + } + if let Some(spatial) = &product.spatial { + check_plain_identifier("PostGIS schema name", &spatial.schema)?; + check_role_name("PostGIS bbox role name", &spatial.bbox_role)?; + } + + let database = target.database.as_str(); + let migration = target.migration.name.as_str(); + let runtime = target.runtime.name.as_str(); + // The migration role is the one the plan makes a member of the bbox role. + let bbox = product + .spatial + .as_ref() + .map(|spatial| spatial.bbox_role.as_str()); + let mut statements = vec![login_role("role.migration", &target.migration, bbox)]; + if !single_role { + statements.push(login_role("role.runtime", &target.runtime, None)); + } + if let Some(spatial) = &product.spatial { + statements.push(statement( + "role.spatial-bbox", + Scope::Server, + Needs::CreateRole, + sql::create_nologin_role_sql(&spatial.bbox_role), + Some(Probe::Role { + name: spatial.bbox_role.clone(), + login: false, + member_of: None, + }), + )); + } + let owner = + |step, printable| statement(step, Scope::Server, Needs::DatabaseOwner, printable, None); + statements.push(statement( + "database.create", + Scope::Server, + Needs::CreateDb, + sql::create_database_sql(database), + Some(Probe::Database { + name: database.to_owned(), + }), + )); + statements.push(owner( + "database.revoke-public", + sql::revoke_public_sql(database), + )); + let grantees: Vec<&str> = if single_role { + vec![migration] + } else { + vec![migration, runtime] + }; + statements.push(owner( + "database.grant-connect", + sql::grant_connect_sql(database, &grantees), + )); + if product.layout == SchemaLayout::CreatedByApply { + statements.push(owner( + "database.grant-create", + sql::grant_create_sql(database, migration), + )); + } + statements.push(owner( + "database.allow-connections", + sql::allow_connections_sql(database), + )); + + let in_database = |step, printable, probe| { + statement( + step, + Scope::Database, + Needs::DatabaseOwner, + printable, + probe, + ) + }; + if product.btree_gist { + statements.push(in_database( + "extension.btree-gist", + sql::btree_gist_sql().to_owned(), + Some(Probe::Extension { + name: "btree_gist".to_owned(), + minimum_version: None, + setup: None, + }), + )); + } + match &product.layout { + SchemaLayout::Owned(schemas) => { + for schema in schemas { + statements.push(in_database( + "schema.owned", + sql::owned_schema_sql(schema, migration), + Some(Probe::Schema { + name: schema.clone(), + owner: migration.to_owned(), + }), + )); + } + } + SchemaLayout::PublicForMigration => { + statements.push(in_database( + "schema.public", + sql::public_schema_sql(migration, runtime), + None, + )); + } + SchemaLayout::CreatedByApply => {} + } + if let Some(spatial) = &product.spatial { + let mut postgis = in_database( + "extension.postgis", + sql::postgis_prerequisites_sql(&spatial.schema, migration, runtime, &spatial.bbox_role), + Some(Probe::Extension { + name: "postgis".to_owned(), + minimum_version: Some(spatial.minimum_postgis), + setup: Some(ExtensionSetup { + schema: spatial.schema.clone(), + member: migration.to_owned(), + role: spatial.bbox_role.clone(), + }), + }), + ); + postgis.needs = Needs::Superuser; + statements.push(postgis); + } + + Ok(Plan { + product: product.product, + database: target.database.clone(), + single_role, + statements, + }) +} + +/// The script an administrator reviews and runs with `psql`. It holds no +/// password and no verifier: each login role is followed by a `\password` +/// line so `psql` prompts for it. +pub fn render_script(plan: &Plan) -> String { + let mut script = format!( + "-- provision script, product {}. Nothing was run.\n\ + -- For a server where these objects do not exist yet. Review, then run with psql as an\n\ + -- administrator that has CREATEROLE and CREATEDB. It stops at the first error.\n\ + \\set ON_ERROR_STOP on\n\ + SET createrole_self_grant = {};\n", + plan.product, + sql::quote_literal(sql::CREATEROLE_SELF_GRANT), + ); + let mut connected = false; + for statement in &plan.statements { + if statement.scope == Scope::Database && !connected { + script.push_str(&format!( + "\\connect {}\n", + sql::quote_identifier(&plan.database) + )); + connected = true; + } + if statement.needs == Needs::Superuser { + script.push_str("-- needs a superuser\n"); + } + script.push_str(&statement.printable); + if !statement.printable.ends_with(';') { + script.push(';'); + } + script.push('\n'); + if let Some(role) = &statement.password_for { + script.push_str(&format!("\\password {}\n", sql::quote_identifier(role))); + } + } + script +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sql::*; + + const PASSWORD_M: &str = "migration-pass-0123"; + const PASSWORD_R: &str = "runtime-pass-4567"; + + fn target() -> ProvisionTarget { + ProvisionTarget { + database: "casework".to_owned(), + migration: RoleCredential::new("casework_migration", PASSWORD_M), + runtime: RoleCredential::new("casework_runtime", PASSWORD_R), + } + } + + fn product(layout: SchemaLayout) -> ProductDatabase { + ProductDatabase { + product: "casework", + layout, + btree_gist: false, + spatial: None, + } + } + + fn breg_schemas() -> Vec { + [ + "registry_internal", + "registry_data", + "registry_source", + "registry_derived", + "registry_context", + ] + .map(str::to_owned) + .to_vec() + } + + fn breg_spatial() -> ProductDatabase { + ProductDatabase { + product: "breg", + layout: SchemaLayout::Owned(breg_schemas()), + btree_gist: true, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: "casework_runtime__spatial_bbox".to_owned(), + minimum_postgis: (3, 5), + }), + } + } + + fn steps(plan: &Plan) -> Vec<&'static str> { + plan.statements().iter().map(|s| s.step).collect() + } + + #[test] + fn plan_lists_statements_in_order_for_public_layout() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "schema.public", + ] + ); + assert!(!plan.single_role()); + } + + #[test] + fn plan_lists_statements_in_order_for_owned_layout_with_spatial() { + let plan = plan(&breg_spatial(), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "role.spatial-bbox", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "extension.btree-gist", + "schema.owned", + "schema.owned", + "schema.owned", + "schema.owned", + "schema.owned", + "extension.postgis", + ] + ); + let postgis = plan.statements().last().unwrap(); + assert_eq!(postgis.needs, Needs::Superuser); + assert_eq!(postgis.scope, Scope::Database); + } + + #[test] + fn plan_lists_statements_in_order_for_created_by_apply_layout() { + let plan = plan(&product(SchemaLayout::CreatedByApply), &target()).unwrap(); + assert_eq!( + steps(&plan), + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.grant-create", + "database.allow-connections", + ] + ); + } + + #[test] + fn statements_carry_scope_needs_and_probe() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + let by_step = |step| plan.statements().iter().find(|s| s.step == step).unwrap(); + let role = by_step("role.migration"); + assert_eq!((role.scope, role.needs), (Scope::Server, Needs::CreateRole)); + assert_eq!( + role.probe, + Some(Probe::Role { + name: "casework_migration".to_owned(), + login: true, + member_of: None, + }) + ); + let create = by_step("database.create"); + assert_eq!(create.needs, Needs::CreateDb); + assert_eq!( + create.probe, + Some(Probe::Database { + name: "casework".to_owned() + }) + ); + for step in [ + "database.revoke-public", + "database.grant-connect", + "database.allow-connections", + "schema.public", + ] { + assert_eq!(by_step(step).probe, None, "{step}"); + assert_eq!(by_step(step).needs, Needs::DatabaseOwner, "{step}"); + } + assert_eq!(by_step("schema.public").scope, Scope::Database); + assert_eq!(by_step("database.revoke-public").scope, Scope::Server); + } + + #[test] + fn rendered_script_holds_no_password_and_no_verifier() { + for product in [product(SchemaLayout::PublicForMigration), breg_spatial()] { + let target = target(); + let plan = plan(&product, &target).unwrap(); + let script = render_script(&plan); + for (label, secret) in [ + ("the migration password", PASSWORD_M), + ("the runtime password", PASSWORD_R), + ("a SCRAM verifier", "SCRAM-SHA-256"), + ("a PASSWORD clause", "PASSWORD '"), + ] { + assert!(!script.contains(secret), "the script holds {label}"); + } + for rendered in [format!("{plan:?}"), format!("{target:?}")] { + assert!(!rendered.contains(PASSWORD_M) && !rendered.contains(PASSWORD_R)); + assert!(!rendered.contains("SCRAM-SHA-256")); + } + for statement in plan.statements() { + assert!(!statement.printable.contains("SCRAM-SHA-256")); + assert!(!statement.printable.contains(PASSWORD_M)); + } + } + } + + #[test] + fn executable_role_statements_carry_a_verifier_never_the_password() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + for statement in plan + .statements() + .iter() + .filter(|s| s.password_for.is_some()) + { + let executable = statement.executable(); + assert!( + executable.contains("PASSWORD 'SCRAM-SHA-256$"), + "{}", + statement.step + ); + assert!(!executable.contains(PASSWORD_M) && !executable.contains(PASSWORD_R)); + } + } + + #[test] + fn rendered_script_asks_for_passwords_and_switches_database() { + let script = render_script(&plan(&breg_spatial(), &target()).unwrap()); + assert!(script.contains("Nothing was run"), "{script}"); + assert!( + script.contains("SET createrole_self_grant = 'set,inherit';"), + "{script}" + ); + assert!( + script.contains("\\password \"casework_migration\""), + "{script}" + ); + assert!( + script.contains("\\password \"casework_runtime\""), + "{script}" + ); + assert!( + !script.contains("\\password \"casework_runtime__spatial_bbox\""), + "{script}" + ); + let connect = script.find("\\connect \"casework\"").expect("connect line"); + let allow = script.find("ALLOW_CONNECTIONS true").unwrap(); + let btree = script.find("CREATE EXTENSION btree_gist").unwrap(); + assert!(allow < connect && connect < btree, "{script}"); + let marker = script.find("-- needs a superuser").unwrap(); + assert!(script[marker..].contains("CREATE EXTENSION IF NOT EXISTS postgis")); + assert_eq!(script.matches("-- needs a superuser").count(), 1); + } + + #[test] + fn single_role_target_plans_one_role() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_M), + }; + let plan = plan(&product(SchemaLayout::PublicForMigration), &target).unwrap(); + assert!(plan.single_role()); + let roles: Vec<_> = plan + .statements() + .iter() + .filter(|s| s.step.starts_with("role.")) + .collect(); + assert_eq!(roles.len(), 1); + assert_eq!(roles[0].step, "role.migration"); + let grant = plan + .statements() + .iter() + .find(|s| s.step == "database.grant-connect") + .unwrap(); + assert_eq!( + grant.printable.matches("\"adapter\"").count(), + 2, + "{}", + grant.printable + ); + assert!( + grant.printable.ends_with("TO \"adapter\""), + "{}", + grant.printable + ); + } + + #[test] + fn single_role_with_two_passwords_is_refused() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_R), + }; + assert!(matches!( + plan(&product(SchemaLayout::PublicForMigration), &target), + Err(PlanError::SingleRolePasswordsDiffer) + )); + } + + #[test] + fn unusable_names_are_refused_without_echoing_them() { + let mut bad = target(); + bad.database = String::new(); + let error = plan(&product(SchemaLayout::PublicForMigration), &bad).unwrap_err(); + assert_eq!( + error, + PlanError::InvalidName { + what: "database name" + } + ); + + let mut long = target(); + long.migration = RoleCredential::new("m".repeat(64), PASSWORD_M); + assert!(plan(&product(SchemaLayout::PublicForMigration), &long).is_err()); + + let mut nul = target(); + nul.runtime = RoleCredential::new("a\0b", PASSWORD_R); + assert!(plan(&product(SchemaLayout::PublicForMigration), &nul).is_err()); + + assert_eq!( + plan(&product(SchemaLayout::Owned(Vec::new())), &target()).unwrap_err(), + PlanError::NoSchemas + ); + + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().schema = "bad schema; DROP".to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + PlanError::InvalidName { + what: "PostGIS schema name" + } + ); + } + + fn invalid(what: &'static str) -> PlanError { + PlanError::InvalidName { what } + } + + fn plan_for(target: &ProvisionTarget) -> Result { + plan(&product(SchemaLayout::PublicForMigration), target) + } + + #[test] + fn names_with_control_characters_or_backslashes_are_refused() { + for bad in ["a\nb", "a\rb", "a\x1bb", "a\x7fb", "a\\b", "a\tb"] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad:?}" + ); + + let mut migration = target(); + migration.migration = RoleCredential::new(bad, PASSWORD_M); + assert_eq!( + plan_for(&migration).unwrap_err(), + invalid("migration role name"), + "{bad:?}" + ); + + let mut runtime = target(); + runtime.runtime = RoleCredential::new(bad, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{bad:?}" + ); + + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().bbox_role = bad.to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + invalid("PostGIS bbox role name"), + "{bad:?}" + ); + } + } + + #[test] + fn a_database_name_with_an_equals_sign_is_refused_but_a_role_name_may_hold_one() { + let mut database = target(); + database.database = "host=attacker.example dbname=x".to_owned(); + assert_eq!(plan_for(&database).unwrap_err(), invalid("database name")); + + let mut role = target(); + role.runtime = RoleCredential::new("app=runtime", PASSWORD_R); + assert!(plan_for(&role).is_ok()); + } + + #[test] + fn a_database_name_that_starts_with_a_connection_uri_scheme_is_refused() { + for bad in [ + "postgresql://evil.example/x", + "postgres://evil.example/x", + "PostgreSQL://evil.example/x", + "POSTGRES://evil.example/x", + ] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad}" + ); + } + // Only a leading scheme is read as a URI, and a role name may hold one. + let mut inner = target(); + inner.database = "app-postgres://x".to_owned(); + assert!(plan_for(&inner).is_ok()); + let mut role = target(); + role.runtime = RoleCredential::new("postgres://runtime", PASSWORD_R); + assert!(plan_for(&role).is_ok()); + } + + #[test] + fn names_with_c1_controls_or_bidirectional_overrides_are_refused() { + for bad in [ + "a\u{85}b", + "a\u{9f}b", + "a\u{202e}b", + "a\u{2066}b", + "a\u{200f}b", + ] { + let mut database = target(); + database.database = bad.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{bad:?}" + ); + let mut runtime = target(); + runtime.runtime = RoleCredential::new(bad, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{bad:?}" + ); + } + let mut accented = target(); + accented.database = "cafe\u{301}".to_owned(); + assert!(plan_for(&accented).is_ok()); + } + + #[test] + fn reserved_role_names_are_refused() { + for reserved in [ + "public", + "PUBLIC", + "none", + "None", + "pg_read_all_data", + "PG_x", + ] { + let mut migration = target(); + migration.migration = RoleCredential::new(reserved, PASSWORD_M); + assert_eq!( + plan_for(&migration).unwrap_err(), + invalid("migration role name"), + "{reserved}" + ); + let mut runtime = target(); + runtime.runtime = RoleCredential::new(reserved, PASSWORD_R); + assert_eq!( + plan_for(&runtime).unwrap_err(), + invalid("runtime role name"), + "{reserved}" + ); + } + let mut spatial = breg_spatial(); + spatial.spatial.as_mut().unwrap().bbox_role = "public".to_owned(); + assert_eq!( + plan(&spatial, &target()).unwrap_err(), + invalid("PostGIS bbox role name") + ); + let mut single = target(); + single.migration = RoleCredential::new("public", PASSWORD_M); + single.runtime = RoleCredential::new("public", PASSWORD_M); + assert!(plan_for(&single).is_err()); + } + + #[test] + fn the_postgres_template_and_maintenance_databases_are_refused() { + for reserved in ["postgres", "template0", "template1"] { + let mut database = target(); + database.database = reserved.to_owned(); + assert_eq!( + plan_for(&database).unwrap_err(), + invalid("database name"), + "{reserved}" + ); + } + } + + #[test] + fn the_printed_script_stops_at_the_first_error_before_anything_else() { + let script = render_script(&plan(&breg_spatial(), &target()).unwrap()); + let first = script + .lines() + .find(|line| !line.starts_with("--")) + .expect("a statement line"); + assert_eq!(first, "\\set ON_ERROR_STOP on", "{script}"); + } + + #[test] + fn the_runtime_role_gets_usage_on_public_from_the_plan() { + let plan = plan(&product(SchemaLayout::PublicForMigration), &target()).unwrap(); + let public = plan + .statements() + .iter() + .find(|statement| statement.step == "schema.public") + .unwrap(); + assert_eq!(public.probe, None); + assert_eq!(public.scope, Scope::Database); + assert_eq!( + public.printable, + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"; \ + GRANT USAGE ON SCHEMA public TO \"casework_runtime\"" + ); + assert!(!public.printable.contains("GRANT OPTION")); + } + + #[test] + fn single_role_public_layout_grants_the_one_role_once() { + let target = ProvisionTarget { + database: "adapter".to_owned(), + migration: RoleCredential::new("adapter", PASSWORD_M), + runtime: RoleCredential::new("adapter", PASSWORD_M), + }; + let plan = plan(&product(SchemaLayout::PublicForMigration), &target).unwrap(); + let public = plan + .statements() + .iter() + .find(|statement| statement.step == "schema.public") + .unwrap(); + assert_eq!( + public.printable, + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"adapter\"" + ); + } + + #[test] + fn literals_with_a_backslash_are_written_as_escape_strings() { + assert_eq!(quote_literal("a\\b'c"), "E'a\\\\b''c'"); + assert_eq!(quote_literal("plain"), "'plain'"); + } + + #[test] + fn server_below_the_floor_is_refused() { + for version in [0, 90_600, 160_999, 169_999] { + assert_eq!( + verify_server_version(version), + Err(UnsupportedPostgres), + "{version}" + ); + } + for version in [170_000, 170_011, 180_000] { + assert_eq!(verify_server_version(version), Ok(()), "{version}"); + } + assert!(UnsupportedPostgres + .to_string() + .starts_with("PostgreSQL 17 or newer is required")); + assert_eq!( + registry_platform_activation::MINIMUM_SERVER_VERSION_NUM, + 170_000 + ); + } + + // Builder and quoting tests, carried over from `registry-rstack-dev`. + + #[test] + fn identifiers_and_passwords_are_quoted_for_postgresql() { + assert_eq!(quote_identifier("a\"b"), "\"a\"\"b\""); + assert_eq!(quote_literal("a'b"), "'a''b'"); + } + + #[test] + fn role_statement_carries_a_postgresql_scram_verifier_not_cleartext() { + let password = "a-throwaway-credential"; + let verifier = postgres_protocol::password::scram_sha_256(password.as_bytes()); + let sql = create_role_sql("rstack_role", &verifier); + let expected = format!( + "CREATE ROLE \"rstack_role\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '{verifier}'" + ); + assert!(verifier.starts_with("SCRAM-SHA-256$")); + assert!(sql == expected && !sql.contains(password)); + } + + #[test] + fn nologin_role_statement_has_no_password_clause() { + assert_eq!( + create_nologin_role_sql("bbox"), + "CREATE ROLE \"bbox\" NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS" + ); + } + + #[test] + fn database_creation_is_closed_to_connections() { + assert_eq!( + create_database_sql("db\"x"), + "CREATE DATABASE \"db\"\"x\" WITH ALLOW_CONNECTIONS false" + ); + } + + #[test] + fn database_access_is_closed_to_public_before_connections_are_enabled() { + let sql = database_access_sql("casework", "casework_migration", "casework_runtime"); + let revoke = sql.find("REVOKE ALL ON DATABASE").unwrap(); + let grant = sql.find("GRANT CONNECT ON DATABASE").unwrap(); + let enable = sql.find("ALLOW_CONNECTIONS true").unwrap(); + assert!(revoke < grant && grant < enable, "{sql}"); + assert!(sql.contains("e_identifier("casework_migration"))); + assert!(sql.contains("e_identifier("casework_runtime"))); + assert_eq!( + sql, + "REVOKE ALL ON DATABASE \"casework\" FROM PUBLIC; \ + GRANT CONNECT ON DATABASE \"casework\" TO \"casework_migration\", \"casework_runtime\"; \ + ALTER DATABASE \"casework\" ALLOW_CONNECTIONS true" + ); + } + + #[test] + fn grant_create_is_on_the_database_for_the_migration_role() { + assert_eq!( + grant_create_sql("coordinator", "coordinator_migration"), + "GRANT CREATE ON DATABASE \"coordinator\" TO \"coordinator_migration\"" + ); + } + + #[test] + fn breg_setup_installs_extension_and_all_owned_schemas() { + let layout = SchemaLayout::Owned(breg_schemas()); + let sql = database_setup_sql("casework_migration", "casework_runtime", &layout, true); + assert!(sql.starts_with("CREATE EXTENSION btree_gist;"), "{sql}"); + for schema in breg_schemas() { + assert!( + sql.contains(&format!( + "CREATE SCHEMA {} AUTHORIZATION {}", + quote_identifier(&schema), + quote_identifier("casework_migration") + )), + "{sql}" + ); + assert!( + sql.contains(&format!( + "REVOKE ALL ON SCHEMA {} FROM PUBLIC", + quote_identifier(&schema) + )), + "{sql}" + ); + } + } + + #[test] + fn public_setup_restricts_create_and_grants_both_roles() { + assert_eq!( + database_setup_sql( + "casework_migration", + "casework_runtime", + &SchemaLayout::PublicForMigration, + false + ), + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO \"casework_migration\"; \ + GRANT USAGE ON SCHEMA public TO \"casework_runtime\"" + ); + assert_eq!( + database_setup_sql("m", "r", &SchemaLayout::CreatedByApply, false), + "" + ); + } + + #[test] + fn postgis_prerequisites_name_the_schema_and_both_roles() { + let sql = postgis_prerequisites_sql("registry_spatial_ext", "m", "r", "bbox"); + assert_eq!( + sql, + "CREATE SCHEMA IF NOT EXISTS registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO \"m\", \"r\";\n\ + GRANT \"bbox\" TO \"m\" WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO \"bbox\";" + ); + } +} diff --git a/crates/registry-platform-provision/src/sql.rs b/crates/registry-platform-provision/src/sql.rs new file mode 100644 index 0000000000..dd1272fe22 --- /dev/null +++ b/crates/registry-platform-provision/src/sql.rs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Statement builders. Every builder returns text and runs nothing. The text +//! of each statement is the text `rstack dev` provisions with. + +use crate::plan::SchemaLayout; + +/// Lets a role holding CREATEROLE use the roles it creates. PostgreSQL 16 and +/// later grant such a creator only ADMIN on them, which is not enough for +/// `CREATE SCHEMA ... AUTHORIZATION` or `CREATE DATABASE ... OWNER`. +pub const CREATEROLE_SELF_GRANT: &str = "set,inherit"; + +pub fn quote_identifier(value: &str) -> String { + format!("\"{}\"", value.replace('"', "\"\"")) +} + +/// A string literal. A backslash makes it an escape string, so the text means +/// the same whatever `standard_conforming_strings` is set to. +pub fn quote_literal(value: &str) -> String { + let escaped = value.replace('\'', "''"); + if value.contains('\\') { + format!("E'{}'", escaped.replace('\\', "\\\\")) + } else { + format!("'{escaped}'") + } +} + +/// `verifier` is a SCRAM-SHA-256 verifier, never a password. +pub fn create_role_sql(role: &str, verifier: &str) -> String { + format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD {}", + quote_identifier(role), + quote_literal(verifier) + ) +} + +/// The login role without its `PASSWORD` clause, for the printed script. +pub(crate) fn create_role_printable_sql(role: &str) -> String { + format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", + quote_identifier(role) + ) +} + +pub fn create_nologin_role_sql(role: &str) -> String { + format!( + "CREATE ROLE {} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", + quote_identifier(role) + ) +} + +pub fn create_database_sql(database: &str) -> String { + format!( + "CREATE DATABASE {} WITH ALLOW_CONNECTIONS false", + quote_identifier(database) + ) +} + +pub fn revoke_public_sql(database: &str) -> String { + format!( + "REVOKE ALL ON DATABASE {} FROM PUBLIC", + quote_identifier(database) + ) +} + +pub fn grant_connect_sql(database: &str, roles: &[&str]) -> String { + let roles = roles + .iter() + .map(|role| quote_identifier(role)) + .collect::>() + .join(", "); + format!( + "GRANT CONNECT ON DATABASE {} TO {roles}", + quote_identifier(database) + ) +} + +pub fn grant_create_sql(database: &str, migration: &str) -> String { + format!( + "GRANT CREATE ON DATABASE {} TO {}", + quote_identifier(database), + quote_identifier(migration) + ) +} + +pub fn allow_connections_sql(database: &str) -> String { + format!( + "ALTER DATABASE {} ALLOW_CONNECTIONS true", + quote_identifier(database) + ) +} + +/// The three statements that close a new database to PUBLIC, open it to the +/// run's roles and then let it accept connections, in that order. +pub fn database_access_sql(database: &str, migration: &str, runtime: &str) -> String { + format!( + "{}; {}; {}", + revoke_public_sql(database), + grant_connect_sql(database, &distinct_roles(migration, runtime)), + allow_connections_sql(database), + ) +} + +pub fn btree_gist_sql() -> &'static str { + "CREATE EXTENSION btree_gist" +} + +pub fn owned_schema_sql(schema: &str, owner: &str) -> String { + format!( + "CREATE SCHEMA {schema} AUTHORIZATION {owner}; \ + REVOKE ALL ON SCHEMA {schema} FROM PUBLIC", + schema = quote_identifier(schema), + owner = quote_identifier(owner), + ) +} + +/// `public` is closed to PUBLIC's CREATE. The migration role gets USAGE and +/// CREATE, and the runtime role USAGE, directly from the administrator that +/// owns the schema, so that PUBLIC's default USAGE is not what lets the +/// runtime role resolve the product's tables. Running it again restores both. +pub fn public_schema_sql(migration: &str, runtime: &str) -> String { + let mut sql = format!( + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO {}", + quote_identifier(migration) + ); + if runtime != migration { + sql.push_str(&format!( + "; GRANT USAGE ON SCHEMA public TO {}", + quote_identifier(runtime) + )); + } + sql +} + +/// Everything that runs inside the database apart from PostGIS: the one batch +/// `rstack dev` configures a fresh database with. `CreatedByApply` has none. +pub fn database_setup_sql( + migration: &str, + runtime: &str, + layout: &SchemaLayout, + btree_gist: bool, +) -> String { + match layout { + SchemaLayout::Owned(schemas) => { + let schemas = schemas + .iter() + .map(|schema| owned_schema_sql(schema, migration)) + .collect::>() + .join("; "); + if btree_gist { + format!("{}; {schemas}", btree_gist_sql()) + } else { + schemas + } + } + SchemaLayout::PublicForMigration => public_schema_sql(migration, runtime), + SchemaLayout::CreatedByApply => String::new(), + } +} + +/// Administrator-run PostGIS setup: the extension in its own schema, usable by +/// both roles, and the bbox role the migration role may SET. The bbox role +/// itself is created earlier. `schema` is written unquoted, so the caller +/// checks it is a plain lower-case identifier. +pub fn postgis_prerequisites_sql( + schema: &str, + migration: &str, + runtime: &str, + bbox_role: &str, +) -> String { + let roles = distinct_roles(migration, runtime) + .iter() + .map(|role| quote_identifier(role)) + .collect::>() + .join(", "); + let migration = quote_identifier(migration); + let bbox = quote_identifier(bbox_role); + format!( + "CREATE SCHEMA IF NOT EXISTS {schema};\n\ + REVOKE ALL ON SCHEMA {schema} FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA {schema};\n\ + GRANT USAGE ON SCHEMA {schema} TO {roles};\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA {schema} TO {bbox};" + ) +} + +/// Single-role mode names one role once. +fn distinct_roles<'a>(migration: &'a str, runtime: &'a str) -> Vec<&'a str> { + if migration == runtime { + vec![migration] + } else { + vec![migration, runtime] + } +} diff --git a/crates/registry-platform-provision/src/test_support.rs b/crates/registry-platform-provision/src/test_support.rs new file mode 100644 index 0000000000..f52994d383 --- /dev/null +++ b/crates/registry-platform-provision/src/test_support.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Helpers for the PostgreSQL tests of the products that provision with this +//! crate. They panic with a message that names the variable or the failure, +//! never the URL or the password. + +use tokio_postgres::Client; + +use crate::admin_config; + +/// Reads `PROVISION_TEST_DATABASE_URL` and the CA PEM file named by +/// `PROVISION_TEST_DATABASE_CA`. A missing variable or unreadable file fails +/// the test: a skipped database test is not database verification. +pub fn provision_test_env() -> (String, Vec) { + let url = std::env::var("PROVISION_TEST_DATABASE_URL") + .expect("PROVISION_TEST_DATABASE_URL names a disposable PostgreSQL superuser URL"); + let ca_path = std::env::var("PROVISION_TEST_DATABASE_CA") + .expect("PROVISION_TEST_DATABASE_CA names the PEM CA of the test server"); + let ca = std::fs::read(&ca_path).unwrap_or_else(|error| { + panic!("cannot read the file PROVISION_TEST_DATABASE_CA names: {error}") + }); + (url, ca) +} + +/// Opens a session over TLS verified against `ca_pem`, with the endpoint and +/// credentials of `url` (the same rules `provision` applies to an +/// administrator URL). `database` replaces the one the URL names. The +/// connection task runs on the current runtime. +pub async fn connect_verified(url: &str, ca_pem: &[u8], database: Option<&str>) -> Client { + let config = admin_config(url, Some(ca_pem)) + .unwrap_or_else(|error| panic!("the test PostgreSQL URL or CA is refused: {error}")); + config + .connect_detached(database) + .await + .unwrap_or_else(|error| panic!("cannot open a verified-TLS test session: {error}")) +} diff --git a/crates/registry-platform-provision/tests/postgres.rs b/crates/registry-platform-provision/tests/postgres.rs new file mode 100644 index 0000000000..9b38ae7fc4 --- /dev/null +++ b/crates/registry-platform-provision/tests/postgres.rs @@ -0,0 +1,1830 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runs the provisioning executor against real PostgreSQL servers. +//! +//! The suite reads three variables and fails, never skips, when one is +//! missing: +//! +//! - `PROVISION_TEST_DATABASE_URL`: a disposable PostgreSQL 17 superuser with +//! PostGIS available, over TLS. +//! - `PROVISION_TEST_DATABASE_CA`: the CA PEM file that signs its certificate. +//! - `PROVISION_TEST_OLD_DATABASE_URL`: a disposable superuser on a server +//! older than the floor, signed by the same CA. +//! +//! Each test creates its own administrator role, so a test that provisions as +//! a non-superuser holds only the attributes the test names. + +use registry_platform_provision::{ + admin_config, execute, execute_recording, plan, render_script, verify_logins, AdminConfig, + AdminConfigError, Mode, Needs, Outcome, ProductDatabase, ProvisionError, ProvisionTarget, + RoleCredential, SchemaLayout, Scope, Spatial, StatementOutcome, +}; +use rustls::pki_types::{pem::PemObject as _, CertificateDer}; +use tokio_postgres::{config::SslMode, Client, Config}; +use tokio_postgres_rustls::MakeRustlsConnect; +use url::Url; + +/// One test at a time: concurrent `CREATE DATABASE` calls contend for +/// `template1`. +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +const NON_SUPERUSER_ADMIN: &str = "CREATEROLE CREATEDB"; +const SUPERUSER_ADMIN: &str = "SUPERUSER"; + +fn required(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("the postgres-test feature needs {name}")) +} + +fn random_hex(bytes: usize) -> String { + let mut buffer = vec![0_u8; bytes]; + getrandom::fill(&mut buffer).expect("random bytes"); + buffer.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn quote(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +fn quote_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +fn tls(ca: &[u8]) -> MakeRustlsConnect { + let provider = rustls::crypto::ring::default_provider(); + if provider.install_default().is_err() { + assert!( + rustls::crypto::CryptoProvider::get_default().is_some(), + "no TLS provider" + ); + } + let mut roots = rustls::RootCertStore::empty(); + for certificate in CertificateDer::pem_slice_iter(ca) { + roots.add(certificate.expect("CA PEM")).expect("CA root"); + } + MakeRustlsConnect::new( + rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(), + ) +} + +/// A plain session for the test's own setup and catalog reads. +struct Raw { + client: Client, + task: tokio::task::JoinHandle>, +} + +impl Drop for Raw { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Raw { + async fn connect(base: &Url, ca: &[u8], user: &str, password: &str, database: &str) -> Self { + let mut config = Config::new(); + config + .host(base.host_str().expect("host")) + .port(base.port().unwrap_or(5432)) + .user(user) + .password(password) + .dbname(database) + .ssl_mode(SslMode::Require); + let (client, connection) = config.connect(tls(ca)).await.expect("test session"); + Self { + client, + task: tokio::spawn(connection), + } + } + + async fn exec(&self, sql: &str) { + self.client.batch_execute(sql).await.unwrap(); + } + + async fn text(&self, sql: &str) -> String { + self.client + .query_one(sql, &[]) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default() + } + + async fn flag(&self, sql: &str) -> bool { + self.client.query_one(sql, &[]).await.unwrap().get(0) + } +} + +struct Server { + url: Url, + ca: Vec, + superuser: Raw, +} + +impl Server { + async fn start(url_variable: &str) -> Self { + let url = Url::parse(&required(url_variable)).expect("test URL"); + let ca = std::fs::read(required("PROVISION_TEST_DATABASE_CA")).expect("CA file"); + let superuser = Raw::connect( + &url, + &ca, + url.username(), + url.password().expect("password"), + "postgres", + ) + .await; + Self { url, ca, superuser } + } + + async fn session(&self, user: &str, password: &str, database: &str) -> Raw { + Raw::connect(&self.url, &self.ca, user, password, database).await + } +} + +/// Names and passwords for one test, and the administrator it provisions as. +struct Fixture { + server: Server, + suffix: String, + admin_password: String, + migration_password: String, + runtime_password: String, +} + +impl Fixture { + async fn new(administrator_attributes: &str) -> Self { + Self::on( + Server::start("PROVISION_TEST_DATABASE_URL").await, + administrator_attributes, + ) + .await + } + + async fn on(server: Server, administrator_attributes: &str) -> Self { + let fixture = Self { + server, + suffix: random_hex(5), + admin_password: random_hex(16), + migration_password: random_hex(16), + runtime_password: random_hex(16), + }; + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN {administrator_attributes} PASSWORD '{}'", + quote(&fixture.admin_name()), + fixture.admin_password + )) + .await; + fixture + } + + fn database(&self) -> String { + format!("s2_db_{}", self.suffix) + } + fn migration_name(&self) -> String { + format!("s2_mig_{}", self.suffix) + } + fn runtime_name(&self) -> String { + format!("s2_run_{}", self.suffix) + } + fn admin_name(&self) -> String { + format!("s2_adm_{}", self.suffix) + } + fn bbox_name(&self) -> String { + format!("s2_bbox_{}", self.suffix) + } + + fn admin_url(&self) -> String { + let mut url = self.server.url.clone(); + url.set_username(&self.admin_name()).unwrap(); + url.set_password(Some(&self.admin_password)).unwrap(); + url.set_path("/postgres"); + url.into() + } + + fn admin(&self) -> AdminConfig { + admin_config(&self.admin_url(), Some(&self.server.ca)).unwrap() + } + + fn target(&self) -> ProvisionTarget { + ProvisionTarget { + database: self.database(), + migration: RoleCredential::new(self.migration_name(), &self.migration_password), + runtime: RoleCredential::new(self.runtime_name(), &self.runtime_password), + } + } + + fn single_role_target(&self) -> ProvisionTarget { + ProvisionTarget { + database: self.database(), + migration: RoleCredential::new(self.migration_name(), &self.migration_password), + runtime: RoleCredential::new(self.migration_name(), &self.migration_password), + } + } + + fn owned_product() -> ProductDatabase { + ProductDatabase { + product: "owned", + layout: SchemaLayout::Owned(vec!["s2_one".to_owned(), "s2_two".to_owned()]), + btree_gist: true, + spatial: None, + } + } + + fn public_product() -> ProductDatabase { + ProductDatabase { + product: "public", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } + } + + fn created_by_apply_product() -> ProductDatabase { + ProductDatabase { + product: "created-by-apply", + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + } + } + + fn spatial_product(&self, minimum_postgis: (u32, u32)) -> ProductDatabase { + ProductDatabase { + product: "spatial", + layout: SchemaLayout::Owned(vec!["s2_one".to_owned()]), + btree_gist: true, + spatial: Some(Spatial { + schema: "registry_spatial_ext".to_owned(), + bbox_role: self.bbox_name(), + minimum_postgis, + }), + } + } + + fn layouts() -> [ProductDatabase; 3] { + [ + Self::owned_product(), + Self::public_product(), + Self::created_by_apply_product(), + ] + } + + async fn provision(&self, product: &ProductDatabase) -> Result { + let plan = plan(product, &self.target()).unwrap(); + execute(&self.admin(), &plan, Mode::Converge).await + } + + /// The catalog this fixture's objects leave behind, with this fixture's + /// names replaced by placeholders, so two fixtures compare by shape. + async fn snapshot(&self) -> String { + let su = &self.server.superuser; + let names = vec![self.migration_name(), self.runtime_name(), self.bbox_name()]; + let roles = su + .client + .query_one( + "SELECT string_agg(concat_ws('|', rolname, rolsuper, rolinherit, rolcreaterole, \ + rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, \ + coalesce(rolvaliduntil::text, '')), E'\\n' ORDER BY rolname) \ + FROM pg_catalog.pg_roles WHERE rolname = ANY($1)", + &[&names], + ) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default(); + let members = su + .client + .query_one( + "SELECT string_agg(concat_ws('|', r.rolname, m.rolname, a.admin_option, \ + a.inherit_option, a.set_option), E'\\n' ORDER BY r.rolname, m.rolname) \ + FROM pg_catalog.pg_auth_members a \ + JOIN pg_catalog.pg_roles r ON r.oid = a.roleid \ + JOIN pg_catalog.pg_roles m ON m.oid = a.member \ + WHERE r.rolname = ANY($1) OR m.rolname = ANY($1)", + &[&names], + ) + .await + .unwrap() + .get::<_, Option>(0) + .unwrap_or_default(); + let database = su + .client + .query_opt( + "SELECT concat_ws('|', datname, pg_catalog.pg_get_userbyid(datdba), \ + datallowconn, coalesce(datacl::text, '')) \ + FROM pg_catalog.pg_database WHERE datname = $1", + &[&self.database()], + ) + .await + .unwrap() + .map(|row| row.get::<_, String>(0)) + .unwrap_or_else(|| "".to_owned()); + let inside = if database == "" { + String::new() + } else { + let session = self + .server + .session( + self.server.url.username(), + self.server.url.password().unwrap(), + &self.database(), + ) + .await; + let schemas = session + .text( + "SELECT string_agg(concat_ws('|', nspname, \ + pg_catalog.pg_get_userbyid(nspowner), coalesce(nspacl::text, '')), \ + E'\\n' ORDER BY nspname) \ + FROM pg_catalog.pg_namespace \ + WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'", + ) + .await; + let extensions = session + .text( + "SELECT string_agg(extname, ',' ORDER BY extname) \ + FROM pg_catalog.pg_extension", + ) + .await; + format!("{schemas}\n{extensions}") + }; + let snapshot = format!("{roles}\n--\n{members}\n--\n{database}\n--\n{inside}"); + snapshot + .replace(&self.database(), "") + .replace(&self.migration_name(), "") + .replace(&self.runtime_name(), "") + .replace(&self.bbox_name(), "") + .replace(&self.admin_name(), "") + } + + async fn role_exists(&self, role: &str) -> bool { + self.server + .superuser + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = '{role}')" + )) + .await + } + + async fn database_exists(&self) -> bool { + self.server + .superuser + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{}')", + self.database() + )) + .await + } + + async fn cleanup(self) { + let su = &self.server.superuser; + su.exec(&format!( + "DROP DATABASE IF EXISTS {} WITH (FORCE)", + quote(&self.database()) + )) + .await; + for role in [ + self.migration_name(), + self.runtime_name(), + self.bbox_name(), + self.admin_name(), + ] { + su.exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + } + } +} + +async fn count_records(session: &Raw) -> String { + session.text("SELECT count(*)::text FROM records").await +} + +async fn lock() -> tokio::sync::MutexGuard<'static, ()> { + SERIAL.lock().await +} + +fn outcome_of(outcome: &Outcome, step: &str) -> StatementOutcome { + outcome + .statements + .iter() + .find(|(name, _)| *name == step) + .unwrap_or_else(|| panic!("no outcome for {step}")) + .1 +} + +fn created(outcome: &Outcome) -> Vec<&'static str> { + outcome + .statements + .iter() + .filter(|(_, result)| *result == StatementOutcome::Created) + .map(|(step, _)| *step) + .collect() +} + +// ---- A.13 test 4 ---------------------------------------------------------- + +#[tokio::test] +async fn provision_twice_leaves_the_same_catalog() { + let _serial = lock().await; + for product in Fixture::layouts() { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "role.migration"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "role.runtime"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "database.create"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "database.grant-connect"), + StatementOutcome::Applied + ); + let after_first = fixture.snapshot().await; + assert!(after_first.contains(""), "{after_first}"); + + let second = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&second), Vec::<&str>::new(), "{product:?}"); + assert_eq!( + outcome_of(&second, "role.migration"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "role.runtime"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "database.create"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "database.revoke-public"), + StatementOutcome::Applied + ); + assert_eq!( + first + .statements + .iter() + .map(|(step, _)| *step) + .collect::>(), + second + .statements + .iter() + .map(|(step, _)| *step) + .collect::>() + ); + assert_eq!(after_first, fixture.snapshot().await, "{product:?}"); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn schema_work_converges_by_object() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::owned_product(); + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "extension.btree-gist"), + StatementOutcome::Created + ); + let schemas: Vec<_> = first + .statements + .iter() + .filter(|(step, _)| *step == "schema.owned") + .map(|(_, result)| *result) + .collect(); + assert_eq!(schemas, vec![StatementOutcome::Created; 2]); + let second = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&second, "extension.btree-gist"), + StatementOutcome::Present + ); + let schemas: Vec<_> = second + .statements + .iter() + .filter(|(step, _)| *step == "schema.owned") + .map(|(_, result)| *result) + .collect(); + assert_eq!(schemas, vec![StatementOutcome::Present; 2]); + fixture.cleanup().await; +} + +// ---- A.13 test 5 ---------------------------------------------------------- + +#[tokio::test] +async fn non_superuser_administrator_provisions() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let su = &fixture.server.superuser; + let attributes = su + .text(&format!( + "SELECT concat_ws('|', rolsuper, rolcreaterole, rolcreatedb, rolbypassrls, \ + rolreplication) \ + FROM pg_catalog.pg_roles WHERE rolname = '{}'", + fixture.admin_name() + )) + .await; + assert_eq!(attributes, "f|t|t|f|f"); + + let outcome = fixture.provision(&Fixture::owned_product()).await.unwrap(); + assert!(!outcome.single_role); + assert_eq!( + outcome_of(&outcome, "schema.owned"), + StatementOutcome::Created + ); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture.cleanup().await; +} + +// ---- A.11: split roles, forced row-level security --------------------------- + +#[tokio::test] +async fn split_roles_hold_only_what_the_plan_grants() { + let _serial = lock().await; + for product in Fixture::layouts() { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&product).await.unwrap(); + let su = &fixture.server.superuser; + let (m, r, db) = ( + fixture.migration_name(), + fixture.runtime_name(), + fixture.database(), + ); + for role in [&m, &r] { + let attributes = su + .text(&format!( + "SELECT concat_ws('|', rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, \ + rolinherit, rolbypassrls, rolreplication) \ + FROM pg_catalog.pg_roles WHERE rolname = '{role}'" + )) + .await; + assert_eq!(attributes, "t|f|f|f|f|f|f", "{role}"); + } + assert!( + su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'CONNECT')" + )) + .await + ); + assert!( + su.flag(&format!( + "SELECT has_database_privilege('{m}', '{db}', 'CONNECT')" + )) + .await + ); + assert!( + !su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'CREATE')" + )) + .await + ); + assert!( + !su.flag(&format!( + "SELECT has_database_privilege('{r}', '{db}', 'TEMPORARY')" + )) + .await, + "PUBLIC temporary access is revoked" + ); + let acl = su + .text(&format!( + "SELECT datacl::text FROM pg_catalog.pg_database WHERE datname = '{db}'" + )) + .await; + assert!( + !acl.split(',') + .any(|entry| entry.trim_start_matches('{').starts_with('=')), + "no PUBLIC entry remains: {acl}" + ); + let wants_create = matches!(product.layout, SchemaLayout::CreatedByApply); + assert_eq!( + su.flag(&format!( + "SELECT has_database_privilege('{m}', '{db}', 'CREATE')" + )) + .await, + wants_create, + "{product:?}" + ); + match &product.layout { + SchemaLayout::Owned(schemas) => { + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &db, + ) + .await; + for schema in schemas { + let owner = session + .text(&format!( + "SELECT pg_catalog.pg_get_userbyid(nspowner) FROM pg_catalog.pg_namespace \ + WHERE nspname = '{schema}'" + )) + .await; + assert_eq!(owner, m); + assert!( + !session + .flag(&format!( + "SELECT has_schema_privilege('{r}', '{schema}', 'USAGE')" + )) + .await, + "the runtime role gets nothing on {schema}" + ); + } + } + SchemaLayout::PublicForMigration => { + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &db, + ) + .await; + assert!( + session + .flag(&format!( + "SELECT has_schema_privilege('{m}', 'public', 'CREATE')" + )) + .await + ); + assert!( + !session + .flag(&format!( + "SELECT has_schema_privilege('{r}', 'public', 'CREATE')" + )) + .await + ); + } + SchemaLayout::CreatedByApply => {} + } + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn provisioned_roles_are_bound_by_forced_row_level_security() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + let migration = fixture + .server + .session( + &fixture.migration_name(), + &fixture.migration_password, + &fixture.database(), + ) + .await; + let runtime = fixture + .server + .session( + &fixture.runtime_name(), + &fixture.runtime_password, + &fixture.database(), + ) + .await; + migration + .exec("CREATE TABLE records (id int PRIMARY KEY, visible bool NOT NULL)") + .await; + migration + .exec("INSERT INTO records VALUES (1, true), (2, false)") + .await; + migration + .exec(&format!( + "GRANT SELECT ON records TO {}", + quote(&fixture.runtime_name()) + )) + .await; + migration + .exec("ALTER TABLE records ENABLE ROW LEVEL SECURITY") + .await; + migration + .exec("CREATE POLICY only_visible ON records FOR SELECT USING (visible)") + .await; + // The owner is exempt from a policy that is not forced. + assert_eq!(count_records(&migration).await, "2"); + assert_eq!(count_records(&runtime).await, "1"); + migration + .exec("ALTER TABLE records FORCE ROW LEVEL SECURITY") + .await; + // Neither role bypasses row-level security, so forcing it binds the owner too. + assert_eq!(count_records(&migration).await, "1"); + assert_eq!(count_records(&runtime).await, "1"); + let denied = runtime + .client + .batch_execute("CREATE TABLE elsewhere (id int)") + .await + .unwrap_err(); + assert_eq!(denied.code().map(|code| code.code()), Some("42501")); + drop((migration, runtime)); + fixture.cleanup().await; +} + +#[tokio::test] +async fn single_role_mode_creates_one_role() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let target = fixture.single_role_target(); + let plan = plan(&Fixture::public_product(), &target).unwrap(); + assert!(plan.single_role()); + let outcome = execute(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap(); + assert!(outcome.single_role); + assert!(outcome + .statements + .iter() + .all(|(step, _)| *step != "role.runtime")); + assert!(fixture.role_exists(&fixture.migration_name()).await); + assert!(!fixture.role_exists(&fixture.runtime_name()).await); + verify_logins(&fixture.admin(), &target).await.unwrap(); + fixture.cleanup().await; +} + +// ---- A.13 test 6 ---------------------------------------------------------- + +#[tokio::test] +async fn administrator_without_createdb_is_told_the_statement() { + let _serial = lock().await; + let fixture = Fixture::new("CREATEROLE").await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("database.create")); + match &error { + ProvisionError::StatementNeedsPrivilege { + needs, + scope, + database, + .. + } => { + assert_eq!(*needs, Needs::CreateDb); + assert_eq!(*scope, Scope::Server); + assert_eq!(database, &fixture.database()); + } + other => panic!("unexpected error {other:?}"), + } + assert_eq!( + error.to_string(), + "the administrator role cannot run CREATE DATABASE in the server; it needs CREATEDB" + ); + assert!(!fixture.database_exists().await); + fixture.cleanup().await; +} + +#[tokio::test] +async fn administrator_without_createrole_is_told_the_first_statement() { + let _serial = lock().await; + let fixture = Fixture::new("").await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("role.migration")); + assert_eq!( + error.to_string(), + "the administrator role cannot run CREATE ROLE in the server; it needs CREATEROLE" + ); + assert!(!fixture.role_exists(&fixture.migration_name()).await); + fixture.cleanup().await; +} + +// ---- A.13 test 7 ---------------------------------------------------------- + +#[tokio::test] +async fn postgis_without_superuser_names_the_extension_statement() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + assert_eq!(error.step(), Some("extension.postgis")); + match &error { + ProvisionError::StatementNeedsPrivilege { + needs, + scope, + database, + .. + } => { + assert_eq!(*needs, Needs::Superuser); + assert_eq!(*scope, Scope::Database); + assert_eq!(database, &fixture.database()); + } + other => panic!("unexpected error {other:?}"), + } + assert_eq!( + error.to_string(), + format!( + "the administrator role cannot run CREATE EXTENSION postgis in database \"{}\"; \ + it needs a superuser", + fixture.database() + ) + ); + + // A superuser runs the one statement the error names, from the plan. + let plan = plan(&product, &fixture.target()).unwrap(); + let statement = plan + .statements() + .iter() + .find(|statement| statement.step == "extension.postgis") + .unwrap(); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec(&statement.printable).await; + drop(session); + + let outcome = execute(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap(); + assert_eq!( + outcome_of(&outcome, "extension.postgis"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&outcome, "schema.owned"), + StatementOutcome::Present + ); + fixture.cleanup().await; +} + +#[tokio::test] +async fn postgis_is_created_when_the_administrator_is_a_superuser() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let first = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&first, "extension.postgis"), + StatementOutcome::Created + ); + assert_eq!( + outcome_of(&first, "role.spatial-bbox"), + StatementOutcome::Created + ); + let second = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&second, "extension.postgis"), + StatementOutcome::Present + ); + assert_eq!( + outcome_of(&second, "role.spatial-bbox"), + StatementOutcome::Present + ); + + // An installed PostGIS below the product's minimum is named, not skipped. + let too_new = fixture.spatial_product((99, 0)); + let error = fixture.provision(&too_new).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-too-old"); + assert_eq!(error.step(), Some("extension.postgis")); + fixture.cleanup().await; +} + +// ---- A.13 test 8 ---------------------------------------------------------- + +#[tokio::test] +async fn existing_role_with_other_attributes_is_refused() { + let _serial = lock().await; + let differing = [ + ("LOGIN CREATEDB", "role.migration", true), + ("LOGIN CREATEROLE", "role.migration", true), + ("LOGIN REPLICATION", "role.migration", true), + ("LOGIN BYPASSRLS", "role.migration", true), + ("LOGIN INHERIT", "role.migration", true), + ("NOLOGIN", "role.migration", true), + ("LOGIN CREATEDB", "role.runtime", false), + ("LOGIN SUPERUSER", "role.runtime", false), + ("LOGIN BYPASSRLS", "role.runtime", false), + ]; + for (attributes, step, migration) in differing { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = if migration { + fixture.migration_name() + } else { + fixture.runtime_name() + }; + let before = "SELECT concat_ws('|', rolcanlogin, rolcreatedb, rolcreaterole, rolinherit, \ + rolbypassrls, rolreplication) FROM pg_catalog.pg_roles WHERE rolname = "; + fixture + .server + .superuser + .exec(&format!("CREATE ROLE {} {attributes}", quote(&role))) + .await; + let stored = fixture + .server + .superuser + .text(&format!("{before}'{role}'")) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!( + error.code(), + "platform.provision.role-attributes-differ", + "{attributes}" + ); + assert_eq!(error.step(), Some(step)); + assert!(error.to_string().contains(&role)); + assert_eq!( + fixture + .server + .superuser + .text(&format!("{before}'{role}'")) + .await, + stored, + "the existing role is never altered" + ); + assert!( + !fixture.database_exists().await, + "nothing runs after a refusal" + ); + fixture + .server + .superuser + .exec(&format!( + "DROP ROLE IF EXISTS {}", + quote(&fixture.migration_name()) + )) + .await; + fixture.cleanup().await; + } +} + +async fn memberships(fixture: &Fixture, role: &str) -> String { + fixture + .server + .superuser + .text(&format!( + "SELECT string_agg(concat_ws('|', g.rolname, a.admin_option, a.inherit_option, \ + a.set_option), ',' ORDER BY g.rolname) \ + FROM pg_catalog.pg_auth_members a \ + JOIN pg_catalog.pg_roles g ON g.oid = a.roleid \ + JOIN pg_catalog.pg_roles m ON m.oid = a.member \ + WHERE m.rolname = '{role}' AND m.rolname = '{role}'" + )) + .await +} + +#[tokio::test] +async fn an_existing_role_that_is_a_member_of_another_role_is_refused_and_left_alone() { + let _serial = lock().await; + let cases = [ + ("pg_read_all_data", "role.runtime", false), + ("pg_execute_server_program", "role.migration", true), + ]; + for (granted, step, migration) in cases { + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = if migration { + fixture.migration_name() + } else { + fixture.runtime_name() + }; + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + GRANT {granted} TO {} WITH INHERIT TRUE", + quote(&role), + quote(&role) + )) + .await; + let before = memberships(&fixture, &role).await; + assert!(before.contains(granted), "{before}"); + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!( + error.code(), + "platform.provision.role-membership-differs", + "{granted}" + ); + assert_eq!(error.step(), Some(step)); + assert!(error.to_string().contains(&role)); + assert!(!error.to_string().contains(granted)); + assert_eq!(memberships(&fixture, &role).await, before, "left alone"); + assert!(!fixture.database_exists().await, "nothing runs after it"); + fixture + .server + .superuser + .exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn an_existing_role_with_members_or_the_plans_own_grants_is_accepted() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + fixture.provision(&product).await.unwrap(); + // The runtime role gains a member, and the migration role is already in + // the bbox role: neither is a refusal. + let member = format!("s2_member_{}", fixture.suffix); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} NOLOGIN; GRANT {} TO {}", + quote(&member), + quote(&fixture.runtime_name()), + quote(&member) + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); + fixture + .server + .superuser + .exec(&format!("DROP ROLE {}", quote(&member))) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn an_existing_role_with_a_role_level_search_path_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let role = fixture.runtime_name(); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ + ALTER ROLE {} SET search_path = pg_catalog", + quote(&role), + quote(&role) + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-settings-differ"); + assert_eq!(error.step(), Some("role.runtime")); + assert!(error.to_string().contains(&role)); + assert!( + !fixture.database_exists().await, + "nothing runs after a refusal" + ); + fixture + .server + .superuser + .exec(&format!("DROP ROLE IF EXISTS {}", quote(&role))) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_search_path_set_for_the_role_in_the_product_database_is_refused_on_a_rerun() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let role = quote(&fixture.runtime_name()); + // A setting for another database does not touch this one. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} IN DATABASE postgres SET search_path = pg_catalog" + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} IN DATABASE {} SET search_path = pg_catalog", + quote(&fixture.database()) + )) + .await; + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-settings-differ"); + assert_eq!(error.step(), Some("role.runtime")); + fixture + .server + .superuser + .exec(&format!("ALTER ROLE {role} IN DATABASE postgres RESET ALL")) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_rerun_converges_over_role_settings_that_do_not_redirect_the_session() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let role = quote(&fixture.runtime_name()); + // The settings an operator puts on the runtime role behind a pooler that + // drops startup options. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {role} SET idle_in_transaction_session_timeout = '120s'; \ + ALTER ROLE {role} SET jit = off; \ + ALTER ROLE {role} IN DATABASE {} SET statement_timeout = '30s'", + quote(&fixture.database()) + )) + .await; + let again = fixture.provision(&product).await.unwrap(); + assert_eq!(created(&again), Vec::<&str>::new()); + fixture.cleanup().await; +} + +#[tokio::test] +async fn an_existing_bbox_role_with_login_or_membership_is_refused() { + let _serial = lock().await; + let plain = "NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS"; + for (attributes, grant) in [("LOGIN", false), ("NOLOGIN", true)] { + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + let bbox = fixture.bbox_name(); + fixture + .server + .superuser + .exec(&format!( + "CREATE ROLE {} {attributes} {plain}", + quote(&bbox) + )) + .await; + if grant { + fixture + .server + .superuser + .exec(&format!("GRANT pg_read_all_data TO {}", quote(&bbox))) + .await; + } + let error = fixture + .provision(&fixture.spatial_product((3, 5))) + .await + .unwrap_err(); + let expected = if grant { + "platform.provision.role-membership-differs" + } else { + "platform.provision.role-attributes-differ" + }; + assert_eq!(error.code(), expected, "{attributes}"); + assert_eq!(error.step(), Some("role.spatial-bbox")); + fixture.cleanup().await; + } +} + +#[tokio::test] +async fn an_existing_template_database_is_not_adopted() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!( + "CREATE DATABASE {} IS_TEMPLATE true", + quote(&fixture.database()) + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.database-is-template"); + assert_eq!(error.step(), Some("database.create")); + assert_eq!( + fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database \ + WHERE datname = '{}'", + fixture.database() + )) + .await, + "", + "the template database is untouched" + ); + fixture + .server + .superuser + .exec(&format!( + "ALTER DATABASE {} IS_TEMPLATE false", + quote(&fixture.database()) + )) + .await; + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_failure_part_way_returns_the_statements_that_ran() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let plan = plan(&product, &fixture.target()).unwrap(); + let failure = execute_recording(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap_err(); + assert_eq!(failure.error.step(), Some("extension.postgis")); + let ran: Vec<_> = failure.reached.iter().map(|(step, _)| *step).collect(); + let before_postgis: Vec<_> = plan + .statements() + .iter() + .map(|statement| statement.step) + .take_while(|step| *step != "extension.postgis") + .collect(); + assert_eq!(ran, before_postgis); + assert!(failure + .reached + .iter() + .any(|(step, outcome)| *step == "role.migration" && *outcome == StatementOutcome::Created)); + fixture.cleanup().await; +} + +#[tokio::test] +async fn postgis_installed_outside_the_plan_is_named_until_the_whole_block_has_run() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = fixture.spatial_product((3, 5)); + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + + // A superuser installs only the extension, without the grants and the + // bbox membership the rest of the block sets up. + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session + .exec( + "CREATE SCHEMA registry_spatial_ext; \ + CREATE EXTENSION postgis WITH SCHEMA registry_spatial_ext", + ) + .await; + let error = fixture.provision(&product).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-incomplete"); + assert_eq!(error.step(), Some("extension.postgis")); + + // The whole printed block, then provision again. + let plan = plan(&product, &fixture.target()).unwrap(); + let block = plan + .statements() + .iter() + .find(|statement| statement.step == "extension.postgis") + .unwrap(); + session.exec(&block.printable).await; + let outcome = fixture.provision(&product).await.unwrap(); + assert_eq!( + outcome_of(&outcome, "extension.postgis"), + StatementOutcome::Present + ); + assert!( + session + .flag(&format!( + "SELECT pg_catalog.pg_has_role({}::name, {}::name, 'SET')", + quote_literal(&fixture.migration_name()), + quote_literal(&fixture.bbox_name()) + )) + .await + ); + drop(session); + fixture.cleanup().await; + + // PostGIS in the default schema is no better. + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let error = fixture.provision(&product_for(&fixture)).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-needs-privilege"); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec("CREATE EXTENSION postgis").await; + let error = fixture.provision(&product_for(&fixture)).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.extension-incomplete"); + drop(session); + fixture.cleanup().await; +} + +fn product_for(fixture: &Fixture) -> ProductDatabase { + fixture.spatial_product((3, 5)) +} + +#[tokio::test] +async fn provision_gives_the_runtime_role_usage_on_public_and_restores_it() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + let product = Fixture::public_product(); + fixture.provision(&product).await.unwrap(); + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + let usage = |role: String| { + format!( + "SELECT pg_catalog.has_schema_privilege({}, 'public', 'USAGE')", + quote_literal(&role) + ) + }; + // A server whose PUBLIC lost USAGE on `public`, and a runtime role that + // lost its own. + session + .exec(&format!( + "REVOKE USAGE ON SCHEMA public FROM PUBLIC; \ + REVOKE USAGE ON SCHEMA public FROM {}", + quote(&fixture.runtime_name()) + )) + .await; + assert!(!session.flag(&usage(fixture.runtime_name())).await); + + fixture.provision(&product).await.unwrap(); + assert!(session.flag(&usage(fixture.runtime_name())).await); + assert!(session.flag(&usage(fixture.migration_name())).await); + assert!( + !session.flag(&usage("public".to_owned())).await, + "the runtime role holds USAGE directly, not through PUBLIC" + ); + let grant_option = session + .flag(&format!( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.aclexplode(nspacl) a \ + JOIN pg_catalog.pg_roles g ON g.oid = a.grantee \ + WHERE a.is_grantable AND g.rolname IN ({}, {})) \ + FROM pg_catalog.pg_namespace WHERE nspname = 'public'", + quote_literal(&fixture.migration_name()), + quote_literal(&fixture.runtime_name()) + )) + .await; + assert!(!grant_option, "no role holds a grant option on public"); + drop(session); + fixture.cleanup().await; +} + +#[tokio::test] +async fn existing_database_owned_by_another_role_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!("CREATE DATABASE {}", quote(&fixture.database()))) + .await; + let acl_before = fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database WHERE datname = '{}'", + fixture.database() + )) + .await; + let error = fixture + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.database-owner-differs"); + assert_eq!(error.step(), Some("database.create")); + assert_eq!( + acl_before, + fixture + .server + .superuser + .text(&format!( + "SELECT coalesce(datacl::text, '') FROM pg_catalog.pg_database \ + WHERE datname = '{}'", + fixture.database() + )) + .await + ); + fixture.cleanup().await; +} + +#[tokio::test] +async fn existing_schema_owned_by_another_role_is_refused() { + let _serial = lock().await; + let fixture = Fixture::new(SUPERUSER_ADMIN).await; + fixture + .server + .superuser + .exec(&format!("CREATE DATABASE {}", quote(&fixture.database()))) + .await; + let session = fixture + .server + .session( + fixture.server.url.username(), + fixture.server.url.password().unwrap(), + &fixture.database(), + ) + .await; + session.exec("CREATE SCHEMA s2_one").await; + drop(session); + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.schema-owner-differs"); + assert_eq!(error.step(), Some("schema.owned")); + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_changed_password_fails_the_login_check_for_that_role() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap(); + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} PASSWORD '{}'", + quote(&fixture.runtime_name()), + random_hex(16) + )) + .await; + // The existing role keeps its stored password, so converging reports it + // present and only the login check notices the mismatch. + let again = fixture.provision(&Fixture::public_product()).await.unwrap(); + assert_eq!( + outcome_of(&again, "role.runtime"), + StatementOutcome::Present + ); + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.role-login-failed"); + assert!(matches!( + &error, + ProvisionError::RoleLoginFailed { sqlstate: Some(state), .. } if state == "28P01" + )); + assert!(error.to_string().contains(&fixture.runtime_name())); + assert!(!error.to_string().contains(&fixture.migration_name())); + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_login_refused_for_another_reason_carries_that_sqlstate() { + let _serial = lock().await; + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + fixture.provision(&Fixture::public_product()).await.unwrap(); + for (alter, sqlstate) in [("NOLOGIN", "28000"), ("LOGIN CONNECTION LIMIT 0", "53300")] { + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} {alter}", + quote(&fixture.runtime_name()) + )) + .await; + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + assert!( + matches!( + &error, + ProvisionError::RoleLoginFailed { sqlstate: Some(state), .. } if state == sqlstate + ), + "{alter}: {error:?}" + ); + } + fixture.cleanup().await; +} + +#[tokio::test] +async fn a_database_session_that_cannot_open_reports_the_statements_that_already_ran() { + let _serial = lock().await; + // One connection is the server session the run keeps open, so the session + // in the new database cannot open. + let fixture = Fixture::new("CREATEROLE CREATEDB CONNECTION LIMIT 1").await; + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + let failure = execute_recording(&fixture.admin(), &plan, Mode::Converge) + .await + .unwrap_err(); + assert_eq!( + failure.error.code(), + "platform.provision.database-connect-failed" + ); + assert!(failure.error.may_have_run_statements()); + let message = failure.error.to_string(); + assert!(message.contains(&fixture.database()), "{message}"); + assert!(message.contains("53300"), "{message}"); + let steps: Vec<&str> = failure.reached.iter().map(|(step, _)| *step).collect(); + assert_eq!( + steps, + [ + "role.migration", + "role.runtime", + "database.create", + "database.revoke-public", + "database.grant-connect", + "database.allow-connections" + ] + ); + assert!( + fixture.database_exists().await, + "the statements listed as run took effect" + ); + fixture.cleanup().await; +} + +// ---- A.13 test 9 ---------------------------------------------------------- + +fn unquote(identifier: &str) -> String { + identifier + .trim() + .trim_start_matches('"') + .trim_end_matches('"') + .replace("\"\"", "\"") +} + +/// Runs a printed script the way `psql` does: a `\connect` opens a new +/// session that has none of the earlier `SET`s, and `\password` sets the +/// password the administrator would have typed. +async fn run_script(fixture: &Fixture, script: &str) { + let server = &fixture.server; + let mut session = server + .session(&fixture.admin_name(), &fixture.admin_password, "postgres") + .await; + let mut pending = String::new(); + for line in script.lines() { + if pending.is_empty() && line.starts_with("--") { + continue; + } + if line.starts_with("\\set ") { + continue; + } + if let Some(database) = line.strip_prefix("\\connect ") { + session = server + .session( + &fixture.admin_name(), + &fixture.admin_password, + &unquote(database), + ) + .await; + continue; + } + if let Some(role) = line.strip_prefix("\\password ") { + let role = unquote(role); + let password = if role == fixture.migration_name() { + &fixture.migration_password + } else { + &fixture.runtime_password + }; + session + .exec(&format!( + "ALTER ROLE {} PASSWORD '{password}'", + quote(&role) + )) + .await; + continue; + } + pending.push_str(line); + pending.push('\n'); + if line.ends_with(';') { + session.exec(&pending).await; + pending.clear(); + } + } + assert!(pending.is_empty(), "the script ends inside a statement"); +} + +#[tokio::test] +async fn printed_script_gives_the_same_catalog() { + let _serial = lock().await; + for product in Fixture::layouts() { + let executed = Fixture::new(NON_SUPERUSER_ADMIN).await; + executed.provision(&product).await.unwrap(); + + let scripted = Fixture::new(NON_SUPERUSER_ADMIN).await; + let script = render_script(&plan(&product, &scripted.target()).unwrap()); + run_script(&scripted, &script).await; + verify_logins(&scripted.admin(), &scripted.target()) + .await + .unwrap(); + + assert_eq!( + executed.snapshot().await, + scripted.snapshot().await, + "{product:?}" + ); + executed.cleanup().await; + scripted.cleanup().await; + } +} + +// ---- Floor ------------------------------------------------------------------ + +#[tokio::test] +async fn server_below_the_floor_is_refused_before_any_statement() { + let _serial = lock().await; + let old = Server::start("PROVISION_TEST_OLD_DATABASE_URL").await; + let version: i32 = old + .superuser + .text("SELECT current_setting('server_version_num')") + .await + .parse() + .unwrap(); + assert!(version < 170_000, "the old server must be below the floor"); + let fixture = Fixture::on(old, SUPERUSER_ADMIN).await; + let error = fixture + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.unsupported-postgres"); + assert_eq!(error.step(), None); + assert!( + error + .to_string() + .starts_with("PostgreSQL 17 or newer is required"), + "{error}" + ); + assert!(!fixture.role_exists(&fixture.migration_name()).await); + assert!(!fixture.database_exists().await); + + // Fresh mode is for a server the caller just made, and does not check. + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + execute(&fixture.admin(), &plan, Mode::Fresh).await.unwrap(); + assert!(fixture.database_exists().await); + fixture.cleanup().await; +} + +// ---- A.13 test 11 ----------------------------------------------------------- + +/// Every rendering of a value the caller could print or log. +fn renderings(error: &(dyn std::error::Error + 'static)) -> Vec { + let mut texts = vec![ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ]; + let mut source = error.source(); + while let Some(cause) = source { + texts.push(format!("{cause}")); + texts.push(format!("{cause:?}")); + source = cause.source(); + } + texts +} + +fn assert_clean(texts: &[String], secrets: &[String]) { + for text in texts { + for secret in secrets { + assert!(!secret.is_empty()); + assert!(!text.contains(secret.as_str()), "a secret reached: {text}"); + } + assert!( + !text.contains("SCRAM-SHA-256$"), + "a verifier reached: {text}" + ); + assert!(!text.contains("postgresql://"), "a URL reached: {text}"); + assert!(!text.contains("PASSWORD"), "statement text reached: {text}"); + } +} + +#[tokio::test] +async fn error_text_never_contains_a_password_a_verifier_or_a_url() { + let _serial = lock().await; + let mut texts: Vec = Vec::new(); + + // A CREATE ROLE statement that carries a verifier and is refused. + let without_createrole = Fixture::new("").await; + let mut secrets = vec![ + without_createrole.admin_password.clone(), + without_createrole.migration_password.clone(), + without_createrole.runtime_password.clone(), + without_createrole.admin_url(), + ]; + let error = without_createrole + .provision(&Fixture::owned_product()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + without_createrole.cleanup().await; + + // A statement that fails on the server with a verifier in its text, and + // the verifiers the server stores. + let fixture = Fixture::new(NON_SUPERUSER_ADMIN).await; + secrets.extend([ + fixture.admin_password.clone(), + fixture.migration_password.clone(), + fixture.runtime_password.clone(), + fixture.admin_url(), + ]); + let success = fixture.provision(&Fixture::public_product()).await.unwrap(); + texts.push(format!("{success:?}")); + for role in [fixture.migration_name(), fixture.runtime_name()] { + secrets.push( + fixture + .server + .superuser + .text(&format!( + "SELECT rolpassword FROM pg_catalog.pg_authid WHERE rolname = '{role}'" + )) + .await, + ); + } + let plan = plan(&Fixture::public_product(), &fixture.target()).unwrap(); + texts.push(format!("{plan:?}")); + texts.push(format!("{:?}", fixture.target())); + texts.push(format!("{:?}", fixture.admin())); + texts.push(render_script(&plan)); + let error = execute(&fixture.admin(), &plan, Mode::Fresh) + .await + .unwrap_err(); + assert_eq!(error.code(), "platform.provision.statement-failed"); + assert_eq!(error.step(), Some("role.migration")); + texts.extend(renderings(&error)); + + // A refused existing role. + let other = Fixture::new(NON_SUPERUSER_ADMIN).await; + secrets.extend([ + other.migration_password.clone(), + other.runtime_password.clone(), + ]); + other + .server + .superuser + .exec(&format!( + "CREATE ROLE {} LOGIN CREATEDB", + quote(&other.migration_name()) + )) + .await; + let error = other + .provision(&Fixture::public_product()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + other.cleanup().await; + + // A wrong administrator password. + let wrong = random_hex(16); + secrets.push(wrong.clone()); + let mut url = Url::parse(&fixture.admin_url()).unwrap(); + url.set_password(Some(&wrong)).unwrap(); + secrets.push(url.to_string()); + let admin = admin_config(url.as_str(), Some(&fixture.server.ca)).unwrap(); + let error = execute(&admin, &plan, Mode::Converge).await.unwrap_err(); + assert_eq!(error.code(), "platform.provision.admin-connect-failed"); + assert!(matches!( + &error, + ProvisionError::AdminConnectFailed { sqlstate: Some(state) } if state == "28P01" + )); + texts.extend(renderings(&error)); + + // A changed password. + fixture + .server + .superuser + .exec(&format!( + "ALTER ROLE {} PASSWORD '{}'", + quote(&fixture.migration_name()), + random_hex(16) + )) + .await; + let error = verify_logins(&fixture.admin(), &fixture.target()) + .await + .unwrap_err(); + texts.extend(renderings(&error)); + + // A URL the executor refuses to read. + let error: AdminConfigError = admin_config( + &format!("{}&sslmode=disable", fixture.admin_url()), + Some(&fixture.server.ca), + ) + .unwrap_err(); + texts.extend(renderings(&error)); + + assert_clean(&texts, &secrets); + fixture.cleanup().await; +} diff --git a/crates/registry-platform-testing/Cargo.toml b/crates/registry-platform-testing/Cargo.toml index d0f2a22eda..5ea7f86165 100644 --- a/crates/registry-platform-testing/Cargo.toml +++ b/crates/registry-platform-testing/Cargo.toml @@ -19,11 +19,18 @@ test-authorization-server = ["test-utils", "dep:sha2", "dep:url", "dep:uuid"] migration-pins = ["test-utils", "dep:sha2"] # Canonical PostgreSQL catalogs for migration replay-equivalence tests. postgres-catalog = ["test-utils", "dep:tokio-postgres"] +# The token fixture corpus under `products/platform/conformance/tokens`, a test-time signer and a +# closure-driven driver; see `TokenCorpus`. +token-fixtures = ["test-utils", "dep:rand", "dep:serde", "dep:registry-platform-yaml"] [[test]] name = "test_authorization_server" required-features = ["test-authorization-server"] +[[test]] +name = "token_fixtures" +required-features = ["token-fixtures"] + [dependencies] axum.workspace = true base64.workspace = true @@ -34,7 +41,10 @@ registry-platform-crypto = { workspace = true } registry-platform-httpsec = { workspace = true, features = ["server"] } registry-platform-httputil = { workspace = true } registry-platform-oidc = { workspace = true } +registry-platform-yaml = { workspace = true, optional = true } +rand = { workspace = true, optional = true } reqwest.workspace = true +serde = { workspace = true, optional = true } serde_json.workspace = true sha2 = { workspace = true, optional = true } thiserror.workspace = true diff --git a/crates/registry-platform-testing/README.md b/crates/registry-platform-testing/README.md index ffff7fed95..20301e791b 100644 --- a/crates/registry-platform-testing/README.md +++ b/crates/registry-platform-testing/README.md @@ -138,6 +138,27 @@ response with: - `jwks_from_private_jwk(private)`: return `{"keys": [public]}` as a `serde_json::Value`; useful for mocking a JWKS endpoint. +## Token Fixtures + +The `token-fixtures` feature (off by default) loads the corpus in +`products/platform/conformance/tokens` and drives a product's authentication +with it. The path comes from this crate's manifest directory. + +- `TokenCorpus::load()` reads and validates every fixture and `expected.yaml`. +- `TokenSigner::new()` makes a fresh key per algorithm (RS256, ES256, EdDSA, HS256, + HS512) in memory only. `sign` signs a fixture's header and claims with its + declared algorithm, times as offsets from now. `public_key_set()` holds the + asymmetric public keys. `SignedToken` never prints its text in `Debug`. +- `TokenCorpus::run_product` (and `run_product_async`) takes the product's + authenticator as a closure from `&FixtureCase` to `Outcome`, runs every + applicable row, and returns a `ProductReport` compared with the product's + column of `expected.yaml`. A row asserts `target` where `landed` is true and + `main` otherwise. + +```bash +cargo test -p registry-platform-testing --features token-fixtures +``` + ## Fixture Notes - Fixtures are deterministic and intended for tests only. diff --git a/crates/registry-platform-testing/src/diagnostic_capture.rs b/crates/registry-platform-testing/src/diagnostic_capture.rs index 8ea00768db..9bfb92863b 100644 --- a/crates/registry-platform-testing/src/diagnostic_capture.rs +++ b/crates/registry-platform-testing/src/diagnostic_capture.rs @@ -54,29 +54,6 @@ impl CapturedDiagnosticLogs { .finish(), ) } - - /// Assert that the capture holds exactly one header-stage diagnostic and - /// that it renders none of the supplied credentials. - /// - /// # Panics - /// - /// Panics when the capture is not one value-free header diagnostic. - pub fn assert_one_value_free_header_diagnostic(&self, tokens: &[String]) { - let rendered = self.text(); - assert_eq!( - rendered.lines().count(), - 1, - "one bounded diagnostic per header stage" - ); - assert!(rendered.contains(r#""stage":"header""#)); - assert!(!rendered.contains("canary")); - for token in tokens.iter().filter(|token| !token.is_empty()) { - assert!( - !rendered.contains(token), - "diagnostics must not contain credentials" - ); - } - } } impl Write for CapturedDiagnosticLogs { diff --git a/crates/registry-platform-testing/src/lib.rs b/crates/registry-platform-testing/src/lib.rs index fde20482a8..f5d814b7a6 100644 --- a/crates/registry-platform-testing/src/lib.rs +++ b/crates/registry-platform-testing/src/lib.rs @@ -24,6 +24,16 @@ pub use migration_pins::{assert_migration_pins, verify_migration_pins, MIGRATION #[cfg(feature = "postgres-catalog")] mod postgres_catalog; +#[cfg(feature = "token-fixtures")] +mod token_fixtures; + +#[cfg(feature = "token-fixtures")] +pub use token_fixtures::{ + Against, Basis, BindTarget, Binding, ClaimValue, Comparison, Configuration, Expectations, + ExpectedCell, ExpectedRow, FixtureCase, FixtureClass, FixtureHeader, Outcome, ProductReport, + RowReport, SignedToken, Stage, TokenCorpus, TokenFixture, TokenFixtureError, TokenSigner, +}; + #[cfg(feature = "postgres-catalog")] pub use postgres_catalog::verify_postgres_schema_equivalence; @@ -518,7 +528,7 @@ mod tests { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("discovery fetch succeeds"); @@ -534,7 +544,7 @@ mod tests { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut config = oidc_verifier_config(idp.issuer(), vec!["registry-api".to_string()]); config.allowed_clients = vec!["client-a".to_string()]; diff --git a/crates/registry-platform-testing/src/token_fixtures.rs b/crates/registry-platform-testing/src/token_fixtures.rs new file mode 100644 index 0000000000..518b6fb886 --- /dev/null +++ b/crates/registry-platform-testing/src/token_fixtures.rs @@ -0,0 +1,1310 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The token fixture corpus, a test-time signer and a closure-driven driver. +//! +//! The corpus lives in `products/platform/conformance/tokens`: one decoded token +//! shape per file under `fixtures/`, and `expected.yaml` with the expected result +//! for every fixture, product and configuration. A fixture holds no signature and +//! no key. [`TokenSigner`] makes a fresh key per algorithm when it is built, keeps +//! it in memory only, and signs a fixture's header and claims with the algorithm +//! the fixture declares. [`TokenCorpus::run_product`] takes a product's +//! authentication as a closure, runs every applicable fixture through it, and +//! compares the results with `expected.yaml` for that product. +//! +//! A product's test depends on this crate and passes its own authenticator in, so +//! no product depends on another. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt, + future::Future, + path::{Path, PathBuf}, + str::FromStr, + time::{SystemTime, UNIX_EPOCH}, +}; + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use futures::FutureExt as _; +use jsonwebtoken::{crypto, Algorithm, DecodingKey, EncodingKey}; +use rand::Rng as _; +use registry_platform_crypto::jws::sign_compact_jws; +use registry_platform_crypto::{ + generate_private_jwk, verify as verify_with_public_jwk, GeneratedKeyAlgorithm, LocalJwkSigner, + PrivateJwk, PublicJwk, +}; +use registry_platform_oidc::OidcError; +use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader}; +use serde::Deserialize; +use serde_json::{json, Map, Value}; +use thiserror::Error; + +const FIXTURE_SCHEMA: &str = "registry.token-fixture/v1"; +const EXPECTATIONS_SCHEMA: &str = "registry.token-fixture-expectations/v1"; +/// `expected.yaml` is test data with a `schema` member and no `apiVersion` or `kind` envelope. +const EXPECTATIONS_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "TokenFixtureExpectations", + envelope: EnvelopeRule::Exempt { + reason: "test data checked by the token fixture corpus tests, not a configuration file", + }, + removed_keys: &[], +}; +const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "k", "oth"]; +const SIGNING_ALGORITHMS: [&str; 5] = ["RS256", "ES256", "EdDSA", "HS256", "HS512"]; + +/// Why a corpus file did not load, validate, sign or run. +#[derive(Debug, Error)] +pub enum TokenFixtureError { + #[error("token fixture corpus: cannot read {path}: {source}")] + Io { + path: String, + source: std::io::Error, + }, + #[error("token fixture `{fixture}`: {reason}")] + Invalid { fixture: String, reason: String }, + #[error("token fixture expectations: {0}")] + Expectations(String), + #[error("token fixture `{fixture}`: cannot sign: {reason}")] + Signing { fixture: String, reason: String }, + #[error("token fixture signature: {0}")] + Verification(String), + #[error("token fixture driver: product `{0}` is not a column of expected.yaml")] + UnknownProduct(String), +} + +fn invalid(fixture: &str, reason: impl Into) -> TokenFixtureError { + TokenFixtureError::Invalid { + fixture: fixture.to_owned(), + reason: reason.into(), + } +} + +// --------------------------------------------------------------------------- +// Results +// --------------------------------------------------------------------------- + +/// The check at which a product refused a token: the shared verifier's labels, +/// and `claims` for a product's own claim extraction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Stage { + Header, + Algorithm, + TokenType, + Key, + Signature, + Issuer, + Audience, + Time, + Client, + Scope, + Profile, + Unavailable, + Claims, +} + +const STAGES: [(Stage, &str); 13] = [ + (Stage::Header, "header"), + (Stage::Algorithm, "algorithm"), + (Stage::TokenType, "token-type"), + (Stage::Key, "key"), + (Stage::Signature, "signature"), + (Stage::Issuer, "issuer"), + (Stage::Audience, "audience"), + (Stage::Time, "time"), + (Stage::Client, "client"), + (Stage::Scope, "scope"), + (Stage::Profile, "profile"), + (Stage::Unavailable, "unavailable"), + (Stage::Claims, "claims"), +]; + +impl Stage { + #[must_use] + pub fn as_str(self) -> &'static str { + STAGES + .iter() + .find(|(stage, _)| *stage == self) + .map_or("unknown-stage", |(_, name)| name) + } +} + +impl fmt::Display for Stage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// The result of running one token through one product. The text forms are the +/// values `expected.yaml` uses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// `admitted` (no actor kind) or `admitted/`, where the kind + /// may be `unspecified`. + Admitted(Option), + /// `refused/`. + Refused(Stage), + /// `none`: the configuration needs a setting the product does not have. + None, + /// `n-a`: the product has no such concept. + NotApplicable, + /// `unknown`: not determined. + Unknown, +} + +impl Outcome { + /// The characterisation result value for a verifier error, `refused/`. + /// It names the stage a corpus row records, so the expected table stays + /// comparable across products. Runtimes log and count the same refusal by + /// `FailedCheck`, not by this value. + /// + /// # Panics + /// + /// On an `OidcError` variant added without a stage here. + #[must_use] + pub fn refused_by(error: &OidcError) -> Self { + use OidcError as E; + let stage = match error { + E::MalformedToken | E::InvalidToken | E::SubjectMismatch => Stage::Header, + E::AlgorithmNotAllowed => Stage::Algorithm, + E::TokenTypeNotAllowed => Stage::TokenType, + E::MissingKid | E::KidTooLong | E::UnknownKid => Stage::Key, + E::SignatureInvalid => Stage::Signature, + E::IssuerMismatch { .. } => Stage::Issuer, + E::AudienceMismatch => Stage::Audience, + E::TokenExpired | E::TokenNotYetValid | E::InvalidTimeClaims => Stage::Time, + E::ClientNotAllowed | E::AssertionIssuerNotAllowed => Stage::Client, + E::Transport(_) + | E::BoundedRead(_) + | E::FetchUrl(_) + | E::HttpStatus(_) + | E::InvalidUrl + | E::Parse + | E::InvalidJwk + | E::EmptyKeySet + | E::StaticKeySet(_) + | E::MissingIssuer + | E::ConflictingEndpointConfiguration + | E::InsecureHttpRequiresOptIn + | E::EndpointRefused { .. } => Stage::Unavailable, + other => panic!("no characterisation stage is recorded for {other:?}"), + }; + Self::Refused(stage) + } +} + +impl fmt::Display for Outcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Admitted(None) => f.write_str("admitted"), + Self::Admitted(Some(kind)) => write!(f, "admitted/{kind}"), + Self::Refused(stage) => write!(f, "refused/{stage}"), + Self::None => f.write_str("none"), + Self::NotApplicable => f.write_str("n-a"), + Self::Unknown => f.write_str("unknown"), + } + } +} + +impl FromStr for Outcome { + type Err = String; + + fn from_str(text: &str) -> Result { + match text { + "admitted" => return Ok(Self::Admitted(None)), + "none" => return Ok(Self::None), + "n-a" => return Ok(Self::NotApplicable), + "unknown" => return Ok(Self::Unknown), + _ => {} + } + if let Some(kind) = text.strip_prefix("admitted/") { + let well_formed = !kind.is_empty() + && kind + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + return if well_formed { + Ok(Self::Admitted(Some(kind.to_owned()))) + } else { + Err(format!("`{text}` names no actor kind")) + }; + } + if let Some(stage) = text.strip_prefix("refused/") { + return STAGES + .iter() + .find(|(_, name)| *name == stage) + .map(|(stage, _)| Self::Refused(*stage)) + .ok_or_else(|| format!("`{text}` names no known stage")); + } + Err(format!("`{text}` is not a result value")) + } +} + +impl<'de> Deserialize<'de> for Outcome { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } +} + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum FixtureClass { + Positive, + Negative, +} + +/// The issuer or audience a claim takes from the product under test. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BindTarget { + Issuer, + Audience, +} + +/// A claim value: plain JSON, or one of three directives. +#[derive(Debug, Clone, PartialEq)] +pub enum ClaimValue { + Literal(Value), + Bind(BindTarget), + /// Seconds after the moment of signing. + OffsetSeconds(i64), + /// A random value made at signing time. + Generated, +} + +/// The JOSE header a fixture declares. `kid` is always generated at signing time. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FixtureHeader { + pub alg: String, + pub typ: Option, +} + +/// One decoded token shape. +#[derive(Debug, Clone, PartialEq)] +pub struct TokenFixture { + pub id: String, + pub class: FixtureClass, + pub provider: String, + pub kind: String, + pub token_use: String, + pub subject_kind: String, + /// The `source` object, kept as written. + pub source: Value, + pub header: Option, + pub claims: BTreeMap, + /// A credential that is not a JWT, as a synthetic string. + pub opaque: Option, + pub omits: Vec, + pub notes: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RawFixture { + schema: String, + id: String, + class: FixtureClass, + provider: String, + kind: String, + token_use: String, + subject_kind: String, + source: Value, + header: Option, + claims: Option>, + opaque: Option, + omits: Option>, + notes: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawHeader { + alg: String, + typ: Option, + kid: Value, +} + +/// OpenID Connect scopes. They select a claim set for the person. No product +/// profile requires one of them as a permission. +const OPENID_CONNECT_SCOPES: [&str; 6] = [ + "openid", + "profile", + "email", + "address", + "phone", + "offline_access", +]; + +impl TokenFixture { + /// The first value of the claim `claim` that is not an OpenID Connect + /// scope: a space-separated string, or the first string of an array. `None` + /// when the claim is absent or holds only OpenID Connect scopes. + #[must_use] + pub fn read_scope(&self, claim: &str) -> Option { + match self.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => text + .split_whitespace() + .find(|scope| !OPENID_CONNECT_SCOPES.contains(scope)) + .map(str::to_owned), + Some(ClaimValue::Literal(Value::Array(items))) => items + .iter() + .filter_map(Value::as_str) + .find(|scope| !OPENID_CONNECT_SCOPES.contains(scope)) + .map(str::to_owned), + _ => None, + } + } + + /// Parse and validate one fixture file. `file_stem` is the file name without + /// its extension and must equal the fixture's `id`. + pub fn parse(file_stem: &str, text: &str) -> Result { + let value: Value = serde_json::from_str(text) + .map_err(|error| invalid(file_stem, format!("not valid JSON: {error}")))?; + reject_key_material(file_stem, &value)?; + let raw: RawFixture = + serde_json::from_value(value).map_err(|error| invalid(file_stem, error.to_string()))?; + if raw.schema != FIXTURE_SCHEMA { + return Err(invalid( + file_stem, + format!("schema must be `{FIXTURE_SCHEMA}`"), + )); + } + if raw.id != file_stem { + return Err(invalid( + file_stem, + format!("id `{}` differs from the file name", raw.id), + )); + } + if raw.source.get("basis").and_then(Value::as_str).is_none() { + return Err(invalid(file_stem, "source.basis is required")); + } + let omits = raw.omits.clone().unwrap_or_default(); + let fixture = match (raw.opaque, raw.header, raw.claims) { + (Some(opaque), None, None) if omits.is_empty() && !opaque.is_empty() => { + (Some(opaque), None, BTreeMap::new()) + } + (Some(_), ..) => return Err(invalid( + file_stem, + "an opaque fixture holds no header, claims or omits, and a JWT fixture no opaque", + )), + (None, Some(header), Some(claims)) => { + let header = parse_header(file_stem, header)?; + let claims = parse_claims(file_stem, &claims)?; + (None, Some(header), claims) + } + (None, ..) => { + return Err(invalid( + file_stem, + "a fixture holds opaque, or both header and claims", + )) + } + }; + let (opaque, header, claims) = fixture; + for omitted in &omits { + if claims.contains_key(omitted) { + return Err(invalid( + file_stem, + format!("omits names claim `{omitted}`, which the fixture sets"), + )); + } + } + Ok(Self { + id: raw.id, + class: raw.class, + provider: raw.provider, + kind: raw.kind, + token_use: raw.token_use, + subject_kind: raw.subject_kind, + source: raw.source, + header, + claims, + opaque, + omits, + notes: raw.notes, + }) + } +} + +fn parse_header(fixture: &str, raw: RawHeader) -> Result { + if !SIGNING_ALGORITHMS.contains(&raw.alg.as_str()) { + return Err(invalid( + fixture, + format!( + "header alg `{}` is not one of {SIGNING_ALGORITHMS:?}", + raw.alg + ), + )); + } + if raw.kid != json!({ "generated": true }) { + return Err(invalid(fixture, "header kid must be {\"generated\": true}")); + } + Ok(FixtureHeader { + alg: raw.alg, + typ: raw.typ, + }) +} + +fn parse_claims( + fixture: &str, + raw: &Map, +) -> Result, TokenFixtureError> { + let mut claims = BTreeMap::new(); + for (name, value) in raw { + let claim = parse_claim(value) + .map_err(|reason| invalid(fixture, format!("claim `{name}`: {reason}")))?; + if matches!(name.as_str(), "exp" | "iat" | "nbf") + && !matches!(claim, ClaimValue::OffsetSeconds(_)) + { + return Err(invalid( + fixture, + format!("claim `{name}` must be an offsetSeconds directive"), + )); + } + claims.insert(name.clone(), claim); + } + if !claims.contains_key("exp") { + return Err(invalid(fixture, "claims must carry exp")); + } + Ok(claims) +} + +fn parse_claim(value: &Value) -> Result { + let Some(map) = value.as_object() else { + return Ok(ClaimValue::Literal(value.clone())); + }; + let is_directive = ["bind", "offsetSeconds", "generated"] + .iter() + .any(|key| map.contains_key(*key)); + if !is_directive { + return Ok(ClaimValue::Literal(value.clone())); + } + if map.len() != 1 { + return Err("a directive holds exactly one member".to_owned()); + } + if let Some(bind) = map.get("bind") { + return match bind.as_str() { + Some("issuer") => Ok(ClaimValue::Bind(BindTarget::Issuer)), + Some("audience") => Ok(ClaimValue::Bind(BindTarget::Audience)), + _ => Err("bind is `issuer` or `audience`".to_owned()), + }; + } + if let Some(offset) = map.get("offsetSeconds") { + return match offset.as_i64() { + Some(seconds) if seconds >= 0 => Ok(ClaimValue::OffsetSeconds(seconds)), + _ => Err("offsetSeconds is a non-negative integer".to_owned()), + }; + } + if map.get("generated") == Some(&Value::Bool(true)) { + return Ok(ClaimValue::Generated); + } + Err("generated is `true`".to_owned()) +} + +/// A fixture is never a key and never a live token: refuse a private JWK member +/// name anywhere, and any string shaped like a compact JWT. +fn reject_key_material(fixture: &str, value: &Value) -> Result<(), TokenFixtureError> { + match value { + Value::Object(map) => { + for (name, member) in map { + if PRIVATE_JWK_MEMBERS.contains(&name.as_str()) { + return Err(invalid( + fixture, + format!("holds the private JWK member name `{name}`"), + )); + } + reject_key_material(fixture, member)?; + } + } + Value::Array(items) => { + for item in items { + reject_key_material(fixture, item)?; + } + } + Value::String(text) => { + if text.starts_with("eyJ") && text.matches('.').count() == 2 { + return Err(invalid(fixture, "holds a string shaped like a compact JWT")); + } + if text.contains("PRIVATE KEY") { + return Err(invalid(fixture, "holds PEM key material")); + } + } + _ => {} + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Expectations +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Against { + PlainRead, + HumanOnlyProfile, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Configuration { + Default, + Recipe, + JwtAccepted, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Basis { + Inferred, + Observed, +} + +/// One product's cell in a row. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExpectedCell { + pub main: Outcome, + pub target: Outcome, + #[serde(deserialize_with = "change_or_none")] + pub changed_by: Option, + pub landed: Option, + pub basis: Basis, + pub reason: Option, + pub target_reason: Option, +} + +impl ExpectedCell { + /// What a test asserts: `target` where the change has landed, `main` + /// everywhere else. + #[must_use] + pub fn expected(&self) -> &Outcome { + if self.landed == Some(true) { + &self.target + } else { + &self.main + } + } +} + +/// A change name is lowercase kebab-case: `caller-contract`. +fn is_change_name(text: &str) -> bool { + let mut words = text.split('-'); + let word_ok = |word: &str| { + !word.is_empty() + && word + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }; + words + .next() + .is_some_and(|first| word_ok(first) && first.starts_with(|c: char| c.is_ascii_lowercase())) + && words.all(word_ok) +} + +fn change_or_none<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let text = String::deserialize(deserializer)?; + if text == "none" { + return Ok(None); + } + if is_change_name(&text) { + Ok(Some(text)) + } else { + Err(serde::de::Error::custom(format!( + "changedBy `{text}` is neither `none` nor a lowercase kebab-case change name like `caller-contract`" + ))) + } +} + +/// One fixture, `against` value and configuration, with a cell per product. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExpectedRow { + pub fixture: String, + pub against: Against, + pub configuration: Configuration, + pub products: BTreeMap, +} + +/// `expected.yaml`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Expectations { + pub schema: String, + pub products: Vec, + pub configurations: BTreeMap, + pub rows: Vec, +} + +// --------------------------------------------------------------------------- +// Signer +// --------------------------------------------------------------------------- + +/// The issuer and audience of the product under test, which `bind` claims take. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binding { + pub issuer: String, + pub audience: String, +} + +/// A signed token, or a synthetic opaque credential. Its `Debug` form shows no +/// token text. +#[derive(Clone)] +pub struct SignedToken { + text: String, + opaque: bool, +} + +impl SignedToken { + /// The credential as a product receives it in an `Authorization` header. + #[must_use] + pub fn expose(&self) -> &str { + &self.text + } + + #[must_use] + pub fn is_opaque(&self) -> bool { + self.opaque + } + + /// The same kind of credential with other text, for tampering tests. + #[must_use] + pub fn with_text(&self, text: String) -> Self { + Self { + text, + opaque: self.opaque, + } + } +} + +impl fmt::Debug for SignedToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SignedToken") + .field("opaque", &self.opaque) + .field("length", &self.text.len()) + .finish() + } +} + +/// Keys made when the signer is built, one per algorithm, held in memory only. +/// A product that verifies tokens is given [`TokenSigner::public_key_set`]. +pub struct TokenSigner { + rs256: PrivateJwk, + es256: PrivateJwk, + eddsa: PrivateJwk, + hs256: Vec, + hs512: Vec, +} + +impl fmt::Debug for TokenSigner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TokenSigner").finish_non_exhaustive() + } +} + +impl Default for TokenSigner { + fn default() -> Self { + Self::new() + } +} + +impl TokenSigner { + /// Make a fresh key for every algorithm. + /// + /// # Panics + /// + /// Panics if a key cannot be generated. + #[must_use] + pub fn new() -> Self { + let mut rs256 = generate_private_jwk(GeneratedKeyAlgorithm::Rs384) + .expect("ephemeral RSA test key generates"); + rs256.alg = Some("RS256".to_owned()); + let es256 = generate_private_jwk(GeneratedKeyAlgorithm::Es256) + .expect("ephemeral ES256 test key generates"); + let eddsa = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519) + .expect("ephemeral EdDSA test key generates"); + let mut hs256 = vec![0_u8; 32]; + let mut hs512 = vec![0_u8; 64]; + rand::rng().fill(hs256.as_mut_slice()); + rand::rng().fill(hs512.as_mut_slice()); + Self { + rs256, + es256, + eddsa, + hs256, + hs512, + } + } + + /// The public halves of the asymmetric keys as a key set. HMAC keys have no + /// public half and are never in it, so a product cannot verify an HS256 or + /// HS512 token from a key set. + /// + /// # Panics + /// + /// Panics if a public key cannot be serialised. + #[must_use] + pub fn public_key_set(&self) -> Value { + let keys: Vec = [&self.rs256, &self.es256, &self.eddsa] + .into_iter() + .map(|key| serde_json::to_value(key.public()).expect("public JWK serialises")) + .collect(); + json!({ "keys": keys }) + } + + fn asymmetric_key(&self, alg: &str) -> Option<&PrivateJwk> { + match alg { + "RS256" => Some(&self.rs256), + "ES256" => Some(&self.es256), + "EdDSA" => Some(&self.eddsa), + _ => None, + } + } + + fn hmac_key(&self, alg: &str) -> Option<(&[u8], Algorithm)> { + match alg { + "HS256" => Some((&self.hs256, Algorithm::HS256)), + "HS512" => Some((&self.hs512, Algorithm::HS512)), + _ => None, + } + } + + /// Sign a fixture now. Times are offsets from this moment, `bind` claims take + /// `binding`, and an opaque fixture yields its synthetic string. + pub fn sign( + &self, + fixture: &TokenFixture, + binding: &Binding, + ) -> Result { + let signing = |reason: String| TokenFixtureError::Signing { + fixture: fixture.id.clone(), + reason, + }; + if let Some(opaque) = &fixture.opaque { + return Ok(SignedToken { + text: opaque.clone(), + opaque: true, + }); + } + let header = fixture + .header + .as_ref() + .ok_or_else(|| signing("no header".to_owned()))?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| signing(error.to_string()))? + .as_secs(); + let now = i64::try_from(now).map_err(|error| signing(error.to_string()))?; + let mut claims = Map::new(); + for (name, claim) in &fixture.claims { + let value = match claim { + ClaimValue::Literal(value) => value.clone(), + ClaimValue::Bind(BindTarget::Issuer) => Value::String(binding.issuer.clone()), + ClaimValue::Bind(BindTarget::Audience) => Value::String(binding.audience.clone()), + ClaimValue::OffsetSeconds(seconds) => json!(now + seconds), + ClaimValue::Generated => Value::String(random_hex()), + }; + claims.insert(name.clone(), value); + } + let payload = serde_json::to_vec(&Value::Object(claims)) + .map_err(|error| signing(error.to_string()))?; + let mut extra_header = Map::new(); + if let Some(typ) = &header.typ { + extra_header.insert("typ".to_owned(), Value::String(typ.clone())); + } + let text = if let Some(key) = self.asymmetric_key(&header.alg) { + let signer = + LocalJwkSigner::new(key.clone()).map_err(|error| signing(error.to_string()))?; + // The signer is local, so its future is ready on the first poll. Polling it + // directly keeps signing usable from inside any executor. + sign_compact_jws(extra_header, &payload, &signer) + .now_or_never() + .ok_or_else(|| signing("the local signer did not complete at once".to_owned()))? + .map_err(|error| signing(error.to_string()))? + } else if let Some((secret, algorithm)) = self.hmac_key(&header.alg) { + extra_header.insert("alg".to_owned(), Value::String(header.alg.clone())); + extra_header.insert( + "kid".to_owned(), + Value::String(format!("test-hmac-{}", header.alg.to_lowercase())), + ); + let header_bytes = serde_json::to_vec(&Value::Object(extra_header)) + .map_err(|error| signing(error.to_string()))?; + let input = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(header_bytes), + URL_SAFE_NO_PAD.encode(&payload) + ); + let signature = crypto::sign( + input.as_bytes(), + &EncodingKey::from_secret(secret), + algorithm, + ) + .map_err(|error| signing(error.to_string()))?; + format!("{input}.{signature}") + } else { + return Err(signing(format!("no key for algorithm `{}`", header.alg))); + }; + Ok(SignedToken { + text, + opaque: false, + }) + } + + /// Check a signed token's signature with this signer's keys. An opaque + /// credential has no signature and passes. + pub fn verify_signature(&self, token: &SignedToken) -> Result<(), TokenFixtureError> { + let fail = |reason: &str| TokenFixtureError::Verification(reason.to_owned()); + if token.opaque { + return Ok(()); + } + let mut parts = token.text.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(fail("not three segments")); + }; + let input = format!("{header}.{payload}"); + let header: Value = URL_SAFE_NO_PAD + .decode(header) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .ok_or_else(|| fail("header is not base64url JSON"))?; + let alg = header + .get("alg") + .and_then(Value::as_str) + .ok_or_else(|| fail("header has no alg"))?; + if let Some(key) = self.asymmetric_key(alg) { + if header.get("kid").and_then(Value::as_str) != key.kid.as_deref() { + return Err(fail("kid names no key of this signer")); + } + let signature = URL_SAFE_NO_PAD + .decode(signature) + .map_err(|_| fail("signature is not base64url"))?; + let public: PublicJwk = key.public(); + verify_with_public_jwk(input.as_bytes(), &signature, &public) + .map_err(|_| fail("signature does not verify")) + } else if let Some((secret, algorithm)) = self.hmac_key(alg) { + let expected_kid = format!("test-hmac-{}", alg.to_lowercase()); + if header.get("kid").and_then(Value::as_str) != Some(expected_kid.as_str()) { + return Err(fail("kid names no key of this signer")); + } + match crypto::verify( + signature, + input.as_bytes(), + &DecodingKey::from_secret(secret), + algorithm, + ) { + Ok(true) => Ok(()), + Ok(false) | Err(_) => Err(fail("signature does not verify")), + } + } else { + Err(fail("alg is not one this signer holds")) + } + } +} + +fn random_hex() -> String { + let mut bytes = [0_u8; 16]; + rand::rng().fill(&mut bytes); + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +// --------------------------------------------------------------------------- +// Corpus and driver +// --------------------------------------------------------------------------- + +/// What the product under test is given for one row. +#[derive(Debug, Clone)] +pub struct FixtureCase { + pub fixture: TokenFixture, + pub against: Against, + pub configuration: Configuration, + /// The product's issuer. + pub issuer: String, + /// The audience the product is configured with for this row. It is the + /// audience the driver was given, except for a positive fixture in the + /// `recipe` configuration that states a literal `aud`: the documented + /// recipe names that audience. + pub audience: String, + /// The credential to present. + pub token: SignedToken, + /// The public key set the product verifies against. + pub jwks: Value, +} + +/// Whether a product's result matched `expected.yaml` for a row. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Comparison { + Match, + Mismatch, + /// The expected value is `none` or `n-a`: nothing was run. + NotApplicable, + /// The expected value is `unknown`: the result was observed and not judged. + Unresolved, +} + +/// The outcome of one row for one product. It holds no token. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RowReport { + pub fixture: String, + pub against: Against, + pub configuration: Configuration, + pub expected: Outcome, + pub observed: Option, + pub comparison: Comparison, +} + +/// Every row of `expected.yaml` for one product column. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProductReport { + pub product: String, + pub rows: Vec, +} + +impl ProductReport { + #[must_use] + pub fn mismatches(&self) -> Vec<&RowReport> { + self.rows + .iter() + .filter(|row| row.comparison == Comparison::Mismatch) + .collect() + } + + /// # Panics + /// + /// Panics, listing each differing row, if any row mismatched. + pub fn assert_matches(&self) { + let mismatches = self.mismatches(); + for row in self + .rows + .iter() + .filter(|row| row.comparison == Comparison::Unresolved) + { + if let Some(observed) = &row.observed { + eprintln!( + "unresolved {} / {} / {:?} / {:?}: observed {observed}", + self.product, row.fixture, row.against, row.configuration + ); + } + } + assert!( + mismatches.is_empty(), + "{} rows of `{}` differ from expected.yaml:\n{}", + mismatches.len(), + self.product, + mismatches + .iter() + .map(|row| format!( + " {} / {:?} / {:?}: expected {}, observed {}", + row.fixture, + row.against, + row.configuration, + row.expected, + row.observed + .as_ref() + .map_or_else(|| "nothing".to_owned(), ToString::to_string), + )) + .collect::>() + .join("\n") + ); + } +} + +/// The fixtures and `expected.yaml`, loaded and cross-checked. +#[derive(Debug, Clone)] +pub struct TokenCorpus { + fixtures: Vec, + expectations: Expectations, +} + +struct PlannedRow { + report: RowReport, + case: Option, +} + +impl TokenCorpus { + /// The corpus directory, resolved from this crate's manifest directory. + #[must_use] + pub fn directory() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../products/platform/conformance/tokens") + } + + /// Load every fixture and `expected.yaml`, and check them against each other. + pub fn load() -> Result { + let root = Self::directory(); + let fixtures_dir = root.join("fixtures"); + let read_error = |path: &Path| { + let path = path.display().to_string(); + move |source| TokenFixtureError::Io { path, source } + }; + let mut paths = Vec::new(); + for entry in std::fs::read_dir(&fixtures_dir).map_err(read_error(&fixtures_dir))? { + let path = entry.map_err(read_error(&fixtures_dir))?.path(); + if path.extension().and_then(|e| e.to_str()) == Some("json") { + paths.push(path); + } + } + paths.sort(); + let mut fixtures = Vec::new(); + for path in &paths { + let text = std::fs::read_to_string(path).map_err(read_error(path))?; + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .ok_or_else(|| invalid(&path.display().to_string(), "file name is not UTF-8"))?; + fixtures.push(TokenFixture::parse(stem, &text)?); + } + let expected_path = root.join("expected.yaml"); + let text = std::fs::read_to_string(&expected_path).map_err(read_error(&expected_path))?; + let expectations: Expectations = Reader::new("expected.yaml") + .decode::(text.as_bytes(), &Expect::one(&EXPECTATIONS_FORMAT)) + .map_err(|report| { + TokenFixtureError::Expectations( + report + .diagnostics() + .iter() + .map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message)) + .collect::>() + .join("; "), + ) + })? + .value; + let corpus = Self { + fixtures, + expectations, + }; + corpus.check_expectations()?; + Ok(corpus) + } + + fn check_expectations(&self) -> Result<(), TokenFixtureError> { + let fail = |reason: String| Err(TokenFixtureError::Expectations(reason)); + let expectations = &self.expectations; + if expectations.schema != EXPECTATIONS_SCHEMA { + return fail(format!("schema must be `{EXPECTATIONS_SCHEMA}`")); + } + let products: BTreeSet<&str> = expectations.products.iter().map(String::as_str).collect(); + if products.len() != expectations.products.len() || products.is_empty() { + return fail("products must be a non-empty list without repeats".to_owned()); + } + let mut seen = BTreeSet::new(); + for row in &expectations.rows { + let Some(fixture) = self.fixture(&row.fixture) else { + return fail(format!("row names unknown fixture `{}`", row.fixture)); + }; + if !seen.insert((row.fixture.as_str(), row.against, row.configuration)) { + return fail(format!( + "row `{}` / {:?} / {:?} repeats", + row.fixture, row.against, row.configuration + )); + } + let row_products: BTreeSet<&str> = row.products.keys().map(String::as_str).collect(); + if row_products != products { + return fail(format!( + "row `{}` does not have exactly the product columns", + row.fixture + )); + } + for (product, cell) in &row.products { + if cell.landed.is_some() != cell.changed_by.is_some() { + return fail(format!( + "`{}` / `{product}`: landed appears exactly when changedBy is a change name", + row.fixture + )); + } + let admitted = |outcome: &Outcome| matches!(outcome, Outcome::Admitted(_)); + if fixture.class == FixtureClass::Negative + && (admitted(&cell.main) || admitted(&cell.target)) + { + return fail(format!( + "negative fixture `{}` is admitted by `{product}`", + row.fixture + )); + } + } + } + for fixture in &self.fixtures { + if !expectations + .rows + .iter() + .any(|row| row.fixture == fixture.id) + { + return fail(format!("fixture `{}` has no row", fixture.id)); + } + } + Ok(()) + } + + #[must_use] + pub fn fixtures(&self) -> &[TokenFixture] { + &self.fixtures + } + + #[must_use] + pub fn fixture(&self, id: &str) -> Option<&TokenFixture> { + self.fixtures.iter().find(|fixture| fixture.id == id) + } + + #[must_use] + pub fn expectations(&self) -> &Expectations { + &self.expectations + } + + fn plan( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + ) -> Result, TokenFixtureError> { + if !self + .expectations + .products + .iter() + .any(|name| name == product) + { + return Err(TokenFixtureError::UnknownProduct(product.to_owned())); + } + let jwks = signer.public_key_set(); + let mut planned = Vec::new(); + for row in &self.expectations.rows { + let cell = row + .products + .get(product) + .ok_or_else(|| TokenFixtureError::UnknownProduct(product.to_owned()))?; + let expected = cell.expected().clone(); + let mut report = RowReport { + fixture: row.fixture.clone(), + against: row.against, + configuration: row.configuration, + expected: expected.clone(), + observed: None, + comparison: Comparison::NotApplicable, + }; + if matches!(expected, Outcome::None | Outcome::NotApplicable) { + planned.push(PlannedRow { report, case: None }); + continue; + } + let fixture = self + .fixture(&row.fixture) + .ok_or_else(|| invalid(&row.fixture, "no such fixture"))?; + let audience = configured_audience(fixture, row.configuration, audience); + let token = signer.sign( + fixture, + &Binding { + issuer: issuer.to_owned(), + audience: audience.clone(), + }, + )?; + report.comparison = Comparison::Unresolved; + planned.push(PlannedRow { + report, + case: Some(FixtureCase { + fixture: fixture.clone(), + against: row.against, + configuration: row.configuration, + issuer: issuer.to_owned(), + audience, + token, + jwks: jwks.clone(), + }), + }); + } + Ok(planned) + } + + /// Run every applicable row through `authenticate` and compare the results + /// with `expected.yaml` for `product`. Rows whose expected value is `none` + /// or `n-a` are not run. `issuer` and `audience` are the product's own. + pub fn run_product( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + mut authenticate: F, + ) -> Result + where + F: FnMut(&FixtureCase) -> Outcome, + { + let mut rows = Vec::new(); + for planned in self.plan(product, signer, issuer, audience)? { + let observed = planned.case.as_ref().map(&mut authenticate); + rows.push(finish(planned.report, observed)); + } + Ok(ProductReport { + product: product.to_owned(), + rows, + }) + } + + /// [`Self::run_product`] for an authenticator that is asynchronous. + pub async fn run_product_async( + &self, + product: &str, + signer: &TokenSigner, + issuer: &str, + audience: &str, + mut authenticate: F, + ) -> Result + where + F: FnMut(FixtureCase) -> Fut, + Fut: Future, + { + let mut rows = Vec::new(); + for planned in self.plan(product, signer, issuer, audience)? { + let observed = match planned.case { + Some(case) => Some(authenticate(case).await), + None => None, + }; + rows.push(finish(planned.report, observed)); + } + Ok(ProductReport { + product: product.to_owned(), + rows, + }) + } +} + +fn configured_audience( + fixture: &TokenFixture, + configuration: Configuration, + product_audience: &str, +) -> String { + if fixture.class == FixtureClass::Positive && configuration == Configuration::Recipe { + if let Some(ClaimValue::Literal(Value::String(literal))) = fixture.claims.get("aud") { + return literal.clone(); + } + } + product_audience.to_owned() +} + +fn finish(mut report: RowReport, observed: Option) -> RowReport { + if let Some(observed) = observed { + report.comparison = match report.expected { + Outcome::Unknown => Comparison::Unresolved, + ref expected if *expected == observed => Comparison::Match, + _ => Comparison::Mismatch, + }; + report.observed = Some(observed); + } + report +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + #[test] + fn the_private_member_list_is_the_platform_list() { + assert_eq!( + super::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); + } +} diff --git a/crates/registry-platform-testing/tests/cross_crate_integration.rs b/crates/registry-platform-testing/tests/cross_crate_integration.rs index 12f6c6ef28..d6f7bf8415 100644 --- a/crates/registry-platform-testing/tests/cross_crate_integration.rs +++ b/crates/registry-platform-testing/tests/cross_crate_integration.rs @@ -10,8 +10,8 @@ use registry_platform_audit::{ AuditDestination, AuditEntry, AuditPhase, AuditWriter, FileDestination, }; use registry_platform_httpsec::{ - body_limit_problem_response, corp_conditional, request_body_limit, security_headers, - CorsPolicy, CspBuilder, Problem, + body_limit_problem_response, corp_conditional, request_body_limit, + security_headers_without_posture, CorsPolicy, CspBuilder, Problem, }; use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ @@ -68,16 +68,16 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { Some(&HeaderValue::from_static("cross-origin")) ); - let security_service = security_headers(CspBuilder::restrictive()).layer(service_fn( - |_request: Request| async { + let security_service = security_headers_without_posture(CspBuilder::restrictive()).layer( + service_fn(|_request: Request| async { Ok::<_, std::convert::Infallible>( axum::response::Response::builder() .status(StatusCode::OK) .body(Body::empty()) .expect("response builds"), ) - }, - )); + }), + ); let secured = security_service .oneshot(Request::new(Body::empty())) .await @@ -127,7 +127,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { discovery_timeout: Duration::from_secs(5), max_doc_bytes: 16 * 1024, }, - &FetchUrlPolicy::dev(), + &FetchUrlPolicy::https_or_loopback(), ) .await .expect("discovery fetch succeeds"); @@ -141,7 +141,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut verifier_config = oidc_verifier_config(idp.issuer(), vec!["registry-api".to_string()]); verifier_config.allowed_clients = vec!["client-a".to_string()]; @@ -162,7 +162,7 @@ async fn sample_axum_app_wires_middleware_oidc_and_audit_writer() { let destination = FileDestination::new(dir.path().join("audit").join("audit.jsonl")).expect("absolute path"); let path = destination.path().to_path_buf(); - let writer = AuditWriter::open(AuditDestination::File(destination)) + let writer = AuditWriter::open_without_posture(AuditDestination::File(destination)) .await .expect("file destination opens"); let correlation = "request-1"; diff --git a/crates/registry-platform-testing/tests/test_authorization_server.rs b/crates/registry-platform-testing/tests/test_authorization_server.rs index f886b7485f..33d19a12b6 100644 --- a/crates/registry-platform-testing/tests/test_authorization_server.rs +++ b/crates/registry-platform-testing/tests/test_authorization_server.rs @@ -323,7 +323,7 @@ async fn verifier(server: &TestAuthorizationServer, audience: &str) -> TokenVeri request_timeout: Duration::from_secs(5), outage_tolerance: Duration::from_secs(900), }, - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )); let mut config = server.verifier_config(vec![audience.to_owned()]); config.allowed_clients = vec![CHAT_HOST.to_owned(), GATEWAY.to_owned()]; diff --git a/crates/registry-platform-testing/tests/token_fixtures.rs b/crates/registry-platform-testing/tests/token_fixtures.rs new file mode 100644 index 0000000000..48863b0e3c --- /dev/null +++ b/crates/registry-platform-testing/tests/token_fixtures.rs @@ -0,0 +1,656 @@ +#![cfg(feature = "token-fixtures")] +//! The token fixture corpus under `products/platform/conformance/tokens`: every +//! fixture loads and validates, signs and verifies, every expectation row names +//! a real fixture and product, and nothing in the corpus is a key or a live token. +//! The driver is exercised with stand-in authenticators. + +use std::collections::BTreeSet; + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use registry_platform_testing::{ + Against, Binding, Comparison, Configuration, ExpectedCell, FixtureClass, Outcome, Stage, + TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://issuer.example.test/realms/journey"; +const AUDIENCE: &str = "https://api.example.test"; +const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "k", "oth"]; + +#[test] +fn the_private_member_list_is_the_platform_list() { + assert_eq!( + PRIVATE_JWK_MEMBERS.into_iter().collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); +} + +fn corpus() -> TokenCorpus { + TokenCorpus::load().expect("the corpus loads and validates") +} + +fn binding() -> Binding { + Binding { + issuer: ISSUER.to_owned(), + audience: AUDIENCE.to_owned(), + } +} + +fn decode_segment(segment: &str) -> Value { + let bytes = URL_SAFE_NO_PAD + .decode(segment) + .expect("segment is base64url"); + serde_json::from_slice(&bytes).expect("segment is JSON") +} + +fn minimal_fixture(extra: Value) -> String { + let mut base = json!({ + "schema": "registry.token-fixture/v1", + "id": "unit-fixture", + "class": "positive", + "provider": "synthetic", + "kind": "user-access", + "tokenUse": "access", + "subjectKind": "user", + "source": { "basis": "constructed", "reason": "a unit test" }, + "header": { "alg": "ES256", "typ": "at+jwt", "kid": { "generated": true } }, + "claims": { + "iss": { "bind": "issuer" }, + "aud": { "bind": "audience" }, + "sub": "subject-1", + "iat": { "offsetSeconds": 0 }, + "exp": { "offsetSeconds": 300 } + } + }); + for (key, value) in extra.as_object().expect("extra is an object") { + base[key] = value.clone(); + } + base.to_string() +} + +fn parse_error(extra: Value) -> String { + TokenFixture::parse("unit-fixture", &minimal_fixture(extra)) + .expect_err("the fixture is refused") + .to_string() +} + +fn fixture_with_claims(claims: Value) -> TokenFixture { + let mut full = json!({ + "iss": { "bind": "issuer" }, + "aud": { "bind": "audience" }, + "sub": "subject-1", + "iat": { "offsetSeconds": 0 }, + "exp": { "offsetSeconds": 300 } + }); + for (key, value) in claims.as_object().expect("claims is an object") { + full[key] = value.clone(); + } + TokenFixture::parse("unit-fixture", &minimal_fixture(json!({ "claims": full }))) + .expect("the fixture parses") +} + +#[test] +fn read_scope_skips_openid_connect_scopes() { + let mixed = fixture_with_claims(json!({ "scope": "openid records:get" })); + assert_eq!(mixed.read_scope("scope").as_deref(), Some("records:get")); + let only_openid = fixture_with_claims(json!({ "scope": "openid email profile" })); + assert_eq!(only_openid.read_scope("scope"), None); + let none = fixture_with_claims(json!({})); + assert_eq!(none.read_scope("scope"), None); + let list = fixture_with_claims(json!({ "scp": ["openid", "records:get", "records:write"] })); + assert_eq!(list.read_scope("scp").as_deref(), Some("records:get")); + assert_eq!(list.read_scope("scope"), None); +} + +// --------------------------------------------------------------------------- +// The corpus as written +// --------------------------------------------------------------------------- + +#[test] +fn every_fixture_loads_and_validates() { + let corpus = corpus(); + assert_eq!(corpus.fixtures().len(), 29, "16 positive and 13 negative"); + let positive = corpus + .fixtures() + .iter() + .filter(|fixture| fixture.class == FixtureClass::Positive) + .count(); + assert_eq!(positive, 16); + let ids: BTreeSet<&str> = corpus.fixtures().iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids.len(), corpus.fixtures().len(), "ids are unique"); +} + +#[test] +fn every_fixture_signs_and_its_signature_verifies() { + let corpus = corpus(); + let signer = TokenSigner::new(); + for fixture in corpus.fixtures() { + let signed = signer + .sign(fixture, &binding()) + .unwrap_or_else(|error| panic!("{} signs: {error}", fixture.id)); + signer + .verify_signature(&signed) + .unwrap_or_else(|error| panic!("{} verifies: {error}", fixture.id)); + } +} + +#[test] +fn a_signed_token_carries_the_declared_header_and_the_bound_claims() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus + .fixture("thunderid-user-access") + .expect("the fixture exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let segments: Vec<&str> = signed.expose().split('.').collect(); + assert_eq!(segments.len(), 3); + let header = decode_segment(segments[0]); + assert_eq!(header["alg"], "RS256"); + assert_eq!(header["typ"], "at+jwt"); + assert!(header["kid"].as_str().is_some_and(|kid| !kid.is_empty())); + let claims = decode_segment(segments[1]); + assert_eq!(claims["iss"], ISSUER); + assert_eq!(claims["aud"], AUDIENCE); + let iat = claims["iat"].as_i64().expect("iat is an integer"); + let exp = claims["exp"].as_i64().expect("exp is an integer"); + assert_eq!(exp - iat, 3600, "the lifetime is the fixture's offset"); +} + +#[test] +fn a_fixture_without_typ_signs_a_header_without_typ() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("esignet-id-token").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let header = decode_segment(signed.expose().split('.').next().expect("header")); + assert!(header.get("typ").is_none()); +} + +#[test] +fn each_declared_algorithm_signs_with_its_own_key() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut seen = BTreeSet::new(); + for fixture in corpus.fixtures() { + let Some(header) = &fixture.header else { + continue; + }; + let signed = signer.sign(fixture, &binding()).expect("signs"); + let signed_header = decode_segment(signed.expose().split('.').next().expect("header")); + assert_eq!(signed_header["alg"], header.alg.as_str()); + seen.insert(header.alg.clone()); + } + assert_eq!( + seen, + ["ES256", "HS256", "HS512", "RS256"] + .into_iter() + .map(str::to_owned) + .collect() + ); +} + +#[test] +fn the_opaque_fixture_signs_to_its_synthetic_string() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("supabase-api-key-opaque").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + assert!(signed.is_opaque()); + assert!(!signed.expose().contains('.')); + signer.verify_signature(&signed).expect("nothing to verify"); +} + +#[test] +fn the_public_key_set_holds_asymmetric_public_members_only() { + let signer = TokenSigner::new(); + let set = signer.public_key_set(); + let keys = set["keys"].as_array().expect("keys is an array"); + let algs: BTreeSet<&str> = keys.iter().filter_map(|k| k["alg"].as_str()).collect(); + assert_eq!(algs, BTreeSet::from(["ES256", "EdDSA", "RS256"])); + for key in keys { + for member in PRIVATE_JWK_MEMBERS { + assert!(key.get(member).is_none(), "public key set has `{member}`"); + } + } +} + +#[test] +fn two_signers_hold_different_keys() { + let corpus = corpus(); + let fixture = corpus.fixture("thunderid-user-access").expect("exists"); + let first = TokenSigner::new(); + let second = TokenSigner::new(); + assert_ne!(first.public_key_set(), second.public_key_set()); + let signed = first.sign(fixture, &binding()).expect("signs"); + assert!( + second.verify_signature(&signed).is_err(), + "a token from one run does not verify under another run's key" + ); +} + +#[test] +fn a_tampered_token_fails_verification() { + let corpus = corpus(); + let signer = TokenSigner::new(); + for id in ["thunderid-user-access", "supabase-api-key-anon"] { + let fixture = corpus.fixture(id).expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let mut segments: Vec = signed.expose().split('.').map(str::to_owned).collect(); + let mut claims = decode_segment(&segments[1]); + claims["sub"] = json!("someone-else"); + segments[1] = URL_SAFE_NO_PAD.encode(claims.to_string()); + let tampered = signed.with_text(segments.join(".")); + assert!(signer.verify_signature(&tampered).is_err(), "{id}"); + } +} + +#[test] +fn a_debug_print_of_a_signed_token_does_not_show_it() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let fixture = corpus.fixture("thunderid-user-access").expect("exists"); + let signed = signer.sign(fixture, &binding()).expect("signs"); + let shown = format!("{signed:?}"); + assert!(!shown.contains(signed.expose())); + assert!(!shown.contains("eyJ")); +} + +#[test] +fn every_expectation_row_names_an_existing_fixture_and_a_known_product() { + let corpus = corpus(); + let expectations = corpus.expectations(); + let products: BTreeSet<&str> = expectations.products.iter().map(String::as_str).collect(); + assert_eq!(products.len(), 11); + let ids: BTreeSet<&str> = corpus.fixtures().iter().map(|f| f.id.as_str()).collect(); + assert!(!expectations.rows.is_empty()); + for row in &expectations.rows { + assert!( + ids.contains(row.fixture.as_str()), + "row names unknown fixture `{}`", + row.fixture + ); + for product in row.products.keys() { + assert!( + products.contains(product.as_str()), + "row for `{}` names unknown product `{product}`", + row.fixture + ); + } + let row_products: BTreeSet<&str> = row.products.keys().map(String::as_str).collect(); + assert_eq!(row_products, products, "row for `{}`", row.fixture); + } +} + +#[test] +fn every_fixture_has_a_row_and_no_row_repeats() { + let corpus = corpus(); + let rows = &corpus.expectations().rows; + let with_row: BTreeSet<&str> = rows.iter().map(|r| r.fixture.as_str()).collect(); + for fixture in corpus.fixtures() { + assert!(with_row.contains(fixture.id.as_str()), "{}", fixture.id); + } + let keys: BTreeSet<(String, Against, Configuration)> = rows + .iter() + .map(|r| (r.fixture.clone(), r.against, r.configuration)) + .collect(); + assert_eq!( + keys.len(), + rows.len(), + "a (fixture, against, configuration) repeats" + ); +} + +#[test] +fn no_negative_fixture_is_expected_to_be_admitted() { + let corpus = corpus(); + for row in &corpus.expectations().rows { + let fixture = corpus.fixture(&row.fixture).expect("exists"); + if fixture.class != FixtureClass::Negative { + continue; + } + for (product, cell) in &row.products { + for outcome in [&cell.main, &cell.target] { + assert!( + !matches!(outcome, Outcome::Admitted(_)), + "negative `{}` is admitted by `{product}`", + row.fixture + ); + } + } + } +} + +fn cell_with_changed_by(changed_by: &str) -> Result { + serde_json::from_value(json!({ + "main": "refused/scope", + "target": "admitted", + "basis": "observed", + "changedBy": changed_by, + "landed": false, + })) +} + +#[test] +fn changed_by_is_a_change_name_or_none() { + for accepted in ["caller-contract", "posture", "none"] { + cell_with_changed_by(accepted) + .unwrap_or_else(|error| panic!("`{accepted}` is refused: {error}")); + } + for refused in [ + "M7", + "Caller-Contract", + "caller_contract", + "-caller", + "caller-", + "7th", + "", + ] { + let error = cell_with_changed_by(refused) + .expect_err(&format!("`{refused}` is accepted")) + .to_string(); + assert!(error.contains("changedBy"), "unhelpful error: {error}"); + } +} + +#[test] +fn landed_appears_exactly_when_a_change_alters_the_cell() { + let corpus = corpus(); + for row in &corpus.expectations().rows { + for (product, cell) in &row.products { + assert_eq!( + cell.landed.is_some(), + cell.changed_by.is_some(), + "`{}` / `{product}`", + row.fixture + ); + } + } +} + +#[test] +fn no_fixture_file_holds_a_private_jwk_member_or_a_live_looking_token() { + let dir = TokenCorpus::directory().join("fixtures"); + let mut checked = 0; + for entry in std::fs::read_dir(&dir).expect("fixtures directory reads") { + let path = entry.expect("entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let text = std::fs::read_to_string(&path).expect("fixture reads"); + let value: Value = serde_json::from_str(&text).expect("fixture is JSON"); + walk(&value, &mut |node| match node { + Value::Object(map) => { + for member in PRIVATE_JWK_MEMBERS { + assert!( + !map.contains_key(member), + "{} holds member `{member}`", + path.display() + ); + } + } + Value::String(text) => { + assert!( + !text.starts_with("eyJ"), + "{} holds a string shaped like a JWT", + path.display() + ); + assert!( + !text.contains("PRIVATE KEY"), + "{} holds key material", + path.display() + ); + } + _ => {} + }); + checked += 1; + } + assert_eq!(checked, 29); +} + +fn walk(value: &Value, visit: &mut impl FnMut(&Value)) { + visit(value); + match value { + Value::Array(items) => items.iter().for_each(|item| walk(item, visit)), + Value::Object(map) => map.values().for_each(|item| walk(item, visit)), + _ => {} + } +} + +// --------------------------------------------------------------------------- +// Validation refuses a bad fixture +// --------------------------------------------------------------------------- + +#[test] +fn validation_accepts_the_minimal_fixture() { + TokenFixture::parse("unit-fixture", &minimal_fixture(json!({}))).expect("valid"); +} + +#[test] +fn validation_refuses_an_id_that_differs_from_the_file_name() { + let error = TokenFixture::parse("other-name", &minimal_fixture(json!({}))) + .expect_err("refused") + .to_string(); + assert!(error.contains("file name"), "{error}"); +} + +#[test] +fn validation_refuses_a_private_jwk_member() { + let error = parse_error(json!({ "notes": "x", "extra": { "kty": "EC", "d": "abc" } })); + assert!( + error.contains("private") || error.contains("unknown"), + "{error}" + ); + let mut text = minimal_fixture(json!({})); + text = text.replace( + "\"sub\":\"subject-1\"", + "\"sub\":\"subject-1\",\"jwk\":{\"kty\":\"oct\",\"k\":\"c2VjcmV0\"}", + ); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("private"), "{error}"); +} + +#[test] +fn validation_refuses_a_string_shaped_like_a_jwt() { + let text = minimal_fixture(json!({})).replace( + "\"subject-1\"", + "\"eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJ4In0.c2lnbmF0dXJl\"", + ); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("JWT"), "{error}"); +} + +#[test] +fn validation_refuses_a_claim_named_in_omits() { + let error = parse_error(json!({ "omits": ["sub"] })); + assert!(error.contains("omits"), "{error}"); +} + +#[test] +fn validation_refuses_a_fixture_with_both_opaque_and_claims() { + let error = parse_error(json!({ "opaque": "synthetic-value" })); + assert!(error.contains("opaque"), "{error}"); +} + +#[test] +fn validation_refuses_missing_exp() { + let text = minimal_fixture(json!({})).replace(",\"exp\":{\"offsetSeconds\":300}", ""); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("exp"), "{error}"); +} + +#[test] +fn validation_refuses_an_algorithm_outside_the_signer_set() { + let error = parse_error(json!({ "header": { "alg": "none", "kid": { "generated": true } } })); + assert!(error.contains("alg"), "{error}"); +} + +#[test] +fn validation_refuses_an_unknown_directive_member() { + let text = minimal_fixture(json!({})) + .replace("{\"bind\":\"issuer\"}", "{\"bind\":\"issuer\",\"extra\":1}"); + let error = TokenFixture::parse("unit-fixture", &text) + .expect_err("refused") + .to_string(); + assert!(error.contains("iss"), "{error}"); +} + +#[test] +fn validation_refuses_an_unknown_top_level_member() { + let error = parse_error(json!({ "surprise": true })); + assert!(error.contains("surprise"), "{error}"); +} + +// --------------------------------------------------------------------------- +// The driver +// --------------------------------------------------------------------------- + +#[test] +fn the_driver_runs_every_applicable_row_and_hands_the_closure_a_verifiable_token() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut calls = 0usize; + let report = corpus + .run_product("breg", &signer, ISSUER, AUDIENCE, |case| { + calls += 1; + signer + .verify_signature(&case.token) + .expect("token verifies"); + Outcome::Refused(Stage::Header) + }) + .expect("the run completes"); + assert_eq!(report.product, "breg"); + assert_eq!(report.rows.len(), corpus.expectations().rows.len()); + let skipped = report + .rows + .iter() + .filter(|row| matches!(row.comparison, Comparison::NotApplicable)) + .count(); + assert_eq!(calls + skipped, report.rows.len()); + assert!(calls > 0); + assert!( + !report.mismatches().is_empty(), + "a stand-in refusing everything differs" + ); +} + +#[test] +fn the_driver_compares_against_main_unless_the_cell_has_landed() { + let corpus = corpus(); + let signer = TokenSigner::new(); + // Answer each case with exactly what the expectation says, then compare. + let expected = corpus.expectations().clone(); + let report = corpus + .run_product("casework", &signer, ISSUER, AUDIENCE, |case| { + let row = expected + .rows + .iter() + .find(|row| { + row.fixture == case.fixture.id + && row.against == case.against + && row.configuration == case.configuration + }) + .expect("row exists"); + row.products["casework"].expected().clone() + }) + .expect("the run completes"); + assert!(report.mismatches().is_empty(), "{:?}", report.mismatches()); + // The report never carries a token. + assert!(!format!("{report:?}").contains("eyJ")); +} + +#[test] +fn a_literal_audience_is_the_configured_audience_only_for_a_positive_recipe_row() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let mut observed: Vec<(String, Configuration, String)> = Vec::new(); + corpus + .run_product("breg", &signer, ISSUER, AUDIENCE, |case| { + if case.fixture.id == "supabase-user-access" || case.fixture.id == "keycloak-id-token" { + observed.push(( + case.fixture.id.clone(), + case.configuration, + case.audience.clone(), + )); + } + Outcome::None + }) + .expect("the run completes"); + assert!(observed.contains(&( + "supabase-user-access".to_owned(), + Configuration::Default, + AUDIENCE.to_owned() + ))); + assert!(observed.contains(&( + "supabase-user-access".to_owned(), + Configuration::Recipe, + "authenticated".to_owned() + ))); + assert!(observed + .iter() + .filter(|(id, ..)| id == "keycloak-id-token") + .all(|(_, _, audience)| audience == AUDIENCE)); +} + +#[test] +fn the_driver_refuses_an_unknown_product() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let error = corpus + .run_product("nonesuch", &signer, ISSUER, AUDIENCE, |_| Outcome::None) + .expect_err("refused") + .to_string(); + assert!(error.contains("nonesuch"), "{error}"); +} + +#[test] +fn outcomes_parse_and_print_the_values_expected_yaml_uses() { + for text in [ + "admitted", + "admitted/human", + "admitted/unspecified", + "refused/token-type", + "refused/claims", + "none", + "n-a", + "unknown", + ] { + let outcome: Outcome = text.parse().expect("parses"); + assert_eq!(outcome.to_string(), text); + } + for text in ["refused", "refused/nowhere", "admitted/", "yes", ""] { + assert!(text.parse::().is_err(), "`{text}`"); + } +} + +#[test] +fn the_async_driver_gives_the_same_report_as_the_sync_driver() { + let corpus = corpus(); + let signer = TokenSigner::new(); + let answer = |case: ®istry_platform_testing::FixtureCase| { + if case.fixture.class == FixtureClass::Negative { + Outcome::Refused(Stage::Header) + } else { + Outcome::Admitted(None) + } + }; + let sync = corpus + .run_product("messaging", &signer, ISSUER, AUDIENCE, |case| answer(case)) + .expect("sync run"); + let asynchronous = futures::executor::block_on(corpus.run_product_async( + "messaging", + &signer, + ISSUER, + AUDIENCE, + |case| async move { answer(&case) }, + )) + .expect("async run"); + assert_eq!(sync, asynchronous); +} diff --git a/crates/registry-platform-yaml/src/de.rs b/crates/registry-platform-yaml/src/de.rs index 01007ad9f3..d09814ff13 100644 --- a/crates/registry-platform-yaml/src/de.rs +++ b/crates/registry-platform-yaml/src/de.rs @@ -36,6 +36,65 @@ pub(crate) const DATA_LITERAL: &str = "\0registry-platform-yaml/data-literal"; /// `expecting` text carries the bounds. pub(crate) const BOUNDED: &str = "\0registry-platform-yaml/bounded"; pub(crate) const BOUNDED_EXPECTING: &str = "a whole number from "; +/// The newtype name a development-only setting asks for. A deserializer +/// that handles it records where the value sits for [`gated_site`] while the +/// value decodes. +pub const DEVELOPMENT_ONLY: &str = "\0registry-platform-yaml/development-only"; + +/// Where a development-only value sits in the document. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GatedSite { + /// The RFC 6901 pointer from the document root. + pub pointer: String, + /// Where the value starts in the file. + pub position: Option, + /// True when the pointer names the value itself. False when the value + /// was decoded from buffered content (under `#[serde(flatten)]` or an + /// untagged enum): the pointer then names the mapping that holds it, and + /// the caller appends the member's own key. + pub exact: bool, +} + +thread_local! { + static EXACT_SITE: RefCell> = const { RefCell::new(None) }; + static MAPPING_SITE: RefCell> = const { RefCell::new(None) }; +} + +/// Restores the previous value of a site cell when dropped, so nested +/// decodes and panics leave the cell as they found it. +struct SiteGuard { + cell: &'static std::thread::LocalKey>>, + previous: Option, +} + +impl SiteGuard { + fn set( + cell: &'static std::thread::LocalKey>>, + site: Option, + ) -> SiteGuard { + let previous = cell.with(|current| current.replace(site)); + SiteGuard { cell, previous } + } +} + +impl Drop for SiteGuard { + fn drop(&mut self) { + let previous = self.previous.take(); + self.cell.with(|current| *current.borrow_mut() = previous); + } +} + +/// The site of the development-only value being decoded, read by the +/// `Deserialize` code that asked for [`DEVELOPMENT_ONLY`]. `None` outside a +/// reader decode. +/// +/// When the value decodes from buffered content the reader never sees it as +/// a node, so the site is the innermost mapping with `exact: false`. +pub fn gated_site() -> Option { + EXACT_SITE + .with(|site| site.borrow().clone()) + .or_else(|| MAPPING_SITE.with(|site| site.borrow().clone())) +} /// A field renamed to a name starting with this prefix holds a platform /// shared block: the block's members sit beside the host's own, in the same @@ -514,6 +573,21 @@ impl<'a> NodeDe<'a> { item } + /// Record this mapping as the innermost one for [`gated_site`], and hide + /// the enclosing value's exact site: a value decoded from buffered + /// content inside this mapping is not that value. + fn enter_mapping(&self) -> (SiteGuard, SiteGuard) { + let mapping = SiteGuard::set( + &MAPPING_SITE, + Some(GatedSite { + pointer: self.site.path.clone(), + position: self.site.value_at(), + exact: false, + }), + ); + (mapping, SiteGuard::set(&EXACT_SITE, None)) + } + /// Run one deserializer method, placing any error that has no position /// yet at this node. fn run( @@ -1159,6 +1233,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { if let Some(tag) = name.strip_prefix(TAGGED_PREFIX) { return self.run(false, |de| { de.mapping()?; + let _mapping = de.enter_mapping(); visitor.visit_enum(TaggedAccess { de: de.clone(), tag, @@ -1209,6 +1284,19 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { } }); } + if name == DEVELOPMENT_ONLY { + return self.run(false, |de| { + let _site = SiteGuard::set( + &EXACT_SITE, + Some(GatedSite { + pointer: de.site.path.clone(), + position: de.site.value_at(), + exact: true, + }), + ); + visitor.visit_newtype_struct(de.clone()) + }); + } if name == BOUNDED { let expecting = Expecting(&visitor).to_string(); let bounds = parse_bounds(&expecting); @@ -1254,6 +1342,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { )); } let entries = de.mapping()?; + let _mapping = de.enter_mapping(); visitor.visit_map(MapAccess::new(de, entries)) }) } @@ -1266,6 +1355,7 @@ impl<'de, 'a> de::Deserializer<'de> for NodeDe<'a> { ) -> Result { self.run(true, |de| { let entries = de.mapping()?; + let _mapping = de.enter_mapping(); let mut access = StructAccess::new(de, entries, fields); let result = visitor.visit_map(&mut access); access.finish(); diff --git a/crates/registry-platform-yaml/src/lib.rs b/crates/registry-platform-yaml/src/lib.rs index f07438ddd4..7eb29fa819 100644 --- a/crates/registry-platform-yaml/src/lib.rs +++ b/crates/registry-platform-yaml/src/lib.rs @@ -127,7 +127,7 @@ pub use check_acceptances::{ CHECK_ACCEPTANCES_API_VERSION, CHECK_ACCEPTANCES_FILE, CHECK_ACCEPTANCES_FORMAT, CHECK_ACCEPTANCES_KIND, CHECK_ACCEPTANCES_SCHEMA_ID, }; -pub use de::{Invalid, SHARED_BLOCK_PREFIX}; +pub use de::{gated_site, GatedSite, Invalid, DEVELOPMENT_ONLY, SHARED_BLOCK_PREFIX}; pub use diagnostic::{Diagnostic, Related, Report, Severity, Source}; pub use document::{ decode_document, read_document, Decoded, Document, Reader, MAXIMUM_DIAGNOSTICS_PER_FILE, diff --git a/crates/registry-platform-yaml/tests/gated_site.rs b/crates/registry-platform-yaml/tests/gated_site.rs new file mode 100644 index 0000000000..fd892238c7 --- /dev/null +++ b/crates/registry-platform-yaml/tests/gated_site.rs @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A development-only newtype learns where it sits in the document. +mod common; + +use common::{codes, decode, refusal}; +use registry_platform_yaml::{gated_site, tagged_union, GatedSite, DEVELOPMENT_ONLY}; +use serde::de::{Deserializer, Visitor}; +use serde::Deserialize; + +/// A stand-in for a gate type: it asks for `DEVELOPMENT_ONLY`, reads the site +/// before it decodes the value, and keeps it. +#[derive(Debug)] +struct Probe { + site: Option, +} + +impl<'de> Deserialize<'de> for Probe { + fn deserialize>(deserializer: D) -> Result { + struct Reads; + impl<'de> Visitor<'de> for Reads { + type Value = Probe; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a probed value") + } + fn visit_newtype_struct>( + self, + inner: D, + ) -> Result { + let site = gated_site(); + bool::deserialize(inner)?; + Ok(Probe { site }) + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Reads) + } +} + +fn site(pointer: &str, exact: bool) -> (String, bool) { + (pointer.to_string(), exact) +} + +fn seen(probe: &Probe) -> (String, bool) { + let site = probe.site.as_ref().expect("the reader sets the site"); + assert!(site.position.is_some(), "the site carries a position"); + (site.pointer.clone(), site.exact) +} + +#[derive(Debug, Deserialize)] +struct Inner { + b: Probe, +} + +#[derive(Debug, Deserialize)] +struct Outer { + a: Inner, +} + +#[derive(Debug, Deserialize)] +struct Listed { + a: Vec, +} + +#[test] +fn a_member_has_an_exact_pointer() { + let read: Outer = decode("a:\n b: true\n").unwrap(); + assert_eq!(seen(&read.a.b), site("/a/b", true)); +} + +#[test] +fn a_list_item_has_an_exact_pointer() { + let read: Listed = decode("a:\n - b: true\n").unwrap(); + assert_eq!(seen(&read.a[0].b), site("/a/0/b", true)); +} + +#[derive(Debug, Deserialize)] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +enum Source { + Http { gate: Probe }, + None {}, +} +tagged_union!(Source); + +#[derive(Debug, Deserialize)] +struct Sourced { + source: Source, +} + +#[test] +fn a_member_of_a_tagged_union_variant_has_an_exact_pointer() { + let read: Sourced = decode("source:\n type: http\n gate: true\n").unwrap(); + let Source::Http { gate } = read.source else { + panic!("an http source"); + }; + assert_eq!(seen(&gate), site("/source/gate", true)); +} + +#[derive(Debug, Deserialize)] +struct Flattened { + #[serde(flatten)] + shared: Shared, +} + +#[derive(Debug, Deserialize)] +struct Shared { + allow: Probe, +} + +#[derive(Debug, Deserialize)] +struct Host { + issuer: Flattened, +} + +#[test] +fn under_flatten_the_site_is_the_parent_mapping_and_inexact() { + let read: Host = decode("issuer:\n allow: true\n").unwrap(); + assert_eq!(seen(&read.issuer.shared.allow), site("/issuer", false)); +} + +#[test] +fn the_site_is_cleared_after_a_decode_and_after_a_decode_error() { + assert_eq!(gated_site(), None); + let _: Outer = decode("a:\n b: true\n").unwrap(); + assert_eq!(gated_site(), None); + let _: Host = decode("issuer:\n allow: true\n").unwrap(); + assert_eq!(gated_site(), None); + let report = refusal::("a:\n b: true\n extra: 1\n"); + assert_eq!(codes(&report), ["config.unknown-key"]); + assert_eq!(gated_site(), None); + let report = refusal::("a:\n b: 7\n"); + assert_eq!(codes(&report), ["config.expected-boolean"]); + assert_eq!(gated_site(), None); +} + +#[test] +fn a_panic_while_the_site_is_set_restores_the_previous_site() { + #[derive(Debug)] + struct Boom; + impl<'de> Deserialize<'de> for Boom { + fn deserialize>(deserializer: D) -> Result { + struct Panics; + impl<'de> Visitor<'de> for Panics { + type Value = Boom; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a value") + } + fn visit_newtype_struct>( + self, + _: D, + ) -> Result { + assert!(gated_site().is_some()); + panic!("a decoder bug"); + } + } + deserializer.deserialize_newtype_struct(DEVELOPMENT_ONLY, Panics) + } + } + #[derive(Debug, Deserialize)] + struct Wrapper { + _a: Boom, + } + let result = std::panic::catch_unwind(|| decode::("_a: true\n")); + assert!(result.is_err()); + assert_eq!(gated_site(), None); +} diff --git a/crates/registry-render-client/src/lib.rs b/crates/registry-render-client/src/lib.rs index ee6c8a6f0c..cb91024b6e 100644 --- a/crates/registry-render-client/src/lib.rs +++ b/crates/registry-render-client/src/lib.rs @@ -8,7 +8,7 @@ use registry_platform_httpsec::{response_trace_id, ProblemDocument}; use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; -use registry_platform_httputil::{read_bounded, validate_response_headers}; +use registry_platform_httputil::{read_bounded, validate_response_headers_without_peer_policy}; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -500,7 +500,8 @@ impl RenderClient { .send() .await .map_err(|error| transport_error(send_failure_kind(&error)))?; - validate_response_headers(response.headers()).map_err(|_| error("protocol"))?; + validate_response_headers_without_peer_policy(response.headers()) + .map_err(|_| error("protocol"))?; let trace = response_trace_id(response.headers()) .map_err(|_| error("protocol"))? .to_owned(); diff --git a/crates/registry-render/Cargo.toml b/crates/registry-render/Cargo.toml index 5614340732..ba9f3f795a 100644 --- a/crates/registry-render/Cargo.toml +++ b/crates/registry-render/Cargo.toml @@ -10,14 +10,14 @@ publish = false [dependencies] registry-platform-audit = { workspace = true } -registry-platform-authcommon = { workspace = true } +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo = { workspace = true } registry-platform-canonical-json = { workspace = true } registry-platform-config = { workspace = true } registry-platform-oidc = { workspace = true } jsonwebtoken = { workspace = true } registry-platform-crypto = { workspace = true, features = ["cms-signing", "transit"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["refusal-trace-id", "server"] } registry-platform-httputil = { workspace = true } registry-platform-metrics = { workspace = true } registry-platform-yaml = { workspace = true } @@ -55,6 +55,7 @@ zeroize = { workspace = true } [dev-dependencies] async-trait = { workspace = true } +registry-platform-testing = { workspace = true, features = ["token-fixtures"] } registry-platform-crypto = { workspace = true, features = ["cms-signing", "test-support", "transit"] } registry-render-client.workspace = true tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/registry-render/src/audit.rs b/crates/registry-render/src/audit.rs index c43f2c61e0..e32f93f0cc 100644 --- a/crates/registry-render/src/audit.rs +++ b/crates/registry-render/src/audit.rs @@ -192,12 +192,14 @@ impl RenderAudit { /// Open the configured destination. A file destination takes the /// single-writer lock and creates an owner-only parent directory. pub async fn open(destination: AuditDestination) -> Result { - let writer = AuditWriter::open(destination).await.map_err(|err| { - RenderProblem::new( - ProblemKind::AuditFailed, - format!("cannot open audit destination: {err}"), - ) - })?; + let writer = AuditWriter::open_without_posture(destination) + .await + .map_err(|err| { + RenderProblem::new( + ProblemKind::AuditFailed, + format!("cannot open audit destination: {err}"), + ) + })?; Ok(Self::new(writer)) } diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index 0682a4a26a..c528c69162 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -1,6 +1,7 @@ //! Bearer verification belongs only to the HTTP adapter. use crate::problem::{ProblemKind, RenderProblem}; use crate::runtime::RenderRuntime; +use registry_platform_authcommon::FailedCheck; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, AccessTokenAlgorithm, IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, TokenVerifier, @@ -58,9 +59,19 @@ pub(crate) async fn verifier( network.declared_jwks_fetch_policy(), ) } - registry_platform_config::JwksSource::Static { document_ref } => { + registry_platform_config::JwksSource::Static { document_ref } + | registry_platform_config::JwksSource::TestIssuer { document_ref } => { let bytes = crate::runtime::resolve_secret(runtime, document_ref)?; - let keys = registry_platform_oidc::parse_static_jwks(&bytes).map_err(|_| refuse())?; + let keys = + registry_platform_oidc::parse_static_jwks(&bytes).map_err(|error| match error { + OidcError::StaticKeySet(refused) => RenderProblem::new( + ProblemKind::RuntimeInvalid, + format!( + "authentication.oidc.jwksSource.documentRef was refused: {refused}" + ), + ), + _ => refuse(), + })?; JwksFetcher::new_static(keys, JwksFetcherConfig::defaults()) } }; @@ -77,29 +88,38 @@ pub(crate) async fn verifier( #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum AuthenticationError { - Refused, - Forbidden { caller_fingerprint: String }, + /// The credential was refused, by the check that refused it. + Refused(FailedCheck), + Forbidden { + caller_fingerprint: String, + check: FailedCheck, + }, Unavailable, } +impl AuthenticationError { + /// The check that refused the caller. A key source that cannot answer is + /// the verifier's own outage. + #[deny(clippy::wildcard_enum_match_arm)] + pub(crate) fn failed_check(&self) -> FailedCheck { + match self { + Self::Refused(check) | Self::Forbidden { check, .. } => *check, + Self::Unavailable => FailedCheck::KeySourceUnavailable, + } + } +} + fn verifier_failure(error: OidcError) -> AuthenticationError { - match error { - OidcError::Transport(_) - | OidcError::BoundedRead(_) - | OidcError::FetchUrl(_) - | OidcError::HttpStatus(_) - | OidcError::InvalidUrl - | OidcError::Parse - | OidcError::InvalidJwk - | OidcError::EmptyKeySet - | OidcError::MissingIssuer - | OidcError::ConflictingEndpointConfiguration - | OidcError::InsecureHttpRequiresOptIn - | OidcError::EndpointRefused { .. } => AuthenticationError::Unavailable, - _ => AuthenticationError::Refused, + if error.is_key_source_unavailable() { + AuthenticationError::Unavailable + } else { + AuthenticationError::Refused(error.failed_check()) } } +/// The claim the verifier reads a token's scopes from. +pub(crate) const SCOPE_CLAIM: &str = "scope"; + /// The scope the render and document routes require. pub(crate) const RENDER_SCOPE: &str = "render:render"; /// The scope the seal route requires. Neither scope implies the other: a @@ -124,13 +144,16 @@ pub(crate) async fn authenticate( required_scope: &str, ) -> Result { registry_platform_authcommon::validate_compact_access_token(token) - .map_err(|_| AuthenticationError::Refused)?; + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; let verified = verifier.verify(token).await.map_err(verifier_failure)?; // The verifier owns resource membership and the configured client binding. // Unrelated task-grant claims confer no Render authority. let caller_fingerprint = registry_platform_authcommon::fingerprint_api_key(token); if !verified.scopes.iter().any(|scope| scope == required_scope) { - return Err(AuthenticationError::Forbidden { caller_fingerprint }); + return Err(AuthenticationError::Forbidden { + caller_fingerprint, + check: FailedCheck::Scope, + }); } // With an allowlist the verifier has bound the client and records which // claim matched. Without one, the signed claims name it, in the same @@ -143,7 +166,7 @@ pub(crate) async fn authenticate( .clone() .or_else(|| verified.claims.client_id.clone()) .filter(|client| !client.is_empty()), - Err(_) => return Err(AuthenticationError::Refused), + Err(_) => return Err(AuthenticationError::Refused(FailedCheck::TokenClient)), }; // Correlate the exact verified credential, as in legacy API-key mode. // Issuer, subject, and client claims are never written into the audit event. @@ -153,6 +176,9 @@ pub(crate) async fn authenticate( }) } +#[cfg(test)] +mod token_characterisation; + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -313,4 +339,76 @@ pub(crate) mod tests { assert_eq!(verified.client_id.as_deref(), client); } } + + /// Builds the verifier from a runtime file whose static key set is `keys`. + async fn verifier_over_static_keys( + keys: &Value, + ) -> Result, RenderProblem> { + use std::os::unix::fs::PermissionsExt; + let scratch = tempfile::tempdir().expect("home directory"); + let home = scratch + .path() + .canonicalize() + .expect("physical home directory"); + std::fs::create_dir(home.join("bundle")).expect("package directory"); + std::fs::create_dir(home.join("audit")).expect("audit directory"); + let key_file = home.join("jwks.json"); + std::fs::write(&key_file, keys.to_string()).expect("write the key set"); + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + let runtime = format!( + "apiVersion: {}\nkind: {}\nlistener:\n bind: 127.0.0.1:18080\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n oidc:\n issuer: https://issuer.example.test\n audience: urn:render:test\n allowedClients: [portal]\n jwksSource:\n type: static\n documentRef: secret:file/jwks.json\naudit:\n path: {}\n", + crate::runtime::RUNTIME_API_VERSION, + crate::runtime::RUNTIME_KIND, + home.join("bundle").display(), + home.display(), + home.join("audit").join("render.jsonl").display(), + ); + let path = home.join("runtime.yaml"); + std::fs::write(&path, runtime).expect("write the runtime file"); + let (runtime, _) = crate::runtime::load(&path).expect("the runtime file loads"); + verifier(&runtime).await + } + + fn ec_public_key() -> Value { + let set = registry_platform_testing::TokenSigner::new().public_key_set(); + set["keys"] + .as_array() + .expect("a key set lists keys") + .iter() + .find(|key| key["kty"] == "EC") + .expect("the corpus holds an EC key") + .clone() + } + + #[tokio::test] + async fn a_static_key_set_with_unknown_public_members_loads() { + let mut key = ec_public_key(); + key["ext"] = json!(true); + let verifier = verifier_over_static_keys(&json!({ "keys": [key] })) + .await + .expect("a public member the verifier does not read is ignored"); + assert!(verifier.is_some()); + } + + #[tokio::test] + async fn a_static_key_set_with_a_private_member_is_refused_with_the_reason() { + let mut key = ec_public_key(); + key["d"] = json!("private"); + let problem = match verifier_over_static_keys(&json!({ "keys": [key] })).await { + Err(problem) => problem, + Ok(_) => panic!("a key set holding a private member must be refused"), + }; + assert_eq!(problem.kind, ProblemKind::RuntimeInvalid); + assert!( + problem.detail.contains("private-key member \"d\""), + "the detail names the refused member: {}", + problem.detail + ); + assert!( + problem.detail.contains("authentication.oidc.jwksSource"), + "the detail names the setting: {}", + problem.detail + ); + } } diff --git a/crates/registry-render/src/auth/token_characterisation.rs b/crates/registry-render/src/auth/token_characterisation.rs new file mode 100644 index 0000000000..39638776c1 --- /dev/null +++ b/crates/registry-render/src/auth/token_characterisation.rs @@ -0,0 +1,133 @@ +//! Characterises which identity-provider tokens Render's real caller +//! authentication admits, against the token fixture corpus in +//! `products/platform/conformance/tokens`. +//! +//! Each row loads a runtime file the way `serve` does, builds the verifier +//! through `verifier`, and presents the fixture to `authenticate` for the +//! render scope, the call every render and document route makes. The module +//! sits under `auth` so it can also ask the verifier for the check that +//! refused a token, which `AuthenticationError` does not carry. +use super::*; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenFixture, TokenSigner, +}; +use serde_json::Value; +use std::path::Path; + +const ISSUER: &str = "https://issuer.example.test"; +const AUDIENCE: &str = "urn:render:test"; +const KEY_FILE: &str = "issuer-keys.json"; +const PLACEHOLDER_CLIENT: &str = "journey-app"; + +fn literal(fixture: &TokenFixture, claim: &str) -> Option { + match fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the token names, read the way the verifier reads it. +fn client_of(fixture: &TokenFixture) -> Option { + literal(fixture, "azp").or_else(|| literal(fixture, "client_id")) +} + +/// A runtime file for one row. The recipe for a token that names no client +/// writes `unrestricted`, as the runtime allows; every other row lists +/// the fixture's client, or a placeholder when the token names none. +fn write_runtime(home: &Path, case: &FixtureCase) -> std::path::PathBuf { + let clients = match (client_of(&case.fixture), case.configuration) { + (Some(client), _) => format!("[{client}]"), + (None, Configuration::Recipe) => "unrestricted".to_owned(), + (None, _) => format!("[{PLACEHOLDER_CLIENT}]"), + }; + let runtime = format!( + "apiVersion: {}\nkind: {}\nlistener:\n bind: 127.0.0.1:18080\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n oidc:\n issuer: {}\n audience: {}\n allowedClients: {}\n jwksSource:\n type: static\n documentRef: secret:file/{KEY_FILE}\naudit:\n path: {}\n", + crate::runtime::RUNTIME_API_VERSION, + crate::runtime::RUNTIME_KIND, + home.join("bundle").display(), + home.display(), + case.issuer, + case.audience, + clients, + home.join("audit").join("render.jsonl").display(), + ); + let path = home.join("runtime.yaml"); + std::fs::write(&path, runtime).expect("write the runtime file"); + path +} + +async fn observe(verifier: &TokenVerifier, token: &str) -> Outcome { + let verdict = verifier.verify(token).await; + let admission = authenticate(verifier, token, RENDER_SCOPE).await; + match (admission, verdict) { + (Ok(_), Ok(_)) => Outcome::Admitted(None), + (Ok(_), Err(_)) => panic!("authenticate admitted a token its own verifier refused"), + (Err(refused), Err(error)) => { + assert_eq!( + refused.failed_check(), + error.failed_check(), + "the recorded check is the verifier's" + ); + Outcome::refused_by(&error) + } + (Err(AuthenticationError::Forbidden { .. }), Ok(_)) => { + "refused/scope".parse().expect("result value") + } + (Err(AuthenticationError::Refused(_)), Ok(_)) => { + "refused/claims".parse().expect("result value") + } + (Err(AuthenticationError::Unavailable), Ok(_)) => { + "refused/unavailable".parse().expect("result value") + } + } +} + +/// The corpus public keys a static key document may hold: it admits RSA and +/// EC keys only, so the corpus's EdDSA key is left out. +fn static_key_document(signer: &TokenSigner) -> String { + let mut keys = signer.public_key_set(); + keys["keys"] + .as_array_mut() + .expect("a key set lists keys") + .retain(|key| key["kty"] != "OKP"); + keys.to_string() +} + +#[tokio::test] +async fn caller_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let signer = TokenSigner::new(); + let scratch = tempfile::tempdir().expect("home directory"); + let home = scratch + .path() + .canonicalize() + .expect("physical home directory"); + std::fs::create_dir(home.join("bundle")).expect("package directory"); + std::fs::create_dir(home.join("audit")).expect("audit directory"); + let key_file = home.join(KEY_FILE); + std::fs::write(&key_file, static_key_document(&signer)).expect("write the key set"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(0o600)) + .expect("owner-only key file"); + } + let home = &home; + let report = corpus + .run_product_async("render", &signer, ISSUER, AUDIENCE, |case| async move { + let path = write_runtime(home, &case); + let (runtime, _) = + crate::runtime::load(&path).expect("the runtime file loads and validates"); + let verifier = verifier(&runtime) + .await + .expect("the verifier builds over the static key set") + .expect("the runtime declares oidc authentication"); + observe(&verifier, case.token.expose()).await + }) + .await + .expect("the corpus runs"); + assert!( + report.rows.iter().any(|row| row.observed.is_some()), + "no row ran" + ); + report.assert_matches(); +} diff --git a/crates/registry-render/src/metrics.rs b/crates/registry-render/src/metrics.rs index e3632fe1fd..ff67b247ec 100644 --- a/crates/registry-render/src/metrics.rs +++ b/crates/registry-render/src/metrics.rs @@ -5,8 +5,9 @@ //! reaching the series requires reaching a different, private address. //! //! Every label is closed by construction. `operation` is `render` or `seal`, -//! `result` is a coarse status class, and `seal` is a seal id the operator -//! wrote in the runtime file, so the set is bounded by that file. Document +//! `result` is a coarse status class, `check` is one of the shared refusal +//! checks, and `seal` is a seal id the operator wrote in the runtime file, so +//! the set is bounded by that file. Document //! data, caller identities, request paths and problem details never become //! labels. //! @@ -14,7 +15,9 @@ //! the metrics are scraped. It reads no database and calls no key provider. use axum::http::StatusCode; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{CounterVec, Exposition, LabelSpace, MetricKind}; +use std::sync::Arc; use time::OffsetDateTime; use crate::seal::Seals; @@ -80,6 +83,7 @@ impl Outcome { pub struct Metrics { documents: CounterVec, + refusals: Arc, } impl std::fmt::Debug for Metrics { @@ -105,11 +109,18 @@ impl Default for Metrics { .expect(DECLARATION), ) .expect(DECLARATION), + refusals: Arc::new(RefusalRecorder::new("render").expect(DECLARATION)), } } } impl Metrics { + /// The recorder that counts each refused request under its check and + /// admits a bounded number of log lines. + pub(crate) fn refusal_recorder(&self) -> &Arc { + &self.refusals + } + /// Count one answered call to a document operation under its status /// class. pub fn record_document(&self, operation: Operation, status: StatusCode) { @@ -128,6 +139,7 @@ impl Metrics { pub fn render(&self, audit_write_failures: u64, seals: &Seals, now: OffsetDateTime) -> String { let mut out = Exposition::new(); self.documents.write(&mut out).expect(DECLARATION); + self.refusals.counter().write(&mut out).expect(DECLARATION); out.header( "render_audit_write_failures_total", Some("Audit entries that could not be written."), diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index cbf9d302da..c0943787ae 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -758,7 +758,7 @@ impl AuditRuntime { /// retired apiVersion. #[must_use] pub const fn runtime_loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(RENDER_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(RENDER_RUNTIME_ENVELOPE) .removed_keys(RENDER_REMOVED_KEYS) .retired_api_versions(RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -1123,6 +1123,7 @@ fn findings( matches!( oidc.provider.jwks_source, registry_platform_config::JwksSource::Static { .. } + | registry_platform_config::JwksSource::TestIssuer { .. } ) }); if needs_secrets @@ -1136,8 +1137,8 @@ fn findings( } match (&runtime.authentication.oidc, &runtime.authentication.api_key_ref) { (Some(oidc), None) => { - findings.extend([oidc.provider.check("authentication.oidc", true), oidc.clients.check("authentication.oidc")].iter().filter_map(|result| result.as_ref().err()).map(block_finding)); - if let registry_platform_config::JwksSource::Static { document_ref } = &oidc.provider.jwks_source { + findings.extend([oidc.provider.check_without_posture("authentication.oidc", true), oidc.clients.check("authentication.oidc")].iter().filter_map(|result| result.as_ref().err()).map(block_finding)); + if let registry_platform_config::JwksSource::Static { document_ref } | registry_platform_config::JwksSource::TestIssuer { document_ref } = &oidc.provider.jwks_source { if let Err(error) = runtime.secret_providers.check_reference("authentication.oidc.jwksSource.documentRef", document_ref) { findings.push(block_finding(&error)); } } } @@ -3239,6 +3240,8 @@ mod tests { "http://127.0.0.1:3161/tsr", "http://127.0.0.2:3161/tsr", "http://[::1]:3161/tsr", + // An IPv4-mapped form of 127.0.0.0/8 is loopback by the shared rule. + "http://[::ffff:127.0.0.1]/tsr", "https://tsa.example.test/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); @@ -3251,7 +3254,7 @@ mod tests { "http://10.0.0.5/tsr", "http://localhost.example.test/", "http://localhost./tsr", - "http://[::ffff:127.0.0.1]/tsr", + "http://[::ffff:10.0.0.5]/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); let problem = refused(&home, &signing_text(&home, &seal)); diff --git a/crates/registry-render/src/seal.rs b/crates/registry-render/src/seal.rs index dfe3cc7e4c..8f48208bbe 100644 --- a/crates/registry-render/src/seal.rs +++ b/crates/registry-render/src/seal.rs @@ -557,9 +557,8 @@ fn local_jwk_signer( // when it drops after parsing. let secret = crate::runtime::resolve_protected_secret(runtime, private_key_ref).map_err(|error| { - let action = if error == SecretError::UnsafeFile { - "Make the key file a regular file owned by the serving user, with mode 0600 or \ - 0400 and one link." + let action = if matches!(error, SecretError::UnsafeFile(_)) { + error.suggested_action() } else { "Provide the seal's private key under the secret provider the reference names." }; diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index 5d6d848965..61972790e6 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -28,13 +28,14 @@ use serde::{Deserialize, Serialize}; use subtle::ConstantTimeEq; use registry_platform_authcommon::{ - parse_bearer_token, validate_api_key_entropy, MIN_API_KEY_ENTROPY_BYTES, + parse_bearer_token, validate_api_key_entropy, BearerParseError, DeclaredScope, FailedCheck, + RefusalNote, RefusalRecorder, MIN_API_KEY_ENTROPY_BYTES, }; use registry_platform_canonical_json::parse_json_preserving_integers; -use registry_platform_httpsec::{request_body_limit, security_headers, CspBuilder}; +use registry_platform_httpsec::{request_body_limit, security_headers_without_posture, CspBuilder}; use crate::audit::{RenderAudit, RenderAuditEvent}; -use crate::auth::{RENDER_SCOPE, SEAL_SCOPE}; +use crate::auth::{RENDER_SCOPE, SCOPE_CLAIM, SEAL_SCOPE}; use crate::bundle::Bundle; use crate::hash::sha256_label; use crate::metrics::{Metrics, Operation, METRICS_PATH}; @@ -266,12 +267,7 @@ async fn serve_async(runtime_path: &Path) -> Result { } None => None, }; - let app = router(Arc::clone(&service)) - .layer(axum::middleware::from_fn(lifecycle_log)) - .layer(axum::middleware::from_fn_with_state( - Arc::clone(&metrics), - count_documents, - )); + let app = public_app(Arc::clone(&service), &metrics); let grace = runtime.listener.shutdown_grace(); let drain_service = Arc::clone(&service); // The stop signal is observed once and broadcast, so the drain and the @@ -437,7 +433,22 @@ pub(crate) fn router(service: Arc) -> Router { } app.fallback(not_found) .with_state(service) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) +} + +/// The public application: the router under the request log, the refusal +/// recording and the document counter. +fn public_app(service: Arc, metrics: &Arc) -> Router { + router(service) + .layer(axum::middleware::from_fn_with_state( + Arc::clone(metrics.refusal_recorder()), + record_refusals, + )) + .layer(axum::middleware::from_fn(lifecycle_log)) + .layer(axum::middleware::from_fn_with_state( + Arc::clone(metrics), + count_documents, + )) } /// The caller guidance a credential without `render:seal` receives on the @@ -478,11 +489,14 @@ async fn require_bearer( Ok(caller) => caller, Err(error) => { use crate::auth::AuthenticationError; + let check = error.failed_check(); let (kind, caller) = match error { - AuthenticationError::Refused => (ProblemKind::Unauthorized, "unknown".to_owned()), - AuthenticationError::Forbidden { caller_fingerprint } => { - (ProblemKind::Forbidden, caller_fingerprint) + AuthenticationError::Refused(_) => { + (ProblemKind::Unauthorized, "unknown".to_owned()) } + AuthenticationError::Forbidden { + caller_fingerprint, .. + } => (ProblemKind::Forbidden, caller_fingerprint), AuthenticationError::Unavailable => { (ProblemKind::AuthenticationUnavailable, "unknown".to_owned()) } @@ -492,7 +506,12 @@ async fn require_bearer( problem = problem.with_public_detail(SEAL_SCOPE_GUIDANCE); } let (path, headers) = (request.uri().path(), request.headers()); - return refuse_access(&service, path, headers, &problem, &caller).await; + let mut response = + refuse_access(&service, path, headers, &problem, &caller, check).await; + if check == FailedCheck::Scope { + response.extensions_mut().insert(declared_scope(scope)); + } + return response; } }; // The legacy API key never seals. The runtime already refuses a signing @@ -501,19 +520,29 @@ async fn require_bearer( let problem = RenderProblem::new(ProblemKind::Forbidden, "the legacy API key cannot seal") .with_public_detail(LEGACY_KEY_GUIDANCE); let (path, headers) = (request.uri().path(), request.headers()); - return refuse_access(&service, path, headers, &problem, &caller.fingerprint).await; + return refuse_access( + &service, + path, + headers, + &problem, + &caller.fingerprint, + FailedCheck::Operation, + ) + .await; } request.extensions_mut().insert(caller); next.run(request).await } -/// Audit an access refusal as one response entry, then answer with it. +/// Audit an access refusal as one response entry, then answer with it. The +/// answer carries the check that refused the caller for the recording layer. async fn refuse_access( service: &Service, path: &str, headers: &HeaderMap, problem: &RenderProblem, caller: &str, + check: FailedCheck, ) -> Response { let target = sanitize_route_target(path); let correlation = correlation_id(headers); @@ -529,7 +558,49 @@ async fn refuse_access( if let Err(audit_problem) = service.audit.response(&envelope, event).await { return problem_response(&audit_problem, trace.as_deref()); } - problem_response(problem, trace.as_deref()) + refusal_response(problem, trace.as_deref(), check) +} + +/// A refusal answer with the check that refused the caller in its response +/// extensions, which are never serialized. +fn refusal_response(problem: &RenderProblem, trace: Option<&str>, check: FailedCheck) -> Response { + let mut response = problem_answer(problem, trace); + response.extensions_mut().insert(RefusalNote::new(check)); + response +} + +/// The values the operator declared for a scope refusal: the claim Render +/// reads scopes from and the scope the route requires. Nothing here comes +/// from the caller's token. +fn declared_scope(required_scope: &str) -> DeclaredScope { + DeclaredScope::new(SCOPE_CLAIM).with_required_scope(required_scope) +} + +/// Count each refusal answer under its check and write the admitted log line. +/// The trace id is the one the answer carries. +async fn record_refusals( + State(refusals): State>, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::() { + let declared = response.extensions().get::(); + match registry_platform_httpsec::response_trace_id(response.headers()) { + Ok(trace) => { + registry_platform_authcommon::record_refusal!( + refusals, + *note, + trace_id = trace, + declared = declared + ); + } + Err(_) => { + registry_platform_authcommon::record_refusal!(refusals, *note, declared = declared); + } + } + } + response } /// The verified caller of an API route. @@ -662,7 +733,7 @@ pub fn metrics_router(service: Arc, metrics: Arc) -> Router { Router::new() .route(METRICS_PATH, get(serve_metrics)) .with_state(MetricsState { metrics, service }) - .layer(security_headers(CspBuilder::restrictive())) + .layer(security_headers_without_posture(CspBuilder::restrictive())) } async fn serve_metrics(State(state): State) -> Response { @@ -704,9 +775,24 @@ fn route_template(path: &str) -> &'static str { } } +/// An answer that is not a refusal of the caller. A 401 or 403 goes through +/// `refusal_response` so it carries the check that refused the caller: a +/// refusal status that arrives here has no check to count, which a debug +/// build refuses outright and a release build logs. +fn problem_response(problem: &RenderProblem, trace: Option<&str>) -> Response { + if matches!(problem.kind.http_status(), 401 | 403) { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.kind.http_code(), + "a refusal was answered without its failed check" + ); + } + problem_answer(problem, trace) +} + /// HTTP callers receive fixed, value-free guidance. Operator diagnostics stay /// with the local CLI and audit boundary; the problem code identifies recovery. -fn problem_response(problem: &RenderProblem, trace: Option<&str>) -> Response { +fn problem_answer(problem: &RenderProblem, trace: Option<&str>) -> Response { let mut context = registry_platform_httpsec::TraceContext::server_created(); if let Some(trace_id) = trace.and_then(|value| registry_platform_httpsec::TraceId::parse(value).ok()) @@ -935,12 +1021,24 @@ async fn authorized( ) -> Result { use crate::auth::AuthenticationError; let mut values = headers.get_all(header::AUTHORIZATION).iter(); - let value = values.next().ok_or(AuthenticationError::Refused)?; + let value = values + .next() + .ok_or(AuthenticationError::Refused(FailedCheck::CredentialMissing))?; if values.next().is_some() { - return Err(AuthenticationError::Refused); + return Err(AuthenticationError::Refused( + FailedCheck::CredentialMalformed, + )); } - let token = parse_bearer_token(value.to_str().map_err(|_| AuthenticationError::Refused)?) - .map_err(|_| AuthenticationError::Refused)?; + let malformed = || AuthenticationError::Refused(FailedCheck::CredentialMalformed); + let token = + parse_bearer_token(value.to_str().map_err(|_| malformed())?).map_err( + |error| match error { + BearerParseError::InvalidScheme => { + AuthenticationError::Refused(FailedCheck::CredentialMissing) + } + _ => malformed(), + }, + )?; if let Some(verifier) = &service.oidc { let verified = crate::auth::authenticate(verifier, token, scope).await?; return Ok(Caller { @@ -955,7 +1053,7 @@ async fn authorized( fingerprint: service.caller_fingerprint.clone(), client_id: None, }) - .ok_or(AuthenticationError::Refused) + .ok_or(AuthenticationError::Refused(FailedCheck::SharedSecret)) } /// Caller-supplied trace id from a W3C traceparent header, fully @@ -1142,12 +1240,45 @@ struct SealCall { } impl SealCall { - /// Refuse the call before any render starts: one response entry naming - /// the seal when it is known, accepted before responding. + /// Refuse the call before any render starts for a reason that is not a + /// caller refusal: one response entry naming the seal when it is known, + /// accepted before responding. A 401 or 403 goes through `refuse_checked`, + /// so every refused caller carries the check that refused it. async fn refuse(&self, service: &Service, problem: RenderProblem) -> Response { + debug_assert!( + !matches!(problem.kind.http_status(), 401 | 403), + "a refused caller is answered by refuse_checked" + ); + match self.audit_refusal(service, &problem).await { + Ok(()) => problem_response(&problem, self.trace.as_deref()), + Err(answer) => answer, + } + } + + /// Refuse the call as `refuse` does, and record the check that refused + /// the caller. + async fn refuse_checked( + &self, + service: &Service, + problem: RenderProblem, + check: FailedCheck, + ) -> Response { + match self.audit_refusal(service, &problem).await { + Ok(()) => refusal_response(&problem, self.trace.as_deref(), check), + Err(answer) => answer, + } + } + + /// Write the refusal's response entry. When the audit write fails the + /// answer is the audit failure. + async fn audit_refusal( + &self, + service: &Service, + problem: &RenderProblem, + ) -> Result<(), Response> { let mut event = RenderAuditEvent::refused( &self.document_type, - &problem, + problem, &self.caller, self.correlation.as_deref(), self.trace.as_deref(), @@ -1155,10 +1286,11 @@ impl SealCall { if let Some(seal_id) = &self.seal_id { event = event.for_seal(seal_id, self.test_only); } - if let Err(audit_problem) = service.audit.response(&self.envelope, event).await { - return problem_response(&audit_problem, self.trace.as_deref()); - } - problem_response(&problem, self.trace.as_deref()) + service + .audit + .response(&self.envelope, event) + .await + .map_err(|audit_problem| problem_response(&audit_problem, self.trace.as_deref())) } } @@ -1234,7 +1366,9 @@ async fn seal_route( ProblemKind::SealClientNotAllowed, format!("the verified client is not in signing.seals.{seal_id}.allowedClients"), ); - return call.refuse(&service, problem).await; + return call + .refuse_checked(&service, problem, FailedCheck::RequesterClient) + .await; } seal.recover_signer().await; // One clock reading decides availability and is the signing time. @@ -1890,7 +2024,9 @@ mod tests { Bundle::load_package(&bundle_path, &verified).expect("packaged receipt bundle"); Arc::new(Service { bundle, - audit: RenderAudit::new(AuditWriter::from_line_sink(Box::new(lines.clone()))), + audit: RenderAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + lines.clone(), + ))), api_key: TEST_API_KEY.as_bytes().to_vec(), oidc: None, caller_fingerprint: "caller-fingerprint".to_owned(), @@ -2609,4 +2745,524 @@ mod tests { assert_eq!(phases, &["request", "response"]); } } + + /// One refused answer, as the golden freezes it: status, the headers a + /// caller or proxy acts on, and the body without its per-request trace id. + async fn frozen_answer(response: Response) -> serde_json::Value { + let status = response.status().as_u16(); + let mut headers = serde_json::Map::new(); + for name in [ + "content-type", + "www-authenticate", + "cache-control", + "retry-after", + ] { + let values: Vec = response + .headers() + .get_all(name) + .iter() + .map(|value| value.to_str().expect("ASCII header").into()) + .collect(); + match values.len() { + 0 => {} + 1 => { + headers.insert(name.to_owned(), values[0].clone()); + } + _ => { + headers.insert(name.to_owned(), values.into()); + } + } + } + let bytes = axum::body::to_bytes(response.into_body(), 16384) + .await + .expect("body"); + let mut body: serde_json::Value = serde_json::from_slice(&bytes).expect("problem body"); + assert!(body["traceId"].is_string(), "{body}"); + body.as_object_mut().expect("object").remove("traceId"); + serde_json::json!({"status": status, "headers": headers, "body": body}) + } + + fn bearer_request( + method: Method, + uri: &str, + authorization: &[Vec], + ) -> axum::extract::Request { + let mut request = axum::http::Request::builder().method(method).uri(uri); + for value in authorization { + request = request.header( + header::AUTHORIZATION, + header::HeaderValue::from_bytes(value).expect("header value"), + ); + } + request + .header(header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from("{}")) + .expect("request") + } + + /// The service a refusal case runs against. + #[derive(Clone, Copy)] + enum Mode { + /// The legacy API key. + Legacy, + /// An OIDC verifier over a static key set. + Oidc, + /// The legacy API key on a service that loaded a seal. + LegacySealed, + /// An OIDC verifier and a seal that allows a different client. + OidcSealed, + /// An OIDC verifier whose key source answers 503. + Outage, + } + + async fn refusal_service(mode: Mode) -> Arc { + use registry_platform_crypto::document_signature::test_support::TestPki; + let lines = AuditLines::new(None); + let mut service = service(&lines, 1); + let inner = Arc::get_mut(&mut service).expect("fixture owns service"); + if matches!(mode, Mode::Oidc | Mode::OidcSealed) { + inner.oidc = Some(crate::auth::tests::test_verifier()); + } + if matches!(mode, Mode::Outage) { + let origin = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("key source listener"); + let url = format!("http://{}/jwks", origin.local_addr().expect("address")); + let keys_app = + Router::new().route("/jwks", get(|| async { StatusCode::SERVICE_UNAVAILABLE })); + tokio::spawn(async move { + axum::serve(origin, keys_app).await.expect("key source"); + }); + let fetch_policy = registry_platform_oidc::IssuerNetworkPolicy::new(&url, true) + .expect("loopback policy") + .declared_jwks_fetch_policy(); + inner.oidc = Some(crate::auth::tests::test_verifier_over(Arc::new( + registry_platform_oidc::JwksFetcher::new_with_fetch_url_policy( + url, + registry_platform_oidc::JwksFetcherConfig::defaults(), + fetch_policy, + ), + ))); + } + if matches!(mode, Mode::LegacySealed | Mode::OidcSealed) { + let pki = TestPki::generate().expect("test PKI"); + let test_seal = pki + .issue_seal(registry_platform_crypto::SigningAlgorithm::Es256) + .expect("test seal"); + let signer = Arc::new(test_seal.signer().expect("test signer")); + inner.seals.insert( + "ministry".to_owned(), + Arc::new(Seal::for_test("ministry", &test_seal, signer)), + ); + // The receipt names the seal, as a sealable document type does. + inner + .bundle + .documents + .get_mut("receipt") + .expect("receipt document") + .spec + .seal = Some("ministry".to_owned()); + } + service + } + + fn token_header(overrides: serde_json::Value) -> Option { + Some(format!("Bearer {}", crate::auth::tests::token(overrides))) + } + + /// One refusal: its name, the service, the request, and the check that + /// must refuse it. + struct RefusalCase { + name: &'static str, + mode: Mode, + method: Method, + uri: &'static str, + /// The `Authorization` header values, in order. + authorization: Vec>, + check: &'static str, + } + + impl RefusalCase { + fn new( + name: &'static str, + mode: Mode, + method: Method, + uri: &'static str, + credential: Option, + check: &'static str, + ) -> Self { + Self { + name, + mode, + method, + uri, + authorization: credential.into_iter().map(String::into_bytes).collect(), + check, + } + } + + /// A case that sends the given `Authorization` header values as they + /// are, repeated or not ASCII included. + fn raw(mut self, authorization: Vec>) -> Self { + self.authorization = authorization; + self + } + } + + /// A client id no refusal answer or log line may repeat. + const CANARY_CLIENT: &str = "canary-client-0123456789"; + + /// Every refusal the access layers and the seal handler make, with the + /// check each one must record. + fn refusal_cases() -> Vec { + let legacy = |key: &str| Some(format!("Bearer {key}")); + vec![ + RefusalCase::new( + "no-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-missing", + ), + RefusalCase::new( + "scheme-not-bearer", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Basic dXNlcjpwYXNz".to_owned()), + "credential-missing", + ), + RefusalCase::new( + "empty-bearer-token", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Bearer ".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "value-shorter-than-the-scheme", + Mode::Legacy, + Method::GET, + "/v1/documents", + Some("Basic".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "repeated-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-malformed", + ) + .raw(vec![b"Bearer first".to_vec(), b"Bearer second".to_vec()]), + RefusalCase::new( + "non-ascii-authorization-header", + Mode::Legacy, + Method::GET, + "/v1/documents", + None, + "credential-malformed", + ) + .raw(vec![b"Bearer caf\xe9".to_vec()]), + RefusalCase::new( + "legacy-key-mismatch", + Mode::Legacy, + Method::GET, + "/v1/documents", + legacy("canary-wrong-key-0123456789abcdef0123456789"), + "shared-secret", + ), + RefusalCase::new( + "compact-token-shape", + Mode::Oidc, + Method::GET, + "/v1/documents", + Some("Bearer canary-invalid-token".to_owned()), + "credential-malformed", + ), + RefusalCase::new( + "token-audience", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"aud":"urn:other"})), + "token-audience", + ), + RefusalCase::new( + "token-expired", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"exp":1})), + "token-time", + ), + RefusalCase::new( + "token-client", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"client_id":"other"})), + "token-client", + ), + RefusalCase::new( + "token-client-canary", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"client_id":CANARY_CLIENT})), + "token-client", + ), + RefusalCase::new( + "scope-on-render-route", + Mode::Oidc, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({"scope":"canary-token-scope"})), + "scope", + ), + RefusalCase::new( + "render-scope-on-seal-route", + Mode::OidcSealed, + Method::POST, + "/v1/seal/receipt", + token_header(serde_json::json!({})), + "scope", + ), + RefusalCase::new( + "legacy-key-on-seal-route", + Mode::LegacySealed, + Method::POST, + "/v1/seal/receipt", + legacy(TEST_API_KEY), + "operation", + ), + RefusalCase::new( + "key-source-unavailable", + Mode::Outage, + Method::GET, + "/v1/documents", + token_header(serde_json::json!({})), + "key-source-unavailable", + ), + RefusalCase::new( + "seal-client-not-allowed", + Mode::OidcSealed, + Method::POST, + "/v1/seal/receipt", + token_header(serde_json::json!({"scope":"render:seal"})), + "requester-client", + ), + ] + } + + /// The refusals as the whole stack answers them, frozen in a checked-in + /// file that was written from the tree before any recording existed. Run + /// with `REGISTRY_RENDER_WRITE_GOLDEN=1` to rewrite it. + #[tokio::test] + async fn refusal_answers_match_the_golden() { + let mut answers = serde_json::Map::new(); + for RefusalCase { + name, + mode, + method, + uri, + authorization, + .. + } in refusal_cases() + { + let service = refusal_service(mode).await; + let response = refusal_stack(service, &Arc::new(Metrics::default())) + .oneshot(bearer_request(method, uri, &authorization)) + .await + .expect("router"); + answers.insert(name.to_owned(), frozen_answer(response).await); + } + let actual = serde_json::Value::Object(answers); + let path = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/authentication_refusals.json"); + if std::env::var_os("REGISTRY_RENDER_WRITE_GOLDEN").is_some() { + std::fs::create_dir_all(path.parent().expect("parent")).expect("golden directory"); + std::fs::write( + &path, + format!("{}\n", serde_json::to_string_pretty(&actual).expect("json")), + ) + .expect("write golden"); + } + let expected: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).expect("golden file")) + .expect("golden json"); + assert_eq!(actual, expected); + } + + /// The stack `serve` builds around the router, for the refusal tests. + fn refusal_stack(service: Arc, metrics: &Arc) -> Router { + public_app(service, metrics) + } + + /// A subscriber that keeps every formatted line in memory. + #[derive(Clone, Default)] + struct LogCapture(Arc>>); + + impl std::io::Write for LogCapture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().expect("log").extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture { + type Writer = Self; + + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + + /// Every refusal is counted once under the check that refused it, writes + /// one value-free log line that names that check and the request's trace + /// id, and leaves every other check at zero. + #[tokio::test] + async fn each_refusal_is_counted_and_logged_under_its_check() { + let canaries = [ + "canary-wrong-key-0123456789abcdef0123456789", + "canary-invalid-token", + "canary-principal", + "canary-token-scope", + CANARY_CLIENT, + ]; + for RefusalCase { + name, + mode, + method, + uri, + authorization, + check, + } in refusal_cases() + { + let logs = LogCapture::default(); + let subscriber = tracing_subscriber::fmt() + .json() + .with_max_level(tracing::Level::INFO) + .with_writer(logs.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let service = refusal_service(mode).await; + let metrics = Arc::new(Metrics::default()); + let response = refusal_stack(Arc::clone(&service), &metrics) + .oneshot(bearer_request(method, uri, &authorization)) + .await + .expect("router"); + let trace = registry_platform_httpsec::response_trace_id(response.headers()) + .expect("trace id") + .to_string(); + let text = scraped(&service, &metrics).await; + let counted: Vec<&str> = text + .lines() + .filter(|line| line.starts_with("render_request_refusals_total{")) + .filter(|line| !line.ends_with(" 0")) + .collect(); + assert_eq!( + counted, + [format!( + "render_request_refusals_total{{check=\"{check}\"}} 1" + )], + "{name}" + ); + let written = String::from_utf8(logs.0.lock().expect("log").clone()).expect("UTF-8"); + // The whole bearer value of a signed token never reaches a log line. + for value in &authorization { + if let Some(token) = value + .strip_prefix(b"Bearer ") + .filter(|token| token.len() > 40) + { + let token = String::from_utf8_lossy(token); + assert!(!written.contains(token.as_ref()), "{name}: {written}"); + } + } + let lines: Vec = written + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON log line")) + .filter(|line| line["fields"]["message"] == "request refused") + .collect(); + assert_eq!(lines.len(), 1, "{name}: {written}"); + let fields = &lines[0]["fields"]; + assert_eq!(fields["decision"], "refused", "{name}"); + assert_eq!(fields["failed_check"], check, "{name}"); + assert_eq!(fields["trace_id"], trace.as_str(), "{name}"); + // A scope refusal names the values the operator declared. Every + // other check names none. + if check == "scope" { + assert_eq!(fields["scope_claim"], "scope", "{name}"); + let required = if uri.starts_with("/v1/seal/") { + SEAL_SCOPE + } else { + RENDER_SCOPE + }; + assert_eq!(fields["required_scope"], required, "{name}"); + assert!(fields.get("access_profile").is_none(), "{name}"); + } else { + for field in ["scope_claim", "required_scope", "access_profile"] { + assert!(fields.get(field).is_none(), "{name}: {field}"); + } + } + for canary in canaries { + assert!(!written.contains(canary), "{name}: {written}"); + } + } + } + + #[tokio::test] + async fn the_refusal_counter_is_exposed_from_zero_for_every_check() { + let service = refusal_service(Mode::Legacy).await; + let text = scraped(&service, &Arc::new(Metrics::default())).await; + assert!(text.contains( + "# HELP render_request_refusals_total Requests refused, by the check that failed.\n# TYPE render_request_refusals_total counter\n" + )); + for check in registry_platform_authcommon::FailedCheck::ALL { + assert!( + text.contains(&format!( + "render_request_refusals_total{{check=\"{}\"}} 0", + check.as_str() + )), + "{}", + check.as_str() + ); + } + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a refusal was built without its failed check")] + fn a_refusal_status_without_its_check_is_not_built() { + for kind in [ + ProblemKind::Unauthorized, + ProblemKind::Forbidden, + ProblemKind::SealClientNotAllowed, + ] { + let _ = problem_response(&RenderProblem::new(kind, "no check"), None); + } + } + + #[test] + fn a_refusal_with_its_check_is_built_without_the_guard() { + for kind in [ + ProblemKind::Unauthorized, + ProblemKind::Forbidden, + ProblemKind::SealClientNotAllowed, + ] { + let response = refusal_response( + &RenderProblem::new(kind, "with check"), + None, + FailedCheck::Operation, + ); + assert!(response.extensions().get::().is_some()); + } + } } diff --git a/crates/registry-render/tests/golden/authentication_refusals.json b/crates/registry-render/tests/golden/authentication_refusals.json new file mode 100644 index 0000000000..b33ac551e1 --- /dev/null +++ b/crates/registry-render/tests/golden/authentication_refusals.json @@ -0,0 +1,252 @@ +{ + "compact-token-shape": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "empty-bearer-token": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "key-source-unavailable": { + "body": { + "code": "render.authentication-unavailable", + "detail": "Credential verification is unavailable; retry when the issuer keys are available.", + "status": 503, + "title": "authentication-unavailable", + "type": "https://render.registrystack.org/problems/authentication-unavailable" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 503 + }, + "legacy-key-mismatch": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "legacy-key-on-seal-route": { + "body": { + "code": "render.forbidden", + "detail": "The legacy API key cannot seal; present an OIDC resource credential with the render:seal scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "no-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "non-ascii-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "render-scope-on-seal-route": { + "body": { + "code": "render.forbidden", + "detail": "Obtain a Render resource credential with the render:seal scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "repeated-authorization-header": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "scheme-not-bearer": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "scope-on-render-route": { + "body": { + "code": "render.forbidden", + "detail": "Obtain a Render resource credential with the render:render scope.", + "status": 403, + "title": "forbidden", + "type": "https://render.registrystack.org/problems/forbidden" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "seal-client-not-allowed": { + "body": { + "code": "render.seal-client-not-allowed", + "detail": "This client is not allowed to use this document type's seal.", + "status": 403, + "title": "seal-client-not-allowed", + "type": "https://render.registrystack.org/problems/seal-client-not-allowed" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json" + }, + "status": 403 + }, + "token-audience": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-client": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-client-canary": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "token-expired": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + }, + "value-shorter-than-the-scheme": { + "body": { + "code": "render.unauthorized", + "detail": "Present a valid bearer credential for this Render resource.", + "status": 401, + "title": "unauthorized", + "type": "https://render.registrystack.org/problems/unauthorized" + }, + "headers": { + "cache-control": "no-store", + "content-type": "application/problem+json", + "www-authenticate": "Bearer" + }, + "status": 401 + } +} diff --git a/crates/registry-render/tests/serve.rs b/crates/registry-render/tests/serve.rs index 4525a5adbd..2450eeee61 100644 --- a/crates/registry-render/tests/serve.rs +++ b/crates/registry-render/tests/serve.rs @@ -405,6 +405,10 @@ fn the_metrics_listener_serves_the_series_and_the_api_listener_does_not() { body.contains("render_documents_total{operation=\"render\",result=\"refused\"} 1"), "{body}" ); + assert!( + body.contains("render_request_refusals_total{check=\"credential-missing\"} 1"), + "{body}" + ); assert!( body.contains("\nrender_audit_write_failures_total 0\n"), "{body}" @@ -1103,6 +1107,7 @@ fn a_render_writes_a_request_entry_then_a_response_entry_sharing_correlation() { "correlation", "eventId", "phase", + "posture", "record", "schema", "time" diff --git a/crates/registry-render/tests/serve_seal.rs b/crates/registry-render/tests/serve_seal.rs index 7ff8244cf2..b4172affc0 100644 --- a/crates/registry-render/tests/serve_seal.rs +++ b/crates/registry-render/tests/serve_seal.rs @@ -2008,7 +2008,7 @@ fn an_unusable_key_file_names_its_reason_and_fix() { stderr.contains("the referenced secret file is unsafe"), "{stderr}" ); - assert!(stderr.contains("mode 0600"), "{stderr}"); + assert!(stderr.contains("mode 0400 or 0600"), "{stderr}"); assert!( stderr.contains(&seal_member_position(&fixture, "privateKeyRef:")), "{stderr}" @@ -2025,7 +2025,7 @@ fn an_unusable_key_file_names_its_reason_and_fix() { stderr.contains("the referenced secret is unavailable"), "{stderr}" ); - assert!(!stderr.contains("mode 0600"), "{stderr}"); + assert!(!stderr.contains("0400 or 0600"), "{stderr}"); assert!( stderr.contains("Provide the seal's private key"), "{stderr}" diff --git a/crates/registry-review-client/src/client.rs b/crates/registry-review-client/src/client.rs index 724e56993e..45d3ffa523 100644 --- a/crates/registry-review-client/src/client.rs +++ b/crates/registry-review-client/src/client.rs @@ -6,7 +6,7 @@ use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_review_protocol::{ review_cancel_path, review_request_path, review_result_path, ReviewCancelRequest, @@ -732,7 +732,7 @@ impl ReviewClient { .map_err(|error| ReviewClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()) + validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| protocol(response.status(), ReviewProtocolFailure::HeaderBounds, None))?; Ok(response) } diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index 15fefe903e..82b740baee 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -42,6 +42,7 @@ registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-httputil.workspace = true +registry-platform-provision.workspace = true registry-platform-yaml.workspace = true reqwest.workspace = true rustix.workspace = true diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 1305474153..6e47652df9 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -9,6 +9,10 @@ use std::{ use anyhow::{anyhow, bail, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use registry_platform_provision::{ + plan, sql::quote_identifier, Plan, ProductDatabase, ProvisionTarget, RoleCredential, + SchemaLayout, Scope, Spatial, +}; use rustls::pki_types::{pem::PemObject as _, CertificateDer}; use serde::{Deserialize, Serialize}; use sha2::{Digest as _, Sha256}; @@ -437,13 +441,20 @@ impl Database { let migration_password = random_password()?; let runtime_password = random_password()?; + let batches = Batches::new( + &names, + breg, + requires_postgis, + &migration_password, + &runtime_password, + )?; self.create_role(&names.migration_role, &migration_password)?; self.create_role(&names.runtime_role, &runtime_password)?; - if requires_postgis { - self.create_spatial_bbox_role(&names)?; + if let Some(statement) = &batches.bbox_role { + self.create_spatial_bbox_role(&spatial_bbox_role(&names), statement)?; } - self.create_database(&names)?; - self.configure_database(&names, breg, requires_postgis)?; + self.create_database(&names, &batches)?; + self.configure_database(&names, &batches)?; Ok(DatabaseUrls { runtime: self.product_url(&names.database, &names.runtime_role, &runtime_password)?, @@ -610,7 +621,9 @@ impl Database { let verifier = Zeroizing::new(postgres_protocol::password::scram_sha_256( password.as_bytes(), )); - let statement = Zeroizing::new(create_role_sql(role, &verifier)); + let statement = Zeroizing::new(registry_platform_provision::sql::create_role_sql( + role, &verifier, + )); self.create_owned_role( role, &statement, @@ -618,14 +631,8 @@ impl Database { ) } - fn create_spatial_bbox_role(&mut self, names: &Names) -> Result<()> { - let role = spatial_bbox_role(names); - let statement = create_nologin_role_sql(&role); - self.create_owned_role( - &role, - &statement, - "cannot create the BReg spatial bbox role", - ) + fn create_spatial_bbox_role(&mut self, role: &str, statement: &str) -> Result<()> { + self.create_owned_role(role, statement, "cannot create the BReg spatial bbox role") } fn create_owned_role( @@ -646,13 +653,12 @@ impl Database { created.map_err(anyhow::Error::new).context(context) } - fn create_database(&mut self, names: &Names) -> Result<()> { - let statement = format!( - "CREATE DATABASE {} WITH ALLOW_CONNECTIONS false", - quote_identifier(&names.database) + fn create_database(&mut self, names: &Names, batches: &Batches) -> Result<()> { + let created = self.execute_admin_operation( + &batches.create_database, + "database creation", + OPERATION_TIMEOUT, ); - let created = - self.execute_admin_operation(&statement, "database creation", OPERATION_TIMEOUT); retain_create_acquisition( &mut self.acquisitions, Acquisition::Database(names.database.clone()), @@ -662,13 +668,13 @@ impl Database { .map_err(anyhow::Error::new) .context("cannot create an isolated PostgreSQL database")?; - self.execute_admin(&database_access_sql(names)) + self.execute_admin(&batches.access) .context("cannot restrict the PostgreSQL database to this run's roles") } - fn configure_database(&self, names: &Names, breg: bool, requires_postgis: bool) -> Result<()> { - let statement = database_setup_sql(names, breg); - let postgis = requires_postgis.then(|| postgis_prerequisites_sql(names)); + fn configure_database(&self, names: &Names, batches: &Batches) -> Result<()> { + let statement = &batches.setup; + let postgis = &batches.postgis; let mut target = self.admin_config.clone(); target.dbname(&names.database).ssl_mode(SslMode::Require); @@ -681,14 +687,14 @@ impl Database { let connection_task = tokio::spawn(connection); let executed = tokio::time::timeout(OPERATION_TIMEOUT, async { client - .batch_execute(&statement) + .batch_execute(statement) .await .map_err(|error| { OperationFailure::postgres("database configuration", error) }) .map_err(anyhow::Error::new) .context("cannot configure the provisioned PostgreSQL database")?; - if let Some(postgis) = &postgis { + if let Some(postgis) = postgis { client .batch_execute(postgis) .await @@ -829,6 +835,90 @@ impl Names { } } +/// The statements one database run sends, taken from the shared provisioning +/// plan and grouped as they are executed: the access statements as one batch +/// on the administrator session, the setup statements as one batch inside the +/// new database, and the PostGIS statements as a second batch there. The login +/// roles are created from their password verifiers, which the plan keeps +/// private. +struct Batches { + bbox_role: Option, + create_database: String, + access: String, + setup: String, + postgis: Option, +} + +impl Batches { + fn new( + names: &Names, + breg: bool, + requires_postgis: bool, + migration_password: &str, + runtime_password: &str, + ) -> Result { + let product = ProductDatabase { + product: "rstack-dev", + layout: if breg { + SchemaLayout::Owned( + BREG_SCHEMAS + .iter() + .map(|schema| (*schema).to_owned()) + .collect(), + ) + } else { + SchemaLayout::PublicForMigration + }, + btree_gist: breg, + spatial: requires_postgis.then(|| Spatial { + schema: POSTGIS_SCHEMA.to_owned(), + bbox_role: spatial_bbox_role(names), + minimum_postgis: MIN_POSTGIS, + }), + }; + let target = ProvisionTarget { + database: names.database.clone(), + migration: RoleCredential::new(&names.migration_role, migration_password), + runtime: RoleCredential::new(&names.runtime_role, runtime_password), + }; + let plan = plan(&product, &target).context("cannot plan the PostgreSQL provisioning")?; + Self::from_plan(&plan) + } + + fn from_plan(plan: &Plan) -> Result { + let printable = |wanted: &dyn Fn(&str, Scope) -> bool| { + plan.statements() + .iter() + .filter(|statement| wanted(statement.step, statement.scope)) + .map(|statement| statement.printable.clone()) + .collect::>() + }; + let one = |step: &str| { + let mut found = printable(&|candidate, _| candidate == step); + match (found.pop(), found.is_empty()) { + (Some(statement), true) => Ok(statement), + _ => Err(anyhow!( + "the provisioning plan has no single {step} statement" + )), + } + }; + let postgis = printable(&|step, _| step == "extension.postgis"); + Ok(Self { + bbox_role: printable(&|step, _| step == "role.spatial-bbox").pop(), + create_database: one("database.create")?, + access: printable(&|step, _| { + step.starts_with("database.") && step != "database.create" + }) + .join("; "), + setup: printable(&|step, scope| { + scope == Scope::Database && step != "extension.postgis" + }) + .join("; "), + postgis: postgis.into_iter().next(), + }) + } +} + fn spatial_bbox_role(names: &Names) -> String { spatial_bbox_role_for(&names.runtime_role) } @@ -853,23 +943,6 @@ fn spatial_bbox_role_for(runtime_role: &str) -> String { /// The schema BReg's generated spatial SQL reads PostGIS from. const POSTGIS_SCHEMA: &str = "registry_spatial_ext"; -/// Administrator-run PostGIS setup for one spatial run: the extension in its -/// own schema, usable by both run roles, and the bbox role the migration role -/// may SET. The bbox role itself is created earlier in provisioning. -fn postgis_prerequisites_sql(names: &Names) -> String { - let migration = quote_identifier(&names.migration_role); - let runtime = quote_identifier(&names.runtime_role); - let bbox = quote_identifier(&spatial_bbox_role(names)); - format!( - "CREATE SCHEMA IF NOT EXISTS {POSTGIS_SCHEMA};\n\ - REVOKE ALL ON SCHEMA {POSTGIS_SCHEMA} FROM PUBLIC;\n\ - CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA {POSTGIS_SCHEMA};\n\ - GRANT USAGE ON SCHEMA {POSTGIS_SCHEMA} TO {migration}, {runtime};\n\ - GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ - GRANT USAGE ON SCHEMA {POSTGIS_SCHEMA} TO {bbox};" - ) -} - fn validate_run_id(run_id: &str) -> Result<()> { if run_id.len() == 32 && run_id @@ -890,56 +963,6 @@ fn validate_label(label: &str) -> Result<()> { } } -fn database_access_sql(names: &Names) -> String { - format!( - "REVOKE ALL ON DATABASE {database} FROM PUBLIC; \ - GRANT CONNECT ON DATABASE {database} TO {migration}, {runtime}; \ - ALTER DATABASE {database} ALLOW_CONNECTIONS true", - database = quote_identifier(&names.database), - migration = quote_identifier(&names.migration_role), - runtime = quote_identifier(&names.runtime_role), - ) -} - -fn create_role_sql(role: &str, verifier: &str) -> String { - format!( - "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD {}", - quote_identifier(role), - quote_literal(verifier) - ) -} - -fn create_nologin_role_sql(role: &str) -> String { - format!( - "CREATE ROLE {} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS", - quote_identifier(role) - ) -} - -fn database_setup_sql(names: &Names, breg: bool) -> String { - if breg { - let schemas = BREG_SCHEMAS - .iter() - .map(|schema| { - format!( - "CREATE SCHEMA {schema} AUTHORIZATION {owner}; \ - REVOKE ALL ON SCHEMA {schema} FROM PUBLIC", - schema = quote_identifier(schema), - owner = quote_identifier(&names.migration_role), - ) - }) - .collect::>() - .join("; "); - format!("CREATE EXTENSION btree_gist; {schemas}") - } else { - format!( - "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ - GRANT USAGE, CREATE ON SCHEMA public TO {}", - quote_identifier(&names.migration_role) - ) - } -} - fn admin_config(admin_url: &str) -> Result<(Config, Endpoint)> { let parsed = Url::parse(admin_url) .map_err(|_| anyhow!("the PostgreSQL admin URL is not a parseable URL"))?; @@ -1061,17 +1084,10 @@ pub(super) fn random_password() -> Result> { Ok(Zeroizing::new(URL_SAFE_NO_PAD.encode(bytes.as_ref()))) } -fn quote_identifier(value: &str) -> String { - format!("\"{}\"", value.replace('"', "\"\"")) -} - -fn quote_literal(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - #[cfg(test)] mod tests { use super::*; + use registry_platform_provision::sql::quote_literal; use std::{future::pending, time::Instant}; const RUN_ID: &str = "0123456789abcdef0123456789abcdef"; @@ -1558,42 +1574,6 @@ mod tests { } } - #[test] - fn database_access_is_closed_to_public_before_connections_are_enabled() { - let names = Names::new(RUN_ID, "casework"); - let sql = database_access_sql(&names); - let revoke = sql.find("REVOKE ALL ON DATABASE").unwrap(); - let grant = sql.find("GRANT CONNECT ON DATABASE").unwrap(); - let enable = sql.find("ALLOW_CONNECTIONS true").unwrap(); - assert!(revoke < grant && grant < enable, "{sql}"); - assert!(sql.contains("e_identifier(&names.migration_role))); - assert!(sql.contains("e_identifier(&names.runtime_role))); - } - - #[test] - fn breg_setup_installs_extension_and_all_owned_schemas() { - let names = Names::new(RUN_ID, "breg"); - let sql = database_setup_sql(&names, true); - assert!(sql.starts_with("CREATE EXTENSION btree_gist;"), "{sql}"); - for schema in BREG_SCHEMAS { - assert!( - sql.contains(&format!( - "CREATE SCHEMA {} AUTHORIZATION {}", - quote_identifier(schema), - quote_identifier(&names.migration_role) - )), - "{sql}" - ); - assert!( - sql.contains(&format!( - "REVOKE ALL ON SCHEMA {} FROM PUBLIC", - quote_identifier(schema) - )), - "{sql}" - ); - } - } - #[test] fn spatial_breg_uses_the_governed_bbox_role_for_its_runtime() { for label in ["breg_test", "breg"] { @@ -1602,7 +1582,9 @@ mod tests { assert_eq!(spatial_bbox_role(&names), expected); assert!(expected.starts_with("breg_bbox_")); assert!(expected.len() <= 63); - let statement = create_nologin_role_sql(&expected); + let batches = + Batches::new(&names, true, true, "migration-secret", "runtime-secret").unwrap(); + let statement = batches.bbox_role.unwrap(); assert_eq!( statement, format!( @@ -1660,10 +1642,102 @@ mod tests { assert!(run_object_names(RUN_ID, "other", false).is_err()); } + /// The statements `rstack dev` issued before it used the shared plan, + /// written out as text. The shared plan must keep rendering exactly this + /// for the same input. + #[test] + fn shared_plan_renders_the_statements_rstack_dev_has_always_issued() { + for (label, breg, postgis) in [ + ("breg", true, false), + ("breg", true, true), + ("casework", false, false), + ("messaging", false, false), + ] { + let names = Names::new(RUN_ID, label); + let batches = + Batches::new(&names, breg, postgis, "migration-secret", "runtime-secret").unwrap(); + let (database, migration, runtime) = ( + quote_identifier(&names.database), + quote_identifier(&names.migration_role), + quote_identifier(&names.runtime_role), + ); + assert_eq!( + batches.create_database, + format!("CREATE DATABASE {database} WITH ALLOW_CONNECTIONS false"), + "{label}" + ); + assert_eq!( + batches.access, + format!( + "REVOKE ALL ON DATABASE {database} FROM PUBLIC; \ + GRANT CONNECT ON DATABASE {database} TO {migration}, {runtime}; \ + ALTER DATABASE {database} ALLOW_CONNECTIONS true" + ), + "{label}" + ); + let expected_setup = if breg { + let schemas = BREG_SCHEMAS + .iter() + .map(|schema| { + format!( + "CREATE SCHEMA \"{schema}\" AUTHORIZATION {migration}; \ + REVOKE ALL ON SCHEMA \"{schema}\" FROM PUBLIC" + ) + }) + .collect::>() + .join("; "); + format!("CREATE EXTENSION btree_gist; {schemas}") + } else { + format!( + "REVOKE CREATE ON SCHEMA public FROM PUBLIC; \ + GRANT USAGE, CREATE ON SCHEMA public TO {migration}; \ + GRANT USAGE ON SCHEMA public TO {runtime}" + ) + }; + assert_eq!(batches.setup, expected_setup, "{label}"); + if postgis { + let bbox_role = spatial_bbox_role(&names); + let bbox = quote_identifier(&bbox_role); + assert_eq!( + batches.bbox_role.as_deref(), + Some( + format!( + "CREATE ROLE {bbox} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE \ + NOINHERIT NOBYPASSRLS" + ) + .as_str() + ) + ); + assert_eq!( + batches.postgis.as_deref(), + Some( + format!( + "CREATE SCHEMA IF NOT EXISTS registry_spatial_ext;\n\ + REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC;\n\ + CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {migration}, {runtime};\n\ + GRANT {bbox} TO {migration} WITH INHERIT FALSE, SET TRUE, ADMIN FALSE;\n\ + GRANT USAGE ON SCHEMA registry_spatial_ext TO {bbox};" + ) + .as_str() + ) + ); + } else { + assert!( + batches.bbox_role.is_none() && batches.postgis.is_none(), + "{label}" + ); + } + } + } + #[test] - fn casework_setup_gives_only_migration_role_public_schema_creation() { + fn casework_setup_gives_the_runtime_role_usage_on_public_and_only_the_migration_role_creation() + { let names = Names::new(RUN_ID, "casework"); - let sql = database_setup_sql(&names, false); + let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") + .unwrap() + .setup; assert!( sql.starts_with("REVOKE CREATE ON SCHEMA public FROM PUBLIC;"), "{sql}" @@ -1672,18 +1746,27 @@ mod tests { "GRANT USAGE, CREATE ON SCHEMA public TO {}", quote_identifier(&names.migration_role) ))); - assert!(!sql.contains(&names.runtime_role)); + assert!(sql.ends_with(&format!( + "GRANT USAGE ON SCHEMA public TO {}", + quote_identifier(&names.runtime_role) + ))); + assert_eq!(sql.matches(&names.runtime_role).count(), 1, "{sql}"); } #[test] - fn messaging_setup_gives_only_migration_role_public_schema_creation() { + fn messaging_setup_gives_the_runtime_role_no_public_schema_creation() { let names = Names::new(RUN_ID, "messaging"); - let sql = database_setup_sql(&names, false); + let sql = Batches::new(&names, false, false, "migration-secret", "runtime-secret") + .unwrap() + .setup; assert!( sql.starts_with("REVOKE CREATE ON SCHEMA public FROM PUBLIC;"), "{sql}" ); - assert!(!sql.contains(&names.runtime_role)); + assert!(!sql.contains(&format!( + "CREATE ON SCHEMA public TO {}", + quote_identifier(&names.runtime_role) + ))); assert_eq!( names.database, format!("rstack_{RUN_ID}_messaging"), @@ -1701,7 +1784,7 @@ mod tests { fn role_statement_carries_a_postgresql_scram_verifier_not_cleartext() { let password = random_password().unwrap(); let verifier = postgres_protocol::password::scram_sha_256(password.as_bytes()); - let sql = create_role_sql("rstack_role", &verifier); + let sql = registry_platform_provision::sql::create_role_sql("rstack_role", &verifier); let expected = format!( "CREATE ROLE \"rstack_role\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '{verifier}'" ); @@ -1724,6 +1807,7 @@ mod tests { #[cfg(all(test, feature = "postgres-test"))] mod postgres_tests { use super::*; + use registry_platform_provision::sql::quote_literal; use std::{sync::mpsc, thread}; struct Server { diff --git a/crates/registry-scheduling-client-node/client.d.ts b/crates/registry-scheduling-client-node/client.d.ts index 85c57ef2f3..4978b07c7a 100644 --- a/crates/registry-scheduling-client-node/client.d.ts +++ b/crates/registry-scheduling-client-node/client.d.ts @@ -316,6 +316,7 @@ export type SchedulingProblemCode = | 'cursor.expired' | 'cursor.invalid' | 'eligibility.unavailable' + | 'grant.lifetime-too-long' | 'hold.expired' | 'hold.released' | 'hook.unavailable' diff --git a/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi b/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi index 258ca4cfef..d8aafe3d40 100644 --- a/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi +++ b/crates/registry-scheduling-client-py/python/registry_scheduling_client/__init__.pyi @@ -400,6 +400,7 @@ SchedulingProblemCode: TypeAlias = Literal[ "cursor.expired", "cursor.invalid", "eligibility.unavailable", + "grant.lifetime-too-long", "hold.expired", "hold.released", "hook.unavailable", diff --git a/crates/registry-scheduling-client/src/client.rs b/crates/registry-scheduling-client/src/client.rs index 241f0346bd..1d7a54c3b7 100644 --- a/crates/registry-scheduling-client/src/client.rs +++ b/crates/registry-scheduling-client/src/client.rs @@ -9,7 +9,7 @@ use registry_platform_httputil::client::{ send_failure_kind, KeyedMutationAttempt, OutboundOptions, RetryAfter, ServiceBaseUrl, }; use registry_platform_httputil::{ - read_bounded, url::append_path_segments, validate_response_headers, + read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_scheduling_core::{ type_uri, valid_identifier, valid_reference, AdmissionRequest, AppointmentDocument, @@ -775,7 +775,7 @@ impl SchedulingClient { .map_err(|error| SchedulingClientError::Transport { kind: send_failure_kind(&error), })?; - validate_response_headers(response.headers()).map_err(|_| { + validate_response_headers_without_peer_policy(response.headers()).map_err(|_| { protocol( response.status(), SchedulingProtocolFailure::HeaderBounds, diff --git a/crates/registry-scheduling-core/src/problem.rs b/crates/registry-scheduling-core/src/problem.rs index f321411773..3f8466ff99 100644 --- a/crates/registry-scheduling-core/src/problem.rs +++ b/crates/registry-scheduling-core/src/problem.rs @@ -26,6 +26,7 @@ pub const CAPACITY_EXHAUSTED_PROBLEM: &str = "capacity.exhausted"; pub const CURSOR_EXPIRED_PROBLEM: &str = "cursor.expired"; pub const CURSOR_INVALID_PROBLEM: &str = "cursor.invalid"; pub const ELIGIBILITY_UNAVAILABLE_PROBLEM: &str = "eligibility.unavailable"; +pub const GRANT_LIFETIME_TOO_LONG_PROBLEM: &str = "grant.lifetime-too-long"; pub const HOLD_EXPIRED_PROBLEM: &str = "hold.expired"; pub const HOLD_RELEASED_PROBLEM: &str = "hold.released"; pub const HORIZON_OUTSIDE_PROBLEM: &str = "horizon.outside"; @@ -63,6 +64,7 @@ pub enum ProblemCode { CursorExpired, CursorInvalid, EligibilityUnavailable, + GrantLifetimeTooLong, HoldExpired, HoldReleased, HookUnavailable, @@ -101,6 +103,7 @@ impl ProblemCode { Self::CursorExpired, Self::CursorInvalid, Self::EligibilityUnavailable, + Self::GrantLifetimeTooLong, Self::HoldExpired, Self::HoldReleased, Self::HookUnavailable, @@ -139,6 +142,7 @@ impl ProblemCode { Self::CursorExpired => CURSOR_EXPIRED_PROBLEM, Self::CursorInvalid => CURSOR_INVALID_PROBLEM, Self::EligibilityUnavailable => ELIGIBILITY_UNAVAILABLE_PROBLEM, + Self::GrantLifetimeTooLong => GRANT_LIFETIME_TOO_LONG_PROBLEM, Self::HoldExpired => HOLD_EXPIRED_PROBLEM, Self::HoldReleased => HOLD_RELEASED_PROBLEM, Self::HorizonOutside => HORIZON_OUTSIDE_PROBLEM, @@ -195,7 +199,9 @@ impl ProblemCode { match self { Self::CursorInvalid | Self::RequestInvalid => 400, Self::AuthenticationRefused => 401, - Self::OperationNotAuthorized | Self::ProfileNotAuthorized => 403, + Self::GrantLifetimeTooLong + | Self::OperationNotAuthorized + | Self::ProfileNotAuthorized => 403, Self::RequestNotFound => 404, Self::RequestMethodNotAllowed => 405, Self::ReceiptUnresolved => 409, @@ -236,6 +242,7 @@ impl ProblemCode { Self::CursorExpired => "Cursor expired", Self::CursorInvalid => "Cursor invalid", Self::EligibilityUnavailable => "Eligibility unavailable", + Self::GrantLifetimeTooLong => "Task grant lifetime too long", Self::HoldExpired => "Hold expired", Self::HoldReleased => "Hold released", Self::HookUnavailable => "Hook unavailable", @@ -290,6 +297,9 @@ impl ProblemCode { Self::EligibilityUnavailable => { "A required eligibility check could not run. Retry; do not treat this as permission." } + Self::GrantLifetimeTooLong => { + "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds." + } Self::HoldExpired => { "The hold expired before confirmation. Its capacity is bookable again; start a new request." } @@ -368,7 +378,7 @@ mod tests { #[test] fn the_vocabulary_is_complete_and_closed() { - assert_eq!(ProblemCode::ALL.len(), 33); + assert_eq!(ProblemCode::ALL.len(), 34); for code in ProblemCode::ALL { assert_eq!(ProblemCode::from_code(code.code()), Some(*code)); } @@ -431,6 +441,19 @@ mod tests { } } + #[test] + fn a_grant_with_too_much_lifetime_left_has_its_own_code_and_keeps_the_status() { + let code = ProblemCode::GrantLifetimeTooLong; + assert_eq!(code.code(), "grant.lifetime-too-long"); + assert_eq!(code.http_status(), 403); + assert_eq!( + type_uri(code.code()), + format!("{SCHEDULING_PROBLEM_TYPE_BASE}grant/lifetime-too-long") + ); + assert_eq!(code.title(), "Task grant lifetime too long"); + assert!(code.detail().contains("900 seconds")); + } + /// The request-edge family is Casework's, pinned one status per code, so /// the runtime's edge and every client agree on what a rejected request /// looks like. diff --git a/crates/registry-scheduling/Cargo.toml b/crates/registry-scheduling/Cargo.toml index 2fb8bbffad..04d9bba46a 100644 --- a/crates/registry-scheduling/Cargo.toml +++ b/crates/registry-scheduling/Cargo.toml @@ -38,16 +38,17 @@ jsonwebtoken.workspace = true registry-scheduling-core.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true -registry-platform-authcommon.workspace = true +registry-platform-authcommon = { workspace = true, features = ["refusal-recorder"] } registry-platform-buildinfo.workspace = true registry-platform-calendar.workspace = true registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-dispatch = { workspace = true, features = ["postgres"] } -registry-platform-httpsec = { workspace = true, features = ["server"] } +registry-platform-httpsec = { workspace = true, features = ["server", "refusal-trace-id"] } registry-platform-httputil.workspace = true registry-platform-hooks = { workspace = true, features = ["postgres"] } +registry-platform-loopback.workspace = true registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true registry-platform-yaml.workspace = true @@ -68,7 +69,7 @@ uuid = { workspace = true, features = ["serde"] } [dev-dependencies] jsonschema.workspace = true -registry-platform-testing = { workspace = true, features = ["migration-pins"] } +registry-platform-testing = { workspace = true, features = ["migration-pins", "token-fixtures"] } reqwest.workspace = true serde_norway.workspace = true tempfile.workspace = true diff --git a/crates/registry-scheduling/migrations/0201_activation_posture.sql b/crates/registry-scheduling/migrations/0201_activation_posture.sql new file mode 100644 index 0000000000..9081894fde --- /dev/null +++ b/crates/registry-scheduling/migrations/0201_activation_posture.sql @@ -0,0 +1,9 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- The activation ledger records the posture the activating process declared. +-- A row written before this column existed reads production: a database that +-- was never activated in development can never read as development. +ALTER TABLE scheduling_activations + ADD COLUMN posture text NOT NULL DEFAULT 'production' + CHECK (posture IN ('development', 'production')); +ALTER TABLE scheduling_activations ALTER COLUMN posture DROP DEFAULT; diff --git a/crates/registry-scheduling/src/audit.rs b/crates/registry-scheduling/src/audit.rs index 3553ebaf26..c0b64f8a4e 100644 --- a/crates/registry-scheduling/src/audit.rs +++ b/crates/registry-scheduling/src/audit.rs @@ -244,7 +244,7 @@ mod capture { #[must_use] pub fn capture() -> (Self, AuditCapture) { let capture = AuditCapture::default(); - let writer = AuditWriter::from_line_sink(Box::new(capture.clone())); + let writer = AuditWriter::from_line_sink_without_posture(Box::new(capture.clone())); capture.0.lock().expect("audit capture").writer = Some(writer.clone()); (Self::new(writer), capture) } @@ -369,7 +369,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_stalled_destination_is_not_ready_until_it_drains() { let sink = HeldSink::default(); - let audit = SchedulingAudit::new(AuditWriter::from_line_sink(Box::new(sink.clone()))); + let audit = SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + sink.clone(), + ))); assert!(audit.ready().await); // The destination stops taking lines. The request waiting on it is diff --git a/crates/registry-scheduling/src/auth.rs b/crates/registry-scheduling/src/auth.rs index 730a7ed76f..9e083b82e3 100644 --- a/crates/registry-scheduling/src/auth.rs +++ b/crates/registry-scheduling/src/auth.rs @@ -35,9 +35,11 @@ use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use chrono::{DateTime, Utc}; -use registry_platform_authcommon::validate_compact_access_token; +use registry_platform_authcommon::{ + validate_compact_access_token, DeclaredScope, FailedCheck, RefusalRecorder, +}; use registry_platform_oidc::{ - actor_kind, grant_claims, ClaimNames, JwksFetcher, OidcError, TokenVerifier, + actor_kind, grant_claims, ClaimError, ClaimNames, JwksFetcher, OidcError, TokenVerifier, TokenVerifierConfig, ASSERTION_ISSUER_CLAIM, }; use serde_json::Value; @@ -57,21 +59,23 @@ pub struct SchedulingAuthenticator { verifier: TokenVerifier, claim_names: ClaimNames, audience: String, + scope_claim: String, reads_scope: String, explain_scope: String, appointment_read_profiles: BTreeMap, busy_import_profiles: BTreeMap, /// Whether the deployment declared any assertion authority at all. binds_assertion_issuers: bool, + /// Counts and logs every refusal the HTTP edge answers, by failed check. + refusals: Arc, } impl SchedulingAuthenticator { - pub(crate) fn record_header_refusal(&self) { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Header, - "Scheduling authentication refused" - ); + /// The recorder the HTTP edge reports each refusal to, and whose counter + /// the metrics listener exposes. + #[must_use] + pub fn refusals(&self) -> &Arc { + &self.refusals } #[must_use] @@ -86,11 +90,41 @@ impl SchedulingAuthenticator { verifier: TokenVerifier::new(verifier, keys), claim_names, audience: oidc.provider.audience.clone(), + scope_claim: oidc.scope_claim.clone(), reads_scope: oidc.reads_scope.clone(), explain_scope: oidc.explain_scope.clone(), appointment_read_profiles: oidc.appointment_read_profiles.clone(), busy_import_profiles: oidc.busy_import_profiles.clone(), binds_assertion_issuers: !oidc.clients.assertion_issuers.is_empty(), + refusals: Arc::new( + RefusalRecorder::new("scheduling").expect("the refusal counter is declared once"), + ), + } + } + + /// The configured values a reads-scope refusal's log line names. + #[must_use] + pub fn declared_reads_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.reads_scope) + } + + /// The configured values an explain-scope refusal's log line names. + #[must_use] + pub fn declared_explain_scope(&self) -> DeclaredScope { + DeclaredScope::new(&self.scope_claim).with_required_scope(&self.explain_scope) + } + + /// The configured values a source-busy scope refusal's log line names: + /// the profile's scope, and the profile id when the deployment declares + /// that profile. + #[must_use] + pub fn declared_busy_scope(&self, profile_selector: &str) -> DeclaredScope { + let declared = DeclaredScope::new(&self.scope_claim); + match self.busy_import_profiles.get(profile_selector) { + Some(profile) => declared + .with_required_scope(&profile.scope) + .with_access_profile(profile_selector), + None => declared, } } @@ -135,7 +169,7 @@ impl SchedulingAuthenticator { }) { return Ok((caller, DetailAdmission::Grant)); } - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) } /// The profile the separately authorized explain path demands: the caller @@ -146,7 +180,7 @@ impl SchedulingAuthenticator { } /// Admit a verified caller holding `required`, or refuse it as a profile - /// miss. Diagnostics name only the fixed stage, never scope or claim values. + /// miss. Nothing about the refusal names a scope or claim value. fn require_scope( &self, caller: Caller, @@ -157,13 +191,7 @@ impl SchedulingAuthenticator { if scopes.iter().any(|scope| scope == required) { return Ok(caller); } - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - registry_platform_oidc::AuthenticationStage::Scope, - "Scheduling authentication profile refused", - remedy = "check authentication.oidc.scopeClaim and readsScope or explainScope" - ); - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) } /// The profile the commitments demand: no product scope, because the @@ -183,16 +211,16 @@ impl SchedulingAuthenticator { profile_selector: &str, ) -> Result { let (caller, scopes, client) = self.verified_caller(token).await?; - let client = client.ok_or(AuthenticationError::Claims)?; + let client = client.ok_or(AuthenticationError::Claims(FailedCheck::TokenClient))?; let identity = BusySourceIdentity::new(caller.issuer, caller.subject, client) - .map_err(|_| AuthenticationError::Profile)?; + .map_err(|_| AuthenticationError::Profile(FailedCheck::TokenClaims))?; authorize_busy_source( &self.busy_import_profiles, &scopes, Some(profile_selector), identity, ) - .map_err(|_| AuthenticationError::Profile) + .map_err(|error| AuthenticationError::Profile(error.failed_check())) } /// Verify one token and authorize exactly one opt-in operational profile @@ -206,9 +234,9 @@ impl SchedulingAuthenticator { now: DateTime, ) -> Result { let (caller, scopes, client) = self.verified_caller(token).await?; - let client = client.ok_or(AuthenticationError::Claims)?; + let client = client.ok_or(AuthenticationError::Claims(FailedCheck::TokenClient))?; let identity = OperationalIdentity::new(caller.issuer, caller.subject, client) - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClaims))?; authorize_operational_read( &self.appointment_read_profiles, &scopes, @@ -217,7 +245,7 @@ impl SchedulingAuthenticator { filter, now, ) - .map_err(|_| AuthenticationError::Profile) + .map_err(|_| AuthenticationError::Profile(FailedCheck::AccessProfile)) } /// Verify one credential and resolve its caller. A present grant is bound @@ -227,18 +255,13 @@ impl SchedulingAuthenticator { &self, token: &str, ) -> Result<(Caller, Vec, Option), AuthenticationError> { - validate_compact_access_token(token).map_err(|_| { - self.record_header_refusal(); - AuthenticationError::Refused - })?; - let verified = self.verifier.verify(token).await.map_err(|error| { - registry_platform_oidc::log_authentication_refusal!( - self.verifier, - error.authentication_stage(), - "Scheduling authentication refused" - ); - verifier_failure(&error) - })?; + validate_compact_access_token(token) + .map_err(|_| AuthenticationError::Refused(FailedCheck::CredentialMalformed))?; + let verified = self + .verifier + .verify(token) + .await + .map_err(|error| verifier_failure(&error))?; // An exchanged token names the authority whose assertion produced it. // The platform applies no rule while the deployment's map is empty, so // an empty map would trust every authority the issuer federates. @@ -247,23 +270,27 @@ impl SchedulingAuthenticator { if !self.binds_assertion_issuers && verified.claims.extra.contains_key(ASSERTION_ISSUER_CLAIM) { - tracing::debug!( - "an exchanged credential arrived at a deployment that declared no assertion authority" - ); - return Err(AuthenticationError::Profile); + return Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer, + )); } let kind = actor_kind(&verified.claims, &self.claim_names) - .map_err(|_| AuthenticationError::Claims)?; - let grant = grant_claims(&verified.claims, &self.claim_names, unix_now()?) - .map_err(|_| AuthenticationError::Claims)?; + .map_err(|_| AuthenticationError::Claims(FailedCheck::ActorKind))?; + let grant = + grant_claims(&verified.claims, &self.claim_names, unix_now()?).map_err(|error| { + AuthenticationError::Claims(match error { + ClaimError::Expired => FailedCheck::TaskGrantExpired, + _ => FailedCheck::TaskGrantClaims, + }) + })?; if let Some(grant) = &grant { grant - .verify_context(&verified, &self.audience) - .map_err(|_| AuthenticationError::Profile)?; + .verify_context_without_peer_policy(&verified, &self.audience) + .map_err(|_| AuthenticationError::Profile(FailedCheck::TaskGrantBinding))?; } let client = verified .matched_client_id() - .map_err(|_| AuthenticationError::Claims)? + .map_err(|_| AuthenticationError::Claims(FailedCheck::TokenClient))? .filter(|client| !client.is_empty()) .map(str::to_owned); // A task-grant exchange preserves the subjects its source authority @@ -287,18 +314,18 @@ impl SchedulingAuthenticator { .iss .clone() .filter(|issuer| !issuer.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let subject = verified .claims .sub .clone() .filter(|subject| !subject.is_empty()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; let credential_exp_unix = verified .claims .exp .and_then(|value| u64::try_from(value).ok()) - .ok_or(AuthenticationError::Claims)?; + .ok_or(AuthenticationError::Claims(FailedCheck::TokenClaims))?; Ok(( Caller { actor_kind: kind.as_str().to_owned(), @@ -330,14 +357,17 @@ impl std::fmt::Debug for SchedulingAuthenticator { } } +/// Why authentication refused a request. Each refusal carries the check it +/// failed, which only the operator sees: the answer to the caller is the same +/// for every check of one kind. #[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] pub enum AuthenticationError { #[error("the bearer credential was refused")] - Refused, + Refused(FailedCheck), #[error("the verified identity claims are invalid")] - Claims, + Claims(FailedCheck), #[error("the caller's authentication profile is not authorized for this request")] - Profile, + Profile(FailedCheck), /// The verifier could not reach a verdict at all. #[error("the credential could not be verified because this verifier cannot answer")] Unavailable, @@ -368,8 +398,9 @@ fn verifier_failure(error: &OidcError) -> AuthenticationError { // signal, not an outage, and answering 503 there would let a caller // probe the key set. A variant added to the platform later is read as // a credential refusal until it is classified here, so a new outcome - // can never widen the door. - _ => AuthenticationError::Refused, + // can never widen the door. The check the refusal records is the + // shared verifier's own map. + _ => AuthenticationError::Refused(error.failed_check()), } } @@ -387,6 +418,8 @@ fn unix_now() -> Result { /// committing capacity for as long as the clock stayed unreadable, and the /// deployment would be told nothing. Nothing has been learned about the /// credential either, so the answer is the outage answer, not a challenge. +/// The edge counts that answer as `key-source-unavailable` because no member +/// names a clock failure. The error line above names the clock. fn unix_seconds(observed: SystemTime) -> Result { observed .duration_since(UNIX_EPOCH) @@ -641,7 +674,7 @@ mod tests { assert_eq!(admission, DetailAdmission::Grant); assert!(matches!( authenticator.authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); let without_action = token(merged("scheduling-explain", grant_claims_value(AUDIENCE))); @@ -649,7 +682,7 @@ mod tests { authenticator .authenticate_appointment_detail(&without_action) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); } @@ -664,7 +697,7 @@ mod tests { let authenticator = authenticator(); assert!(matches!( authenticator.authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); // Mutating routes demand no product scope: their authority is the // task grant, checked per offering in the service. @@ -692,7 +725,7 @@ mod tests { Utc::now(), ) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let grant_only = token(merged("", grant_claims_value(AUDIENCE))); @@ -700,7 +733,7 @@ mod tests { authenticator .authenticate_operational_read(&grant_only, None, operational_filter(), Utc::now(),) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let two_roles = token(json!({ @@ -713,7 +746,7 @@ mod tests { authenticator .authenticate_operational_read(&two_roles, None, operational_filter(), Utc::now(),) .await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::AccessProfile)) ); let authorized = authenticator .authenticate_operational_read( @@ -738,7 +771,7 @@ mod tests { })); assert!(matches!( authenticator.authenticate_explain(&reader).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); let explainer = token(json!({ "sub": "principal-2", @@ -799,7 +832,7 @@ mod tests { )); assert!(matches!( authenticator().authenticate_mutate(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::TaskGrantBinding)) )); } @@ -812,7 +845,7 @@ mod tests { let credential = token(merged("scheduling-read", grant)); assert!(matches!( authenticator().authenticate_mutate(&credential).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::TaskGrantClaims)) )); } @@ -826,7 +859,7 @@ mod tests { })); assert!(matches!( authenticator().authenticate_read(&credential).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) )); } @@ -843,7 +876,9 @@ mod tests { assert!( matches!( authenticator().authenticate_read(&credential).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile( + FailedCheck::TokenAssertionIssuer + )) ), "an exchanged token was accepted by a deployment that declared no assertion authority" ); @@ -867,7 +902,9 @@ mod tests { })); assert!(matches!( authenticator_with(declared).authenticate_read(&other).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused( + FailedCheck::TokenAssertionIssuer + )) )); } @@ -931,7 +968,7 @@ mod tests { Arc::new(JwksFetcher::new_with_fetch_url_policy( format!("{}/jwks.json", issuer_keys.uri()), JwksFetcherConfig::defaults(), - FetchUrlPolicy::dev(), + FetchUrlPolicy::https_or_loopback(), )), ); assert!( @@ -985,7 +1022,7 @@ mod tests { ] { assert_eq!( verifier_failure(&refusal), - AuthenticationError::Refused, + AuthenticationError::Refused(refusal.failed_check()), "{refusal} was excused as an outage" ); } @@ -1016,40 +1053,53 @@ mod tests { .unwrap(); assert!(matches!( authenticator().authenticate_read(&forged).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(FailedCheck::TokenSignature)) )); } #[tokio::test] - async fn compact_token_admission_logs_one_value_free_header_diagnostic() { - use registry_platform_testing::{malformed_access_token_fixtures, CapturedDiagnosticLogs}; + async fn malformed_compact_tokens_are_refused_as_malformed_credentials_and_logged_value_free() { + use registry_platform_testing::CapturedDiagnosticLogs; use tracing::instrument::WithSubscriber; let captured = CapturedDiagnosticLogs::default(); let subscriber = captured.subscriber(); - let tokens = malformed_access_token_fixtures(); + let tokens = registry_platform_testing::malformed_access_token_fixtures(); let auth = authenticator(); - for _ in 0..3 { - for token in &tokens { - assert!(matches!( - auth.authenticate_read(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate_explain(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - assert!(matches!( - auth.authenticate_mutate(token) - .with_subscriber(subscriber.clone()) - .await, - Err(AuthenticationError::Refused) - )); - } + let malformed = Some(AuthenticationError::Refused( + FailedCheck::CredentialMalformed, + )); + for token in &tokens { + assert_eq!( + auth.authenticate_read(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + assert_eq!( + auth.authenticate_explain(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + assert_eq!( + auth.authenticate_mutate(token) + .with_subscriber(subscriber.clone()) + .await + .err(), + malformed + ); + } + // The refusal line is written at the HTTP edge. Whatever the + // authenticator itself logs carries no part of a credential. + let rendered = captured.text(); + assert!(!rendered.contains("canary")); + for token in tokens.iter().filter(|token| !token.is_empty()) { + assert!( + !rendered.contains(token), + "diagnostics must not contain credentials" + ); } - captured.assert_one_value_free_header_diagnostic(&tokens); } #[tokio::test] @@ -1084,7 +1134,7 @@ mod tests { let auth = &auth; async move { auth.authenticate_read(&token).await } }, - |error| matches!(error, AuthenticationError::Refused), + |error| matches!(error, AuthenticationError::Refused(_)), ) .await; // A valid symmetric JWT is outside the asymmetric production baseline. @@ -1093,21 +1143,21 @@ mod tests { ); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Refused) + Err(AuthenticationError::Refused(_)) )); let mut wrong_actor = claims.clone(); wrong_actor["registry_actor_kind"] = json!("canary-invalid-actor"); let token = sign(wrong_actor, "at+jwt"); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Claims) + Err(AuthenticationError::Claims(FailedCheck::ActorKind)) )); let mut missing = claims.clone(); missing["registry_scopes"] = json!(""); let token = sign(missing, "at+jwt"); assert!(matches!( auth.authenticate_read(&token).await, - Err(AuthenticationError::Profile) + Err(AuthenticationError::Profile(FailedCheck::Scope)) )); } } diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index dab6998f8d..7b9b4a4795 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -28,10 +28,12 @@ pub use registry_platform_config::{ SecretProvidersConfig, TaskGrantStatusConfig, TlsTermination, UrlHookDestinationConfig, }; use registry_platform_httputil::destination::validate_fixed_destination_path; +use registry_platform_loopback::loopback_host; use registry_platform_oidc::task_grant::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}; use registry_platform_oidc::{ access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, - IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifierConfig, + IssuerNetworkPolicy, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, OidcError, + TokenVerifierConfig, }; use registry_platform_yaml::{ escape_pointer_segment, Diagnostic, Invalid, LocalId, Report, RetiredApiVersion, @@ -87,6 +89,14 @@ pub const SCHEDULING_RUNTIME_ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { /// Keys an earlier Scheduling runtime configuration accepted, each refused /// with the key that replaced it. pub const SCHEDULING_REMOVED_KEYS: &[RemovedKey] = &[ + RemovedKey { + path: "destinations.reminders.bearerTokenRef", + replacement: "Remove bearerTokenRef. Reminders are signed with destinations.reminders.hmacSha256KeyRef (Standard Webhooks).", + }, + RemovedKey { + path: "destinations.reminders.purposeUrls", + replacement: "Move each purpose URL to destinations.reminders.purposes..url with its own hmacSha256KeyRef.", + }, REMOVED_OIDC_JWKS_URI, REMOVED_OIDC_JWKS_SOURCE_KIND, RemovedKey { @@ -316,25 +326,6 @@ fn valid_database_id(value: &str) -> bool { && !value.chars().any(char::is_control) } -/// A secret reference, `secret:env/NAME` or `secret:file/name` (CFG-SEC-1), -/// kept as written. The reader refuses any other spelling at its position -/// without repeating it. -fn secret_reference<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - SecretReference::deserialize(deserializer).map(|reference| reference.as_str().to_owned()) -} - -/// An optional member holding a secret reference; absent reads as `None` -/// through `serde(default)`. -fn optional_secret_reference<'de, D>(deserializer: D) -> Result, D::Error> -where - D: Deserializer<'de>, -{ - secret_reference(deserializer).map(Some) -} - /// The policy and package identity produced by one verified package load. #[derive(Clone, Debug)] pub struct LoadedSchedulingPolicy { @@ -530,6 +521,7 @@ pub struct DestinationsConfig { pub hooks: BTreeMap, } +/// Fallback destination for reminder delivery. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -539,68 +531,95 @@ pub struct ReminderDestinationConfig { #[serde(deserialize_with = "registry_scheduling_core::url")] #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] pub url: String, - /// Optional endpoints for individual reminder purposes. Any omitted - /// purpose uses `url`; every override must share that URL's origin. + /// Reference to 32 to 64 exact key bytes used only for this destination. + pub hmac_sha256_key_ref: SecretReference, + /// Previous signing key during rotation. + #[serde(default, deserialize_with = "present_reminder_key_reference")] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, + /// Purpose-specific destinations on the fallback URL's origin. #[serde(default)] - pub purpose_urls: ReminderPurposeUrls, - #[serde(default, deserialize_with = "optional_secret_reference")] - #[cfg_attr(feature = "schema", schemars(with = "Option"))] - pub bearer_token_ref: Option, - /// Optional HMAC-SHA-256 key for the shared signed event-delivery - /// contract. Bearer authentication, when configured, remains independent. - #[serde(default, deserialize_with = "optional_secret_reference")] - #[cfg_attr(feature = "schema", schemars(with = "Option"))] - pub hmac_sha256_key_ref: Option, + pub purposes: ReminderPurposes, +} + +/// Destination for reminder delivery of one configured purpose. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReminderPurposeDestinationConfig { + #[serde(deserialize_with = "registry_scheduling_core::url")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub url: String, + /// Reference to 32 to 64 exact key bytes used only for this destination. + pub hmac_sha256_key_ref: SecretReference, + /// Previous signing key during rotation. + #[serde(default, deserialize_with = "present_reminder_key_reference")] + #[cfg_attr(feature = "schema", schemars(with = "SecretReference"))] + pub previous_hmac_sha256_key_ref: Option, } -/// Optional endpoint overrides named for the four reminder intent purposes -/// Scheduling emits. +/// Optional reminder destinations that override the fallback by purpose. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct ReminderPurposeUrls { - #[serde(default, deserialize_with = "optional_url")] +pub struct ReminderPurposes { + #[serde(default, deserialize_with = "present_reminder_purpose")] #[cfg_attr( feature = "schema", - schemars(with = "Option") + schemars(with = "ReminderPurposeDestinationConfig") )] - pub confirmation: Option, - #[serde(default, deserialize_with = "optional_url")] + pub confirmation: Option, + #[serde(default, deserialize_with = "present_reminder_purpose")] #[cfg_attr( feature = "schema", - schemars(with = "Option") + schemars(with = "ReminderPurposeDestinationConfig") )] - pub change: Option, - #[serde(default, deserialize_with = "optional_url")] + pub change: Option, + #[serde(default, deserialize_with = "present_reminder_purpose")] #[cfg_attr( feature = "schema", - schemars(with = "Option") + schemars(with = "ReminderPurposeDestinationConfig") )] - pub cancellation: Option, - #[serde(default, deserialize_with = "optional_url")] + pub cancellation: Option, + #[serde(default, deserialize_with = "present_reminder_purpose")] #[cfg_attr( feature = "schema", - schemars(with = "Option") + schemars(with = "ReminderPurposeDestinationConfig") )] - pub reminder: Option, + pub reminder: Option, } -impl ReminderPurposeUrls { - fn iter(&self) -> [(&'static str, Option<&str>); 4] { +impl ReminderPurposes { + pub(crate) fn iter( + &self, + ) -> impl Iterator { [ - ("confirmation", self.confirmation.as_deref()), - ("change", self.change.as_deref()), - ("cancellation", self.cancellation.as_deref()), - ("reminder", self.reminder.as_deref()), + ("confirmation", self.confirmation.as_ref()), + ("change", self.change.as_ref()), + ("cancellation", self.cancellation.as_ref()), + ("reminder", self.reminder.as_ref()), ] + .into_iter() + .filter_map(|(purpose, destination)| Some((purpose, destination?))) } } -fn optional_url<'de, D>(deserializer: D) -> Result, D::Error> +fn present_reminder_key_reference<'de, D>( + deserializer: D, +) -> Result, D::Error> where D: Deserializer<'de>, { - registry_scheduling_core::url(deserializer).map(Some) + SecretReference::deserialize(deserializer).map(Some) +} + +fn present_reminder_purpose<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + ReminderPurposeDestinationConfig::deserialize(deserializer).map(Some) } /// Retention periods the retention sweep enforces. Every value is deployment @@ -715,7 +734,7 @@ impl RuntimeConfig { /// removed keys, and retired apiVersions. #[must_use] pub const fn loader() -> RuntimeConfigLoader { - RuntimeConfigLoader::new(SCHEDULING_RUNTIME_ENVELOPE) + RuntimeConfigLoader::new_without_posture(SCHEDULING_RUNTIME_ENVELOPE) .removed_keys(SCHEDULING_REMOVED_KEYS) .retired_api_versions(SCHEDULING_RETIRED_RUNTIME_API_VERSIONS) .require_trusted_ownership() @@ -892,27 +911,34 @@ impl RuntimeConfig { )); } } - if let Some(reference) = self - .destinations - .reminders - .as_ref() - .and_then(|reminders| reminders.bearer_token_ref.as_deref()) - { - references.push(( - "destinations.reminders.bearerTokenRef".to_owned(), - reference, - )); - } - if let Some(reference) = self - .destinations - .reminders - .as_ref() - .and_then(|reminders| reminders.hmac_sha256_key_ref.as_deref()) - { - references.push(( - "destinations.reminders.hmacSha256KeyRef".to_owned(), - reference, - )); + if let Some(reminders) = &self.destinations.reminders { + let mut check = + |prefix: &[&str], current: &SecretReference, previous: Option<&SecretReference>| { + self.check_binding_reference( + findings, + &[prefix, &["hmacSha256KeyRef"]].concat(), + current.as_str(), + ); + if let Some(previous) = previous { + self.check_binding_reference( + findings, + &[prefix, &["previousHmacSha256KeyRef"]].concat(), + previous.as_str(), + ); + } + }; + check( + &["destinations", "reminders"], + &reminders.hmac_sha256_key_ref, + reminders.previous_hmac_sha256_key_ref.as_ref(), + ); + for (purpose, destination) in reminders.purposes.iter() { + check( + &["destinations", "reminders", "purposes", purpose], + &destination.hmac_sha256_key_ref, + destination.previous_hmac_sha256_key_ref.as_ref(), + ); + } } for (field, raw) in references { if let Err(error) = self.secret_providers.check_reference(&field, raw) { @@ -925,6 +951,13 @@ impl RuntimeConfig { &["destinations", "hooks", id, "hmacSha256KeyRef"], destination.hmac_sha256_key_ref.as_str(), ); + if let Some(reference) = &destination.previous_hmac_sha256_key_ref { + self.check_binding_reference( + findings, + &["destinations", "hooks", id, "previousHmacSha256KeyRef"], + reference.as_str(), + ); + } } } @@ -966,7 +999,7 @@ impl RuntimeConfig { fn check_oidc(&self, findings: &mut Vec) { let oidc = &self.authentication.oidc; - if let Err(error) = oidc.provider.check( + if let Err(error) = oidc.provider.check_without_posture( "authentication.oidc", self.listener.tls_termination == TlsTermination::DevelopmentLoopback, ) { @@ -1067,11 +1100,9 @@ impl RuntimeConfig { "url", ])); } - for (purpose, configured) in reminders.purpose_urls.iter() { - let Some(configured) = configured else { - continue; - }; - let segments = ["destinations", "reminders", "purposeUrls", purpose]; + for (purpose, destination) in reminders.purposes.iter() { + let configured = &destination.url; + let segments = ["destinations", "reminders", "purposes", purpose, "url"]; match reminder_destination_origin_and_path(configured) { None => findings.push(RuntimeConfigError::invalid_destination_url(&segments)), Some(_) @@ -1158,7 +1189,7 @@ impl RuntimeConfig { policy, ) } - JwksSource::Static { document_ref } => { + JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets.resolve(document_ref).map_err(|error| { RuntimeConfigError::OidcJwksSecret(describe_secret_failure( "authentication.oidc.jwksSource.documentRef", @@ -1166,8 +1197,18 @@ impl RuntimeConfig { &error, )) })?; - let jwks = parse_static_jwks(document.expose_secret()) - .map_err(|_| RuntimeConfigError::Oidc)?; + let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { + match error { + // The operator's document broke a key set rule: say + // which, so the fix does not start at the issuer. + OidcError::StaticKeySet(refusal) => { + RuntimeConfigError::OidcJwksSecret(format!( + "the document at authentication.oidc.jwksSource.documentRef was refused: {refusal}" + )) + } + _ => RuntimeConfigError::Oidc, + } + })?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } }; @@ -1280,10 +1321,9 @@ fn valid_destination_url(value: &str) -> bool { { match parsed.scheme() { "https" => true, - "http" => matches!( - parsed.host_str(), - Some("127.0.0.1") | Some("localhost") | Some("[::1]") - ), + "http" => parsed + .host_str() + .is_some_and(|host| loopback_host(host).is_some()), _ => false, } } else { @@ -1561,7 +1601,7 @@ fn stand_in_for(pointer: &str) -> &'static str { | ["authentication", "oidc", "issuer"] | ["authentication", "oidc", "jwksSource", "uri"] | ["destinations", "reminders", "url"] - | ["destinations", "reminders", "purposeUrls", _] + | ["destinations", "reminders", "purposes", _, "url"] | ["destinations", "hooks", _, "url"] => "https://deferred.invalid", ["taskGrantStatus", _, "sourceIssuer"] | ["taskGrantStatus", _, "statusResource"] @@ -3313,31 +3353,22 @@ holdPolicy: ), ( "destinations", - serde_json::json!({"reminders": {"url": "not-a-url"}}), + serde_json::json!({"reminders": {"url": "not-a-url", "hmacSha256KeyRef": "secret:file/reminder"}}), "config.invalid-value", "/destinations/reminders/url", ), ( "destinations", - serde_json::json!({"reminders": {"url": "https://reminders.example.test/due?all=1"}}), + serde_json::json!({"reminders": {"url": "https://reminders.example.test/due?all=1", "hmacSha256KeyRef": "secret:file/reminder"}}), "scheduling.runtime.invalid-destination-url", "/destinations/reminders/url", ), ( "destinations", - serde_json::json!({"reminders": {"url": "http://reminders.example.test/due"}}), + serde_json::json!({"reminders": {"url": "http://reminders.example.test/due", "hmacSha256KeyRef": "secret:file/reminder"}}), "scheduling.runtime.invalid-destination-url", "/destinations/reminders/url", ), - ( - "destinations", - serde_json::json!({"reminders": { - "url": "https://reminders.example.test/due", - "bearerTokenRef": "vault:reminders" - }}), - "config.invalid-value", - "/destinations/reminders/bearerTokenRef", - ), ( "destinations", serde_json::json!({"hooks": {"Appointment-Events": { @@ -3394,34 +3425,165 @@ holdPolicy: } #[test] - fn reminder_purpose_urls_are_typed_and_optional() { + fn a_reminder_destination_without_a_key_is_refused_with_its_fix() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["destinations"]["reminders"] = serde_json::json!({ + "url": "https://events.example.test/due" + }); + let error = parse_runtime(&document).expect_err("a signing key is required"); + assert_eq!(error.code(), "config.missing-key"); + assert!( + error.suggested_action().contains("hmacSha256KeyRef"), + "{error}" + ); + } + + #[test] + fn a_reminder_bearer_token_names_its_replacement() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["destinations"]["reminders"] = serde_json::json!({ + "url": "https://events.example.test/due", + "bearerTokenRef": "secret:file/bearer" + }); + let error = parse_runtime(&document).expect_err("bearer authentication was removed"); + assert!( + error.suggested_action().contains("Standard Webhooks"), + "{error}" + ); + } + + #[test] + fn reminder_purpose_urls_name_their_replacement() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["destinations"]["reminders"] = serde_json::json!({ + "url": "https://events.example.test/due", + "purposeUrls": {"confirmation": "https://events.example.test/confirmed"} + }); + let error = parse_runtime(&document).expect_err("purposeUrls was removed"); + assert!( + error.suggested_action().contains("purposes..url"), + "{error}" + ); + } + + #[test] + fn a_reminder_purpose_without_its_own_key_is_refused() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["destinations"]["reminders"] = serde_json::json!({ + "url": "https://events.example.test/due", + "hmacSha256KeyRef": "secret:file/reminder", + "purposes": {"confirmation": {"url": "https://events.example.test/confirmed"}} + }); + let error = parse_runtime(&document).expect_err("the confirmation needs its own key"); + assert_eq!(error.code(), "config.missing-key"); + assert_eq!( + error.pointer(), + "/destinations/reminders/purposes/confirmation" + ); + assert!( + error.suggested_action().contains("hmacSha256KeyRef"), + "{error}" + ); + } + + #[test] + fn an_explicit_null_previous_reminder_key_is_refused() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["destinations"]["reminders"] = serde_json::json!({ + "url": "https://events.example.test/due", + "hmacSha256KeyRef": "secret:file/reminder", + "previousHmacSha256KeyRef": null + }); + let error = parse_runtime(&document).expect_err("omit the previous key when absent"); + assert_eq!(error.code(), "config.null-value"); + assert_eq!( + error.pointer(), + "/destinations/reminders/previousHmacSha256KeyRef" + ); + } + + #[test] + fn a_hook_previous_key_naming_a_disabled_provider_is_refused_by_check() { + let root = canonical_tempdir(); + let (_, mut document) = development(root.path()); + document["secretProviders"] + .as_object_mut() + .unwrap() + .remove("environment"); + document["database"] = serde_json::json!({ + "runtimeUrlRef": "secret:file/runtime", + "migrationUrlRef": "secret:file/migration" + }); + document["destinations"]["hooks"] = serde_json::json!({"appointment-events": { + "url": "https://events.example.test/hooks", + "hmacSha256KeyRef": "secret:file/hook", + "previousHmacSha256KeyRef": "secret:env/HOOK_PREVIOUS" + }}); + let config = parse_runtime(&document).expect("the document decodes"); + assert_eq!( + config + .findings(None) + .iter() + .map(refusal) + .collect::>(), + [( + "scheduling.runtime.secret-provider-disabled".to_owned(), + "/destinations/hooks/appointment-events/previousHmacSha256KeyRef".to_owned() + )] + ); + } + + #[test] + fn reminder_purposes_are_typed_and_optional() { let root = canonical_tempdir(); let (_, mut document) = development(root.path()); document["destinations"]["reminders"] = serde_json::json!({ "url": "https://events.example.test:443/fallback", - "purposeUrls": { - "confirmation": "https://events.example.test/confirmed", - "change": "https://events.example.test/rescheduled", - "cancellation": "https://events.example.test/cancelled", - "reminder": "https://events.example.test/reminder" + "hmacSha256KeyRef": "secret:file/reminder", + "purposes": { + "confirmation": {"url": "https://events.example.test/confirmed", "hmacSha256KeyRef": "secret:file/purpose"}, + "change": {"url": "https://events.example.test/rescheduled", "hmacSha256KeyRef": "secret:file/purpose"}, + "cancellation": {"url": "https://events.example.test/cancelled", "hmacSha256KeyRef": "secret:file/purpose"}, + "reminder": {"url": "https://events.example.test/reminder", "hmacSha256KeyRef": "secret:file/purpose"} } }); let config = parse_runtime(&document).expect("purpose-specific URLs are accepted"); let reminders = config.destinations.reminders.expect("reminder destination"); assert_eq!( - reminders.purpose_urls.confirmation.as_deref(), + reminders + .purposes + .confirmation + .as_ref() + .map(|destination| destination.url.as_str()), Some("https://events.example.test/confirmed") ); assert_eq!( - reminders.purpose_urls.change.as_deref(), + reminders + .purposes + .change + .as_ref() + .map(|destination| destination.url.as_str()), Some("https://events.example.test/rescheduled") ); assert_eq!( - reminders.purpose_urls.cancellation.as_deref(), + reminders + .purposes + .cancellation + .as_ref() + .map(|destination| destination.url.as_str()), Some("https://events.example.test/cancelled") ); assert_eq!( - reminders.purpose_urls.reminder.as_deref(), + reminders + .purposes + .reminder + .as_ref() + .map(|destination| destination.url.as_str()), Some("https://events.example.test/reminder") ); } @@ -3434,32 +3596,33 @@ holdPolicy: ( serde_json::json!({"unknown": "https://events.example.test/unknown-canary"}), "config.unknown-key", - "/destinations/reminders/purposeUrls/unknown", + "/destinations/reminders/purposes/unknown", "unknown-canary", ), ( - serde_json::json!({"confirmation": "https://other.example.test/origin-canary"}), + serde_json::json!({"confirmation": {"url": "https://other.example.test/origin-canary", "hmacSha256KeyRef": "secret:file/purpose"}}), "scheduling.runtime.reminder-destination-origin-mismatch", - "/destinations/reminders/purposeUrls/confirmation", + "/destinations/reminders/purposes/confirmation/url", "other.example.test", ), ( - serde_json::json!({"change": "https://events.example.test/path?query-canary=1"}), + serde_json::json!({"change": {"url": "https://events.example.test/path?query-canary=1", "hmacSha256KeyRef": "secret:file/purpose"}}), "scheduling.runtime.invalid-destination-url", - "/destinations/reminders/purposeUrls/change", + "/destinations/reminders/purposes/change/url", "query-canary", ), ( - serde_json::json!({"cancellation": "https://events.example.test/a/%2Funsafe-canary"}), + serde_json::json!({"cancellation": {"url": "https://events.example.test/a/%2Funsafe-canary", "hmacSha256KeyRef": "secret:file/purpose"}}), "scheduling.runtime.invalid-destination-url", - "/destinations/reminders/purposeUrls/cancellation", + "/destinations/reminders/purposes/cancellation/url", "unsafe-canary", ), ] { let mut document = base.clone(); document["destinations"]["reminders"] = serde_json::json!({ "url": "https://events.example.test/fallback", - "purposeUrls": purpose_urls + "hmacSha256KeyRef": "secret:file/reminder", + "purposes": purpose_urls }); let error = RuntimeConfig::load(write_operator(root.path(), document)) .expect_err("the purpose URL is refused"); @@ -4417,10 +4580,49 @@ holdPolicy: ); } + /// `loopback-plaintext` places the listener on loopback in every posture + /// and relaxes nothing: a plain http issuer on loopback is admitted under + /// `development-loopback` and refused under `loopback-plaintext`. + #[test] + fn loopback_plaintext_places_the_listener_and_relaxes_nothing() { + let root = canonical_tempdir(); + let (_, base) = development(root.path()); + let load = |tls: &str, bind: &str, issuer: Option<&str>| { + let mut document = base.clone(); + document["listener"]["tlsTermination"] = serde_json::json!(tls); + document["listener"]["bind"] = serde_json::json!(bind); + if let Some(issuer) = issuer { + document["authentication"]["oidc"]["issuer"] = serde_json::json!(issuer); + } + RuntimeConfig::load(write_operator(root.path(), document)) + }; + + load("loopback-plaintext", "127.0.0.1:8105", None).expect("a loopback bind is admitted"); + for tls in ["development-loopback", "loopback-plaintext"] { + let error = load(tls, "10.20.30.40:8105", None).unwrap_err(); + assert_eq!( + refusal(&error), + ( + "scheduling.runtime.invalid-listener".to_owned(), + "/listener/bind".to_owned() + ), + "{tls}" + ); + } + + let issuer = "http://127.0.0.1:8082"; + load("development-loopback", "127.0.0.1:8105", Some(issuer)) + .expect("development-loopback admits a loopback http issuer"); + let error = load("loopback-plaintext", "127.0.0.1:8105", Some(issuer)).unwrap_err(); + assert_eq!(error.pointer(), "/authentication/oidc/issuer"); + } + /// The runtime's static JWKS arm hands the resolved document to the /// shared parser and refuses a key set it cannot trust before any /// verifier exists: a symmetric key, an unnamed key, two keys sharing a - /// name, or no key at all. + /// name, a private key member, or no key at all. The operator is told + /// which rule the file broke, under the code for an unusable key file + /// and never the issuer-unreachable one. #[cfg(unix)] #[tokio::test] async fn static_jwks_requires_unique_named_asymmetric_keys() { @@ -4447,14 +4649,42 @@ holdPolicy: .await .expect("one named asymmetric key is accepted"); - for (case, invalid) in [ - ("symmetric", br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#.as_slice()), - ("unnamed", br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#), + // Members the key set rule does not name are not inspected. + write_jwks( + br#"{"issuer":"https://issuer.test","keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","ext":true,"x5c":["AA=="],"x5t":"AA","x5u":"https://issuer.test/chain"}]}"#, + ); + config + .oidc_verifier(&secrets) + .await + .expect("unknown public members are ignored"); + + for (case, invalid, text) in [ + ( + "symmetric", + br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#.as_slice(), + "symmetric key", + ), + ( + "unnamed", + br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#, + "has no \"kid\"", + ), ( "duplicate name", br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + "repeats the \"kid\"", + ), + ("empty", br#"{"keys":[]}"#, "holds no keys"), + ( + "private member", + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB","d":"AQAB"}]}"#, + "private-key member \"d\"", + ), + ( + "repeated member name", + br#"{"keys":[{"kty":"RSA","kid":"one","kid":"two","n":"AQAB","e":"AQAB"}]}"#, + "repeats a member name", ), - ("empty", br#"{"keys":[]}"#), ] { write_jwks(invalid); let error = config @@ -4465,22 +4695,54 @@ holdPolicy: assert_eq!( refusal(&error), ( - "scheduling.runtime-dependency.unavailable".to_owned(), - "/authentication/oidc".to_owned() + "scheduling.runtime.unreadable-jwks-secret".to_owned(), + "/authentication/oidc/jwksSource/documentRef".to_owned() ), "{case}" ); + assert!(error.to_string().contains(text), "{case}: {error}"); assert!(!error.in_file(), "{case}"); } } + /// A reminder or hook destination takes plain http only on a loopback + /// host: any address of 127.0.0.0/8, `::1`, a mapped loopback address, or + /// the exact name `localhost`. Another host, or another spelling of the + /// name, is refused. + #[test] + fn plain_http_destinations_take_only_loopback_hosts() { + for accepted in [ + "http://127.0.0.1:8080/hook", + "http://127.0.0.2:8080/hook", + "http://[::1]:8080/hook", + "http://[::ffff:127.0.0.1]:8080/hook", + "http://localhost:8080/hook", + "http://LOCALHOST:8080/hook", + "https://example.test/hook", + ] { + assert!(valid_destination_url(accepted), "{accepted}"); + } + for refused in [ + "http://10.0.0.1:8080/hook", + "http://[::ffff:10.0.0.1]:8080/hook", + "http://0.0.0.0:8080/hook", + "http://[::]:8080/hook", + "http://169.254.169.254/hook", + "http://a.localhost:8080/hook", + "http://localhost.:8080/hook", + "http://example.test/hook", + ] { + assert!(!valid_destination_url(refused), "{refused}"); + } + } + /// A runtime file that breaks three rules, each away from the others. fn file_breaking_three_rules(root: &Path) -> PathBuf { let mut document = operator_value(&root.join("package"), "development-loopback"); document["identity"]["databaseId"] = serde_json::json!(" padded "); document["listener"]["bind"] = serde_json::json!("10.0.0.5:8100"); document["destinations"] = serde_json::json!({ - "reminders": {"url": "http://reminders.example.test/due"} + "reminders": {"url": "http://reminders.example.test/due", "hmacSha256KeyRef": "secret:file/reminder"} }); write_operator(root, document) } diff --git a/crates/registry-scheduling/src/hooks.rs b/crates/registry-scheduling/src/hooks.rs index e100c31a1c..699343afd9 100644 --- a/crates/registry-scheduling/src/hooks.rs +++ b/crates/registry-scheduling/src/hooks.rs @@ -14,6 +14,7 @@ use std::time::{Duration, SystemTime}; use registry_platform_canonical_json::canonicalize_json; use registry_platform_config::SecretResolver; +use registry_platform_crypto::delivery_signature::DeliveryKeyError; use registry_platform_dispatch::postgres::PooledClient; use registry_platform_hooks::delivery::{ activate_url_hook_destinations, hook_audit_entry, insert_delivery, verify_active_package, @@ -48,10 +49,12 @@ use crate::config::{ }; use crate::store::{activation_layout, ClaimRow, PostgresStore}; +pub(crate) const CURRENT_KEY_MEMBER: &str = "hmacSha256KeyRef"; +pub(crate) const PREVIOUS_KEY_MEMBER: &str = "previousHmacSha256KeyRef"; + const DESTINATION_BINDING_SCHEMA: &str = "registry.scheduling-hook-destinations/v1"; const COMPILED_HOOK_SCHEMA: &str = "registry.scheduling-hooks/v1"; const DATA_SCHEMA_BINDING: &str = "registry.scheduling-hook-data/v1"; -const IDEMPOTENCY_DOMAIN: &[u8] = b"scheduling-hook-idempotency-v1"; const ENTITY_ID: &str = "appointment"; /// The refusal code retained with a delivery whose destination answered with /// a proposal. Each dotted segment is lowercase kebab-case. @@ -68,7 +71,7 @@ const IDENTITY_LOCK_TIMEOUT_MS: u32 = 5_000; const _: () = assert!(MAXIMUM_PAYLOAD_BYTES <= MAX_DESTINATION_REQUEST_BODY_BYTES); /// Value-free refusal from hook compilation or deployment activation. -#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum HookActivationError { #[error("the Scheduling hook declaration is invalid")] InvalidDeclaration, @@ -92,8 +95,8 @@ pub enum HookActivationError { InvalidDestination, #[error("a Scheduling hook destination widens the fixed delivery budget")] DeliveryBudgetWidening, - #[error("a Scheduling hook signing secret is unavailable or invalid")] - InvalidSigningMaterial, + #[error("{0}")] + SigningMaterial(String), #[error("the Scheduling hook runtime identity is invalid")] InvalidIdentity, } @@ -294,18 +297,20 @@ impl ActivatedHooks { self.compiled.schema_fingerprint() } - /// Compile `declarations` and resolve every destination they name with - /// its signing material, as [`Self::activate`] does, without a runtime - /// identity, and keep nothing. Operator tooling reports with it that a - /// candidate's hooks cannot run before anything is planned or applied. - pub fn check_destinations( + /// Compile the hook declarations and activate every configured binding + /// without a runtime identity. Plan uses these bindings to check the + /// same signing keys a runtime would hold. + pub fn activate_destination_bindings( declarations: &[HookDeclaration], configured: &BTreeMap, secrets: &SecretResolver, - ) -> Result<(), HookActivationError> { + ) -> Result { let compiled = CompiledHooks::compile(declarations)?; - activate_destinations(&compiled.destination_ids, configured, secrets)?; - Ok(()) + activate_destinations(&compiled.destination_ids, configured, secrets) + } + + pub(crate) fn destination_bindings(&self) -> &ActivatedUrlHookDestinations { + &self.destinations } #[must_use] @@ -533,7 +538,6 @@ impl ActivatedHooks { seams, DeliveryConfig { schema: self.schema.clone(), - idempotency_domain: IDEMPOTENCY_DOMAIN.to_vec(), delivery_source: self.delivery_source.clone(), }, ), @@ -571,12 +575,69 @@ fn activation_error(error: UrlHookActivationError) -> HookActivationError { HookActivationError::DeliveryBudgetWidening } UrlHookActivationError::InvalidDestination => HookActivationError::InvalidDestination, - UrlHookActivationError::InvalidSigningMaterial => { - HookActivationError::InvalidSigningMaterial + UrlHookActivationError::SigningKeyUnavailable { + destination, + member, + reason, + } => HookActivationError::SigningMaterial(format!( + "destinations.hooks.{destination}.{member} could not be resolved: {reason}. {}", + reason.suggested_action() + )), + UrlHookActivationError::InvalidSigningKey { + destination, + member, + length, + trailing_newline, + reason, + } => { + let path = format!("destinations.hooks.{destination}.{member}"); + let message = if reason == DeliveryKeyError::PreviousEqualsCurrent { + repeated_rotation_key( + &path, + &format!("destinations.hooks.{destination}.{CURRENT_KEY_MEMBER}"), + ) + } else { + invalid_delivery_key(&path, length, trailing_newline, reason) + }; + HookActivationError::SigningMaterial(message) + } + UrlHookActivationError::RepeatedSigningKey { first, second } => { + HookActivationError::SigningMaterial(repeated_delivery_key( + &format!("destinations.hooks.{first}"), + &format!("destinations.hooks.{second}"), + )) } } } +pub(crate) fn invalid_delivery_key( + path: &str, + length: usize, + trailing_newline: bool, + error: DeliveryKeyError, +) -> String { + let action = match error { + DeliveryKeyError::TooShort { .. } | DeliveryKeyError::TooLong { .. } => { + "Supply 32 to 64 exact key bytes." + } + DeliveryKeyError::SecretText => "Supply the exact key bytes without the whsec_ encoding.", + DeliveryKeyError::PreviousEqualsCurrent => unreachable!("rotation uses its own refusal"), + }; + format!("{path} has {length} bytes (trailing newline: {trailing_newline}). {action}") +} + +pub(crate) fn repeated_delivery_key(first: &str, second: &str) -> String { + format!( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there." + ) +} + +pub(crate) fn repeated_rotation_key(previous: &str, current: &str) -> String { + format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}." + ) +} + /// The delays between attempts: from 30 seconds, doubling, capped at one /// hour, one delay between each pair of the attempt ceiling's attempts. fn retry_delays_ms() -> Vec { @@ -1124,6 +1185,77 @@ mod tests { assert_eq!(retry_delays_ms(), expected); } + fn hook_key_refusal(second_key: &[u8], use_previous: bool) -> String { + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + for (name, key) in [ + ("event-key", [0x5a; 32].as_slice()), + ("mirror-key", second_key), + ] { + let path = directory.path().join(name); + std::fs::write(&path, key).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let secrets = SecretResolver::new([SecretProvider::File], directory.path()).unwrap(); + let mut configured: DestinationsConfig = serde_json::from_value(json!({"hooks": { + "appointment-events": { + "url": "https://events.example.test/scheduling", + "hmacSha256KeyRef": "secret:file/event-key" + }, + "audit-mirror": { + "url": "https://events.example.test/mirror", + "hmacSha256KeyRef": "secret:file/mirror-key" + } + }})) + .unwrap(); + if use_previous { + let mirror = configured.hooks.get_mut("audit-mirror").unwrap(); + mirror.previous_hmac_sha256_key_ref = Some(mirror.hmac_sha256_key_ref.clone()); + } + activate_destinations(&BTreeSet::new(), &configured.hooks, &secrets) + .expect_err("hook signing material is refused") + .to_string() + } + + #[test] + fn a_repeated_hook_key_names_both_destinations_and_the_key_recipe() { + let error = hook_key_refusal(&[0x5a; 32], false); + let first = "destinations.hooks.appointment-events.hmacSha256KeyRef"; + let second = "destinations.hooks.audit-mirror.hmacSha256KeyRef"; + assert_eq!(error, format!( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there." + )); + } + + #[test] + fn an_observer_previous_key_equal_to_its_current_key_names_both_paths_and_rotation() { + let error = hook_key_refusal(&[0x5b; 32], true); + let previous = "destinations.hooks.audit-mirror.previousHmacSha256KeyRef"; + let current = "destinations.hooks.audit-mirror.hmacSha256KeyRef"; + assert_eq!(error, format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}." + )); + } + + #[test] + fn invalid_hook_keys_name_the_path_size_newline_and_action_once() { + let mut key = [0x5b; 65]; + key[64] = b'\n'; + let mut encoded = [0x5b; 32]; + encoded[..6].copy_from_slice(b"whsec_"); + let path = "destinations.hooks.audit-mirror.hmacSha256KeyRef"; + assert_eq!( + hook_key_refusal(&key, false), + format!( + "{path} has 65 bytes (trailing newline: true). Supply 32 to 64 exact key bytes." + ) + ); + assert_eq!(hook_key_refusal(&encoded, false), format!( + "{path} has 32 bytes (trailing newline: false). Supply the exact key bytes without the whsec_ encoding." + )); + } + /// The binding digests a deployed Scheduling runtime records with every /// captured delivery. A retained delivery is refused once its recorded /// digest no longer matches the activated destination, so these values @@ -1137,6 +1269,10 @@ mod tests { std::fs::write(&key_path, [0x5a; 32]).expect("write the test hook key"); std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600)) .expect("restrict the test hook key"); + let mirror_path = directory.path().join("mirror-key"); + std::fs::write(&mirror_path, [0x5b; 32]).expect("write the test mirror key"); + std::fs::set_permissions(&mirror_path, std::fs::Permissions::from_mode(0o600)) + .expect("restrict the test mirror key"); let secrets = SecretResolver::new([SecretProvider::File], directory.path()) .expect("the test secret resolver"); let configured: DestinationsConfig = serde_json::from_value(json!({"hooks": { @@ -1146,7 +1282,7 @@ mod tests { }, "audit-mirror": { "url": "http://127.0.0.1:8080/hooks", - "hmacSha256KeyRef": "secret:file/hook-key", + "hmacSha256KeyRef": "secret:file/mirror-key", "attemptTimeoutMilliseconds": 250, "maximumAttempts": 3, }, @@ -1159,7 +1295,7 @@ mod tests { assert_eq!( activated.binding_digest, - "sha256:6021194b5df3b34eeb31b21c8b3ef448f2d639d3e8393d13b98a8276b5411df0" + "sha256:63f9ba0e4c8368aa0a5f82253a3523ed604c0553b8f39c7e349b5277fc962782" ); assert_eq!( activated.bindings["appointment-events"].binding_digest(), @@ -1167,7 +1303,7 @@ mod tests { ); assert_eq!( activated.bindings["audit-mirror"].binding_digest(), - "sha256:dd0b35e51274ab6a1d2456e9b0520acdf5b68e720a352d0d4819f41090ff7d97" + "sha256:2f321a61540105f154d771348140d9275e1a0e2eed721f6d593a0a59f5babc9e" ); } @@ -1195,6 +1331,7 @@ mod tests { url: Url::new("https://events.example.test/scheduling").expect("the test URL"), hmac_sha256_key_ref: SecretReference::parse("secret:file/hook-key") .expect("the test key reference"), + previous_hmac_sha256_key_ref: None, attempt_timeout_milliseconds: timeout, maximum_attempts: attempts, }; @@ -1242,7 +1379,7 @@ mod tests { if configured { accepted += 1; assert!( - matches!(activated, Err(HookActivationError::InvalidSigningMaterial)), + matches!(activated, Err(HookActivationError::SigningMaterial(_))), "activation refused {id:?} {config:?} for its budget, which the configuration accepts" ); } else { diff --git a/crates/registry-scheduling/src/http.rs b/crates/registry-scheduling/src/http.rs index 113bc853d6..8b24b4a14d 100644 --- a/crates/registry-scheduling/src/http.rs +++ b/crates/registry-scheduling/src/http.rs @@ -32,11 +32,15 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; use chrono::{DateTime, Utc}; -use registry_platform_authcommon::parse_bearer_token; +use registry_platform_authcommon::{ + parse_bearer_token, record_refusal, BearerParseError, DeclaredScope, FailedCheck, RefusalNote, + RefusalRecorder, +}; use registry_platform_httpsec::{ - normalize_framework_rejection, request_body_limit_default, security_headers, CspBuilder, - FrameworkRejection, ProblemBody, TraceContext, + normalize_framework_rejection, request_body_limit_default, security_headers_without_posture, + CspBuilder, FrameworkRejection, ProblemBody, TraceContext, }; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use registry_scheduling_core::{ type_uri, valid_identifier, valid_reference, AdmissionRequest, AvailabilityPreviewRequest, CancelAppointmentRequest, CreateAppointmentRequest, ExternalReference, ProblemCode, @@ -52,7 +56,9 @@ use uuid::Uuid; use crate::auth::{AuthenticationError, SchedulingAuthenticator}; use crate::metrics::{serve_metrics, Metrics, MetricsState, METRICS_PATH}; -use crate::service::{Caller, CommitmentAnswer, DetailAdmission, SchedulingService, ServiceError}; +use crate::service::{ + Caller, CommitmentAnswer, DetailAdmission, RefusalCode, SchedulingService, ServiceError, +}; use crate::source_busy::{ validate_busy_reconciliation_request, BusyReconciliationRequest, BusyRequestError, BUSY_SOURCE_APPLY_PATH, BUSY_SOURCE_PREVIEW_PATH, @@ -86,8 +92,11 @@ pub fn metrics_router(metrics: Arc, store: PostgresStore) -> Router { } pub fn router(state: HttpState) -> Router { - http_edge( + let refusals = Arc::clone(state.authenticator.refusals()); + http_edge(with_refusal_recording( Router::new() + .route(HEALTH_PATH, get(health)) + .route(READY_PATH, get(ready)) .route("/healthz", get(healthz)) .route("/readyz", get(readyz)) .route(SCHEDULING_PATH, get(scheduling)) @@ -114,7 +123,8 @@ pub fn router(state: HttpState) -> Router { .route(APPOINTMENT_CANCEL_ROUTE, post(cancel_appointment)) .route(APPOINTMENT_HISTORY_ROUTE, get(appointment_history)) .route(APPOINTMENT_ATTENDANCE_ROUTE, put(record_attendance)), - ) + refusals, + )) .with_state(state) } @@ -164,39 +174,43 @@ async fn authenticate_busy_source( profile: &str, ) -> Result { if !valid_identifier(profile) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_busy_source(token, profile) .await - .map_err(authentication_problem) + .map_err(|error| { + authentication_problem(error) + .with_declared_scope(state.authenticator.declared_busy_scope(profile)) + }) } fn busy_request_problem(error: BusyRequestError) -> HttpError { match error { - BusyRequestError::Authority => HttpError(ProblemCode::ProfileNotAuthorized), + BusyRequestError::Authority => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, FailedCheck::Operation) + } BusyRequestError::Invalid | BusyRequestError::Bound => { - HttpError(ProblemCode::RequestInvalid) + HttpError::plain(ProblemCode::RequestInvalid) } } } fn busy_store_problem(error: BusyStoreError) -> HttpError { match error { - BusyStoreError::RevisionMismatch { .. } => HttpError(ProblemCode::RevisionMismatch), + BusyStoreError::RevisionMismatch { .. } => HttpError::plain(ProblemCode::RevisionMismatch), BusyStoreError::CoverageBoundary | BusyStoreError::ObservationConflict => { - HttpError(ProblemCode::PreconditionFailed) + HttpError::plain(ProblemCode::PreconditionFailed) } - BusyStoreError::ResourceMissing => HttpError(ProblemCode::ResourceUnavailable), + BusyStoreError::ResourceMissing => HttpError::plain(ProblemCode::ResourceUnavailable), BusyStoreError::AuditUnavailable | BusyStoreError::RecoveryUnavailable | BusyStoreError::Query(_) | BusyStoreError::Store(_) => { tracing::error!(%error, "the source-busy operation failed"); - HttpError(ProblemCode::ServiceUnavailable) + HttpError::plain(ProblemCode::ServiceUnavailable) } } } @@ -210,7 +224,7 @@ where .method_not_allowed_fallback(method_not_allowed) .layer(request_body_limit_default()) .layer(middleware::from_fn(http_boundary)) - .layer(security_headers(CspBuilder::restrictive()).without_hsts()) + .layer(security_headers_without_posture(CspBuilder::restrictive()).without_hsts()) } async fn http_boundary(request: axum::http::Request, next: Next) -> Response { @@ -251,6 +265,23 @@ async fn method_not_allowed() -> Response { problem_response(ProblemCode::RequestMethodNotAllowed) } +fn probe_response(body: &'static str) -> Response { + ([(CONTENT_TYPE, "application/json")], body).into_response() +} + +async fn health() -> Response { + probe_response(HEALTH_BODY) +} + +/// Ready on the same terms as `readyz`. +async fn ready(State(state): State) -> Result { + if state.service.ready().await.is_ok() { + Ok(probe_response(READY_BODY)) + } else { + Err(HttpError::plain(ProblemCode::ServiceUnavailable)) + } +} + async fn healthz() -> StatusCode { StatusCode::OK } @@ -262,7 +293,7 @@ async fn readyz(State(state): State) -> Result if state.service.ready().await.is_ok() { Ok(StatusCode::OK) } else { - Err(HttpError(ProblemCode::ServiceUnavailable)) + Err(HttpError::plain(ProblemCode::ServiceUnavailable)) } } @@ -598,13 +629,13 @@ async fn list_operational_appointments( record_type, identifier, }), - _ => return Err(HttpError(ProblemCode::RequestInvalid)), + _ => return Err(HttpError::plain(ProblemCode::RequestInvalid)), }; if profile .as_deref() .is_some_and(|profile| !valid_identifier(profile)) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let filter = crate::operational::OperationalReadFilter::with_optional_filters( service, @@ -617,9 +648,8 @@ async fn list_operational_appointments( start, end, ) - .map_err(|_| HttpError(ProblemCode::RequestInvalid))?; - let token = - bearer_token(&headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + .map_err(|_| HttpError::plain(ProblemCode::RequestInvalid))?; + let token = bearer_token(&headers)?; let authority = state .authenticator .authenticate_operational_read( @@ -832,7 +862,7 @@ fn bounded_selection( if duration_minutes.is_some_and(|value| { !(1..=registry_scheduling_core::MAXIMUM_BOOKING_DURATION_MINUTES).contains(&value) }) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } if let Some(resource) = &resource { bounded_identifier(resource)?; @@ -853,41 +883,48 @@ struct ExplainQuery { } async fn authenticate_read(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_read(token) .await - .map_err(authentication_problem) + .map_err(|error| { + authentication_problem(error) + .with_scope_remedy() + .with_declared_scope(state.authenticator.declared_reads_scope()) + }) } async fn authenticate_appointment_detail( state: &HttpState, headers: &HeaderMap, ) -> Result<(Caller, DetailAdmission), HttpError> { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_appointment_detail(token) .await - .map_err(authentication_problem) + .map_err(|error| { + authentication_problem(error) + .with_declared_scope(state.authenticator.declared_reads_scope()) + }) } async fn authenticate_explain(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_explain(token) .await - .map_err(authentication_problem) + .map_err(|error| { + authentication_problem(error) + .with_scope_remedy() + .with_declared_scope(state.authenticator.declared_explain_scope()) + }) } async fn authenticate_mutate(state: &HttpState, headers: &HeaderMap) -> Result { - let token = - bearer_token(headers).inspect_err(|_| state.authenticator.record_header_refusal())?; + let token = bearer_token(headers)?; state .authenticator .authenticate_mutate(token) @@ -896,24 +933,36 @@ async fn authenticate_mutate(state: &HttpState, headers: &HeaderMap) -> Result Result<&str, HttpError> { + let refused = |check| HttpError::refused(RefusalCode::AuthenticationRefused, check); let authorization = headers .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .ok_or(HttpError(ProblemCode::AuthenticationRefused))?; - parse_bearer_token(authorization).map_err(|_| HttpError(ProblemCode::AuthenticationRefused)) + .ok_or_else(|| refused(FailedCheck::CredentialMissing))? + .to_str() + .map_err(|_| refused(FailedCheck::CredentialMalformed))?; + parse_bearer_token(authorization).map_err(|error| { + refused(match error { + // Another scheme is a credential this route does not take. + BearerParseError::InvalidScheme => FailedCheck::CredentialMissing, + _ => FailedCheck::CredentialMalformed, + }) + }) } fn authentication_problem(error: AuthenticationError) -> HttpError { match error { - AuthenticationError::Refused | AuthenticationError::Claims => { - HttpError(ProblemCode::AuthenticationRefused) + AuthenticationError::Refused(check) | AuthenticationError::Claims(check) => { + HttpError::refused(RefusalCode::AuthenticationRefused, check) + } + AuthenticationError::Profile(check) => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, check) } - AuthenticationError::Profile => HttpError(ProblemCode::ProfileNotAuthorized), // The verifier reached no verdict, so the credential is not what is // wrong. Answering 401 here would challenge a caller holding a good // token and invite it to rotate one during an outage that is ours; // `service.unavailable` carries `Retry-After` instead. - AuthenticationError::Unavailable => HttpError(ProblemCode::ServiceUnavailable), + AuthenticationError::Unavailable => { + HttpError::unavailable(FailedCheck::KeySourceUnavailable) + } } } @@ -946,7 +995,7 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { bounded_references(&request.capabilities)?; bounded_references(&request.prerequisites)?; if request.external_references.len() > MAXIMUM_COLLECTION_ENTRIES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let mut unique = BTreeSet::new(); for reference in &request.external_references { @@ -956,11 +1005,11 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { reference.record_type.as_str(), reference.identifier.as_str(), )) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } } if request.party_references.len() > registry_scheduling_core::MAXIMUM_PARTY_REFERENCES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } let mut unique_parties = BTreeSet::new(); for party in &request.party_references { @@ -971,7 +1020,7 @@ fn bounded_admission(request: &AdmissionRequest) -> Result<(), HttpError> { party.reference.record_type.as_str(), party.reference.identifier.as_str(), )) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } } Ok(()) @@ -987,20 +1036,20 @@ fn bounded_external_reference(reference: &ExternalReference) -> Result<(), HttpE fn bounded_identifier(value: &str) -> Result<(), HttpError> { valid_identifier(value) .then_some(()) - .ok_or(HttpError(ProblemCode::RequestInvalid)) + .ok_or(HttpError::plain(ProblemCode::RequestInvalid)) } /// One scoped reference as the authored grammar admits it. fn bounded_reference(value: &str) -> Result<(), HttpError> { valid_reference(value) .then_some(()) - .ok_or(HttpError(ProblemCode::RequestInvalid)) + .ok_or(HttpError::plain(ProblemCode::RequestInvalid)) } /// A list of scoped references, no longer than a policy collection may be. fn bounded_references(values: &[String]) -> Result<(), HttpError> { if values.len() > MAXIMUM_COLLECTION_ENTRIES { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } values.iter().try_for_each(|value| bounded_reference(value)) } @@ -1009,7 +1058,7 @@ fn bounded_references(values: &[String]) -> Result<(), HttpError> { fn bounded_reason(reason: Option<&str>) -> Result<(), HttpError> { match reason { Some(reason) if reason.len() > MAXIMUM_CANCELLATION_REASON_BYTES => { - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError::plain(ProblemCode::RequestInvalid)) } _ => Ok(()), } @@ -1022,33 +1071,140 @@ fn idempotency_key(headers: &HeaderMap) -> Result<&str, HttpError> { .get(IDEMPOTENCY_KEY_HEADER) .and_then(|value| value.to_str().ok()) .filter(|value| !value.is_empty()) - .ok_or(HttpError(ProblemCode::RequestInvalid))?; + .ok_or(HttpError::plain(ProblemCode::RequestInvalid))?; if value.len() > MAXIMUM_IDEMPOTENCY_KEY_BYTES || !value.bytes().all(|byte| byte.is_ascii_graphic()) { - return Err(HttpError(ProblemCode::RequestInvalid)); + return Err(HttpError::plain(ProblemCode::RequestInvalid)); } Ok(value) } -/// One refusal from the closed vocabulary, as an HTTP answer: every product +/// One answer from the closed vocabulary, as an HTTP answer: every product /// decision and every request-edge rejection renders through the same pinned -/// document. +/// document. A refusal of authority also carries the check it failed, which +/// reaches the operator's counter and log line through the response +/// extensions and never the caller's body. #[derive(Debug)] -pub struct HttpError(pub ProblemCode); +pub struct HttpError { + problem: ProblemCode, + note: Option, + /// The operator-declared scope values a scope refusal's log line names. + declared: Option, +} + +impl HttpError { + /// An answer that is not a refusal of authority. A refusal code is built + /// with [`HttpError::refused`] so it names its check. + pub(crate) fn plain(problem: ProblemCode) -> Self { + if RefusalCode::of(problem).is_some() { + debug_assert!(false, "a refusal was built without its failed check"); + tracing::error!( + code = problem.code(), + "a refusal was answered without its failed check" + ); + } + Self { + problem, + note: None, + declared: None, + } + } + + /// A refusal of authority, with the check it failed. + pub(crate) fn refused(code: RefusalCode, check: FailedCheck) -> Self { + Self { + problem: code.problem(), + note: Some(RefusalNote::new(check)), + declared: None, + } + } + + /// `service.unavailable`, counted under the check that could not be made. + pub(crate) fn unavailable(check: FailedCheck) -> Self { + Self { + problem: ProblemCode::ServiceUnavailable, + note: Some(RefusalNote::new(check)), + declared: None, + } + } + + /// Attach the values the operator declared for the scope this route + /// demands. They ride in the response extensions and are written to the + /// log line only for a scope refusal. + fn with_declared_scope(mut self, declared: DeclaredScope) -> Self { + self.declared = Some(declared); + self + } + + /// Name the setting the operator checks when this is a scope refusal of + /// a read or explain route. + fn with_scope_remedy(mut self) -> Self { + self.note = self.note.map(|note| { + if note.check == FailedCheck::Scope { + note.with_remedy(SCOPE_REMEDY) + } else { + note + } + }); + self + } +} + +/// The fixed operator hint on a read or explain scope refusal. +const SCOPE_REMEDY: &str = "check authentication.oidc.scopeClaim and readsScope or explainScope"; impl From for HttpError { fn from(error: ServiceError) -> Self { match error { - ServiceError::Problem(problem) => Self(problem), + ServiceError::Problem(problem) => Self::plain(problem), + ServiceError::Refused { code, check } => Self::refused(code, check), } } } impl IntoResponse for HttpError { fn into_response(self) -> Response { - problem_response(self.0) + let mut response = problem_response(self.problem); + if let Some(note) = self.note { + response.extensions_mut().insert(note); + } + if let Some(declared) = self.declared { + response.extensions_mut().insert(declared); + } + response + } +} + +/// Record the refusals the routes answer. The edge layers wrap this one, so +/// the request's trace is in scope when a refusal is recorded. +fn with_refusal_recording(routes: Router, recorder: Arc) -> Router +where + S: Clone + Send + Sync + 'static, +{ + routes.layer(middleware::from_fn_with_state(recorder, record_refusals)) +} + +/// Count and log every refusal an answer carries, once, after the route has +/// answered. The note rides in the response extensions, which are never +/// serialized, so recording cannot change a byte of the answer. +async fn record_refusals( + State(recorder): State>, + request: Request, + next: Next, +) -> Response { + let response = next.run(request).await; + if let Some(note) = response.extensions().get::().copied() { + let trace = current_trace(); + let declared = response.extensions().get::(); + record_refusal!( + recorder, + note, + trace_id = &trace.trace_id, + declared = declared + ); } + response } fn current_trace() -> TraceContext { @@ -1207,6 +1363,247 @@ mod tests { ) } + /// The refusals a request can meet, by case name, as the handlers build + /// them: one route that answers each one under the recording layer. + fn refusal_case(case: &str) -> HttpError { + match case { + "credential-missing" => bearer_token(&HeaderMap::new()).unwrap_err(), + "credential-malformed" => { + bearer_token(&headers_with(AUTHORIZATION, "Bearer a b")).unwrap_err() + } + "token-signature" => { + authentication_problem(AuthenticationError::Refused(FailedCheck::TokenSignature)) + } + "scope" => authentication_problem(AuthenticationError::Profile(FailedCheck::Scope)) + .with_scope_remedy(), + "operation" => { + HttpError::refused(RefusalCode::ProfileNotAuthorized, FailedCheck::Operation) + } + "task-grant-missing" => ServiceError::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::TaskGrantMissing, + } + .into(), + "visibility" => ServiceError::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::Visibility, + } + .into(), + "task-grant-lifetime" => HttpError::refused( + RefusalCode::GrantLifetimeTooLong, + FailedCheck::TaskGrantLifetime, + ), + "key-source-unavailable" => authentication_problem(AuthenticationError::Unavailable), + "plain" => HttpError::plain(ProblemCode::RequestInvalid), + other => unreachable!("no refusal case named {other}"), + } + } + + fn refusal_router(recorder: Arc) -> Router { + async fn refuse(Path(case): Path) -> HttpError { + refusal_case(&case) + } + http_edge(with_refusal_recording( + Router::new().route("/refuse/{case}", get(refuse)), + recorder, + )) + } + + fn refusal_exposition(recorder: &RefusalRecorder) -> String { + let mut out = registry_platform_metrics::Exposition::new(); + recorder + .counter() + .write(&mut out) + .expect("the counter writes"); + out.finish() + } + + fn refusal_lines(captured: ®istry_platform_testing::CapturedDiagnosticLogs) -> Vec { + captured + .text() + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect() + } + + const REFUSAL_CASES: [&str; 8] = [ + "credential-missing", + "credential-malformed", + "token-signature", + "scope", + "operation", + "task-grant-missing", + "visibility", + "task-grant-lifetime", + ]; + + /// The renderer answers each refusal code with the status, headers and + /// body the golden file holds, with the trace id removed. The cases build + /// each error directly, so this pins the rendering. The postgres suite + /// pins which code each real path answers. + #[tokio::test] + async fn the_refusal_renderer_matches_the_golden_bodies() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let mut observed = serde_json::Map::new(); + for case in REFUSAL_CASES.into_iter().chain(["key-source-unavailable"]) { + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let response = refusal_router(Arc::clone(&recorder)) + .oneshot(traced_request("GET", &format!("/refuse/{case}"))) + .with_subscriber(captured.subscriber()) + .await + .expect("an in-process request always answers"); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("an ASCII header").to_owned()) + }; + let mut entry = serde_json::json!({ + "status": response.status().as_u16(), + "contentType": header("content-type"), + "wwwAuthenticate": header("www-authenticate"), + "retryAfter": header("retry-after"), + "cacheControl": header("cache-control"), + }); + let mut body = body_json(response).await; + assert_eq!(body["traceId"], TRACE_ID, "{case}"); + body.as_object_mut().unwrap().remove("traceId"); + entry["body"] = body; + observed.insert(case.to_owned(), entry); + } + let golden: Value = + serde_json::from_str(include_str!("../tests/golden/refusal-answers.json")) + .expect("the golden file is JSON"); + assert_eq!(Value::Object(observed), golden); + } + + #[tokio::test] + async fn each_refusal_is_counted_and_logged_once_under_its_check() { + use tracing::instrument::WithSubscriber as _; + for (case, check) in [ + ("credential-missing", "credential-missing"), + ("credential-malformed", "credential-malformed"), + ("token-signature", "token-signature"), + ("scope", "scope"), + ("operation", "operation"), + ("task-grant-missing", "task-grant-missing"), + ("visibility", "visibility"), + ("task-grant-lifetime", "task-grant-lifetime"), + ("key-source-unavailable", "key-source-unavailable"), + ] { + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let request = Request::builder() + .uri(format!("/refuse/{case}")) + .header("traceparent", TRACEPARENT) + .header("authorization", "Bearer canary-credential-value") + .header("x-canary", "canary-header-value") + .body(Body::empty()) + .unwrap(); + refusal_router(Arc::clone(&recorder)) + .oneshot(request) + .with_subscriber(captured.subscriber()) + .await + .expect("an in-process request always answers"); + let exposition = refusal_exposition(&recorder); + assert!( + exposition.contains(&format!( + "scheduling_request_refusals_total{{check=\"{check}\"}} 1" + )), + "{case}: {exposition}" + ); + assert_eq!( + exposition.matches("} 1\n").count(), + 1, + "{case} counted under one check only" + ); + let lines = refusal_lines(&captured); + assert_eq!(lines.len(), 1, "{case}"); + assert_eq!(lines[0]["fields"]["failed_check"], check, "{case}"); + assert_eq!(lines[0]["fields"]["decision"], "refused", "{case}"); + assert_eq!(lines[0]["fields"]["trace_id"], TRACE_ID, "{case}"); + let rendered = captured.text(); + assert!(!rendered.contains("canary"), "{case}: {rendered}"); + } + } + + #[tokio::test] + async fn a_scope_refusal_names_the_settings_to_check() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + refusal_router(recorder) + .oneshot(traced_request("GET", "/refuse/scope")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + let lines = refusal_lines(&captured); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["remedy"], SCOPE_REMEDY); + } + + #[tokio::test] + async fn an_answer_that_is_not_a_refusal_records_nothing() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let response = refusal_router(Arc::clone(&recorder)) + .oneshot(traced_request("GET", "/refuse/plain")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(!refusal_exposition(&recorder).contains("} 1\n")); + assert!(refusal_lines(&captured).is_empty()); + } + + #[tokio::test] + async fn a_flood_of_one_refusal_is_counted_in_full_and_logged_in_part() { + use tracing::instrument::WithSubscriber as _; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let captured = registry_platform_testing::CapturedDiagnosticLogs::default(); + let router = refusal_router(Arc::clone(&recorder)); + for _ in 0..50 { + router + .clone() + .oneshot(traced_request("GET", "/refuse/token-signature")) + .with_subscriber(captured.subscriber()) + .await + .unwrap(); + } + assert!(refusal_exposition(&recorder) + .contains("scheduling_request_refusals_total{check=\"token-signature\"} 50")); + assert_eq!( + refusal_lines(&captured).len(), + registry_platform_authcommon::REFUSAL_LOG_LINES_PER_WINDOW as usize + ); + } + + #[test] + fn a_problem_code_is_a_refusal_exactly_when_it_refuses_authority() { + let refusals: Vec<_> = ProblemCode::ALL + .iter() + .filter(|problem| RefusalCode::of(**problem).is_some()) + .map(|problem| problem.code()) + .collect(); + assert_eq!( + refusals, + [ + "authentication.refused", + "grant.lifetime-too-long", + "operation.not-authorized", + "profile.not-authorized" + ] + ); + for problem in ProblemCode::ALL { + if let Some(code) = RefusalCode::of(*problem) { + assert_eq!(code.problem(), *problem); + } + } + } + #[tokio::test] async fn an_unknown_route_answers_the_pinned_problem_under_the_callers_trace() { let response = send(edge_router(), traced_request("GET", "/v1/nothing")).await; @@ -1451,11 +1848,14 @@ mod tests { let problem = authentication_problem(AuthenticationError::Unavailable); assert!(matches!( problem, - HttpError(ProblemCode::ServiceUnavailable) + HttpError { + problem: ProblemCode::ServiceUnavailable, + .. + } )); let response = REQUEST_TRACE .scope(TraceContext::server_created(), async { - problem_response(problem.0) + problem_response(problem.problem) }) .await; assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); @@ -1467,15 +1867,24 @@ mod tests { #[test] fn a_refused_credential_still_answers_a_challenge() { - for refusal in [AuthenticationError::Refused, AuthenticationError::Claims] { + for refusal in [ + AuthenticationError::Refused(FailedCheck::TokenSignature), + AuthenticationError::Claims(FailedCheck::TokenClaims), + ] { assert!(matches!( authentication_problem(refusal), - HttpError(ProblemCode::AuthenticationRefused) + HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + } )); } assert!(matches!( - authentication_problem(AuthenticationError::Profile), - HttpError(ProblemCode::ProfileNotAuthorized) + authentication_problem(AuthenticationError::Profile(FailedCheck::Scope)), + HttpError { + problem: ProblemCode::ProfileNotAuthorized, + .. + } )); } @@ -1636,7 +2045,10 @@ mod tests { assert!( matches!( bounded_admission(&request), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) ), "an unbounded caller string reached the store: {request:?}" ); @@ -1652,7 +2064,10 @@ mod tests { external_references: vec![duplicate.clone(), duplicate], ..admission() }), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1666,7 +2081,10 @@ mod tests { // the service is down for a request only the caller can fix. assert!(matches!( bounded_reason(Some(&"r".repeat(MAXIMUM_CANCELLATION_REASON_BYTES + 1))), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1675,7 +2093,10 @@ mod tests { bounded_identifier("registry-update-30").expect("an authored offering reads"); assert!(matches!( bounded_identifier(&"o".repeat(65)), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1692,7 +2113,10 @@ mod tests { Some(registry_scheduling_core::MAXIMUM_BOOKING_DURATION_MINUTES + 1), None ), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); } @@ -1706,20 +2130,32 @@ mod tests { fn the_idempotency_key_is_present_bounded_and_graphical() { assert!(matches!( idempotency_key(&HeaderMap::new()), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "")), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "a key with spaces")), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); let oversized = "k".repeat(MAXIMUM_IDEMPOTENCY_KEY_BYTES + 1); assert!(matches!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, &oversized)), - Err(HttpError(ProblemCode::RequestInvalid)) + Err(HttpError { + problem: ProblemCode::RequestInvalid, + .. + }) )); assert_eq!( idempotency_key(&headers_with(IDEMPOTENCY_KEY_HEADER, "hold-7")).unwrap(), @@ -1744,11 +2180,17 @@ mod tests { ); assert!(matches!( bearer_token(&headers_with(AUTHORIZATION, "Basic dXNlcjpwYXNz")), - Err(HttpError(ProblemCode::AuthenticationRefused)) + Err(HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + }) )); assert!(matches!( bearer_token(&HeaderMap::new()), - Err(HttpError(ProblemCode::AuthenticationRefused)) + Err(HttpError { + problem: ProblemCode::AuthenticationRefused, + .. + }) )); } } diff --git a/crates/registry-scheduling/src/lib.rs b/crates/registry-scheduling/src/lib.rs index 317b6b1f18..1e6682c56b 100644 --- a/crates/registry-scheduling/src/lib.rs +++ b/crates/registry-scheduling/src/lib.rs @@ -25,6 +25,7 @@ pub mod hooks; pub mod http; pub mod metrics; pub mod operational; +pub mod refusal; pub mod runtime; #[cfg(feature = "schema")] pub mod schema; diff --git a/crates/registry-scheduling/src/metrics.rs b/crates/registry-scheduling/src/metrics.rs index f2d16bffd1..a3d5b17b78 100644 --- a/crates/registry-scheduling/src/metrics.rs +++ b/crates/registry-scheduling/src/metrics.rs @@ -13,6 +13,10 @@ //! runtime's own loops. Paths, appointment or hold identifiers, principals, //! and problem details never become labels. //! +//! The refusal counter, `scheduling_request_refusals_total`, is labelled by +//! the check a request failed. The check is a closed set of 45 names, never a +//! value a caller sent. +//! //! The outbox and hook-delivery series are gauges sampled from the store when //! the metrics are scraped. When a queue cannot be read its gauges have no //! samples for that scrape, so the series goes stale rather than reporting an @@ -36,6 +40,7 @@ use axum::http::header::CONTENT_TYPE; use axum::http::{Method, Request, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use registry_platform_authcommon::RefusalRecorder; use registry_platform_metrics::{ CounterVec, Exposition, LabelSpace, MetricKind, ScrapeDeadline, CONTENT_TYPE as METRICS_CONTENT_TYPE, @@ -124,6 +129,9 @@ impl SampledQueue { pub struct Metrics { requests: CounterVec, sample_failures: CounterVec, + /// The recorder the HTTP edge reports each refusal to. Its counter is + /// written into the exposition when one is attached. + refusals: Option>, started: Instant, /// Seconds after `started` at which each worker last completed a pass. last_success: [AtomicU64; 2], @@ -156,6 +164,7 @@ impl Default for Metrics { LabelSpace::closed_zero_filled(&["queue"], &queues).expect(DECLARATION), ) .expect(DECLARATION), + refusals: None, started: Instant::now(), last_success: [AtomicU64::new(0), AtomicU64::new(0)], } @@ -171,6 +180,14 @@ pub struct Sampled { } impl Metrics { + /// Expose `scheduling_request_refusals_total`, the counter of `refusals`, + /// beside the other series. + #[must_use] + pub fn with_refusals(mut self, refusals: Arc) -> Self { + self.refusals = Some(refusals); + self + } + /// Count one answered request under its closed labels. pub fn record_request(&self, route: &str, method: &Method, status: StatusCode) { count( @@ -204,6 +221,9 @@ impl Metrics { let mut out = Exposition::new(); self.requests.write(&mut out).expect(DECLARATION); self.sample_failures.write(&mut out).expect(DECLARATION); + if let Some(refusals) = &self.refusals { + refusals.counter().write(&mut out).expect(DECLARATION); + } write_queue( &mut out, "scheduling_outbox_items", @@ -429,6 +449,30 @@ mod tests { )); } + #[test] + fn the_refusal_counter_is_exposed_for_every_check_once_attached() { + use registry_platform_authcommon::FailedCheck; + let recorder = Arc::new(RefusalRecorder::new("scheduling").unwrap()); + let unattached = Metrics::default().render(&Sampled::default()); + assert!(!unattached.contains("scheduling_request_refusals_total")); + + let metrics = Metrics::default().with_refusals(Arc::clone(&recorder)); + assert!(recorder.record(FailedCheck::Scope).is_some()); + let text = metrics.render(&Sampled::default()); + assert!(text.contains("# TYPE scheduling_request_refusals_total counter")); + assert!(text.contains("scheduling_request_refusals_total{check=\"scope\"} 1")); + for check in FailedCheck::ALL { + assert!( + text.contains(&format!( + "scheduling_request_refusals_total{{check=\"{}\"}}", + check.as_str() + )), + "{} has no series", + check.as_str() + ); + } + } + #[test] fn every_status_has_its_own_bounded_class() { let class = |code: u16| status_class(StatusCode::from_u16(code).unwrap()); diff --git a/crates/registry-scheduling/src/refusal.rs b/crates/registry-scheduling/src/refusal.rs new file mode 100644 index 0000000000..a1a9ab73ff --- /dev/null +++ b/crates/registry-scheduling/src/refusal.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The problem codes that refuse a caller's authority. +//! +//! Kept apart from the request path so the vocabulary classification names +//! every problem code on purpose: the OpenAPI generator reads the request +//! path for the codes it produces, and a classification there would count +//! every code as produced. + +use registry_scheduling_core::ProblemCode; + +/// The problem codes that refuse a caller's authority. A refusal is built +/// with the check it failed (`ServiceError::Refused`), never from the bare +/// code, so the operator's counter and log line can name the check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefusalCode { + AuthenticationRefused, + GrantLifetimeTooLong, + OperationNotAuthorized, + ProfileNotAuthorized, +} + +impl RefusalCode { + /// The problem this refusal answers with. + #[must_use] + pub const fn problem(self) -> ProblemCode { + match self { + Self::AuthenticationRefused => ProblemCode::AuthenticationRefused, + Self::GrantLifetimeTooLong => ProblemCode::GrantLifetimeTooLong, + Self::OperationNotAuthorized => ProblemCode::OperationNotAuthorized, + Self::ProfileNotAuthorized => ProblemCode::ProfileNotAuthorized, + } + } + + /// Sort a problem into a refusal or a plain answer. The match names every + /// code, so a code added to the vocabulary does not compile until it is + /// sorted here. The vocabulary test in `http.rs` pins the refusal set. + #[must_use] + #[deny(clippy::wildcard_enum_match_arm)] + pub const fn of(problem: ProblemCode) -> Option { + match problem { + ProblemCode::AuthenticationRefused => Some(Self::AuthenticationRefused), + ProblemCode::GrantLifetimeTooLong => Some(Self::GrantLifetimeTooLong), + ProblemCode::OperationNotAuthorized => Some(Self::OperationNotAuthorized), + ProblemCode::ProfileNotAuthorized => Some(Self::ProfileNotAuthorized), + ProblemCode::BookingDuplicateActive + | ProblemCode::CancellationCutoffPassed + | ProblemCode::CapabilityUnmatched + | ProblemCode::CapacityExhausted + | ProblemCode::CursorExpired + | ProblemCode::CursorInvalid + | ProblemCode::EligibilityUnavailable + | ProblemCode::HoldExpired + | ProblemCode::HoldReleased + | ProblemCode::HookUnavailable + | ProblemCode::HorizonOutside + | ProblemCode::IdempotencyExpired + | ProblemCode::IdempotencyKeyReused + | ProblemCode::LocationClosed + | ProblemCode::PartyCapacityInadequate + | ProblemCode::PolicyChanged + | ProblemCode::PreconditionFailed + | ProblemCode::PreconditionRequired + | ProblemCode::PrerequisiteMissing + | ProblemCode::ReceiptUnresolved + | ProblemCode::RequestBodyTooLarge + | ProblemCode::RequestInvalid + | ProblemCode::RequestMethodNotAllowed + | ProblemCode::RequestNotFound + | ProblemCode::RequestUnprocessable + | ProblemCode::RequestUnsupportedMediaType + | ProblemCode::ResourceUnavailable + | ProblemCode::RevisionMismatch + | ProblemCode::ScheduleUnpublished + | ProblemCode::ServiceUnavailable => None, + } + } +} diff --git a/crates/registry-scheduling/src/runtime.rs b/crates/registry-scheduling/src/runtime.rs index cebc632ba3..99b1349dff 100644 --- a/crates/registry-scheduling/src/runtime.rs +++ b/crates/registry-scheduling/src/runtime.rs @@ -31,6 +31,7 @@ //! sends the stale reminder, and the receiver gets no ordering promise //! across processes: that is inherent to at-least-once delivery. +use std::collections::BTreeMap; use std::future::Future; use std::num::NonZeroUsize; use std::path::Path; @@ -39,18 +40,20 @@ use std::time::{Duration, SystemTime}; use clap::{Arg, Command}; use registry_platform_audit::{AuditProfile, AuditWriter}; -use registry_platform_config::{ProtectedSecret, SecretResolver, MAX_SECRET_BYTES}; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields, SigningError}; -use registry_platform_dispatch::idempotency_key; +use registry_platform_config::{ProtectedSecret, SecretReference, SecretResolver}; +use registry_platform_crypto::delivery_signature::{ + distinct_delivery_keys, sign, DeliveryKey, DeliveryKeys, +}; use registry_platform_dispatch::postgres::{DispatchOutcome, DispatchWorker, WorkerConfig}; +use registry_platform_hooks::delivery::ActivatedUrlHookDestinations; use registry_platform_hooks::{Causation, EnvelopeLimits, EventSubject, HookEnvelope}; use registry_platform_httputil::destination::{ - DataDestinationPolicy, DataDestinationRequestTemplate, DestinationAuthorizationTemplate, - DestinationBodyTemplate, DestinationMethod, DestinationProfile, FixedDestinationPolicy, + DataDestinationPolicy, DataDestinationRequest, DataDestinationRequestTemplate, + DestinationAuthorizationTemplate, DestinationBodyTemplate, DestinationMethod, + DestinationProfile, DestinationRequestError, FixedDestinationPolicy, }; use registry_platform_oidc::task_grant::TaskGrantStatusRegistry; use thiserror::Error; -use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio::time::{Interval, MissedTickBehavior}; @@ -61,7 +64,10 @@ use crate::config::{ reminder_destination_origin_and_path, same_reminder_destination_origin, ReminderDestinationConfig, RuntimeConfig, RuntimeConfigError, TaskGrantStatus, }; -use crate::hooks::{ActivatedHooks, HookActivationError, HookRuntimeIdentity}; +use crate::hooks::{ + invalid_delivery_key, repeated_delivery_key, repeated_rotation_key, ActivatedHooks, + HookActivationError, HookRuntimeIdentity, CURRENT_KEY_MEMBER, PREVIOUS_KEY_MEMBER, +}; use crate::http::{metrics_router, router, HttpState}; use crate::metrics::{count_requests, Metrics, Worker}; use crate::service::SchedulingService; @@ -82,18 +88,7 @@ const INTENT_DRAIN_LIMIT: usize = 1024; /// One rendered reminder event is bounded, as is the whole request. const REMINDER_MAXIMUM_BODY_BYTES: usize = 16 * 1024; const REMINDER_MAXIMUM_REQUEST_BYTES: usize = 32 * 1024; -const REMINDER_BEARER_MAXIMUM_BYTES: usize = 8192; -const MIN_REMINDER_HMAC_SHA256_KEY_BYTES: usize = 32; -const REMINDER_IDEMPOTENCY_DOMAIN: &[u8] = b"scheduling-reminder-delivery-v1"; -const REMINDER_ACCEPT_MAXIMUM_BYTES: usize = 32; -const REMINDER_CONTENT_TYPE_MAXIMUM_BYTES: usize = 64; -const REMINDER_EVENT_ID_MAXIMUM_BYTES: usize = 128; -const REMINDER_EVENT_SOURCE_MAXIMUM_BYTES: usize = 2_048; -const REMINDER_EVENT_TYPE_MAXIMUM_BYTES: usize = 256; -const REMINDER_EVENT_TIME_MAXIMUM_BYTES: usize = 64; -const REMINDER_EVENT_DATASCHEMA_MAXIMUM_BYTES: usize = 2_048; -const REMINDER_DELIVERY_FIELD_MAXIMUM_BYTES: usize = 256; -const REMINDER_SIGNATURE_MAXIMUM_BYTES: usize = 256; +const REMINDER_CONFIG_PATH: &str = "destinations.reminders"; #[must_use] pub fn command() -> Command { @@ -238,6 +233,13 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> hook_payload_retention, )?; + let reminders = activate_reminder_delivery( + config.destinations.reminders.as_ref(), + hooks.destination_bindings(), + &secrets, + ) + .map_err(RuntimeError::Destination)?; + // The audit destination is keyed and opened before the listener binds, // so a mis-provisioned deployment never serves a request it cannot hold // to account. @@ -259,13 +261,6 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> keys, )); - let reminders = match &config.destinations.reminders { - Some(destination) => { - Some(reminder_transport(destination, &secrets).map_err(RuntimeError::Destination)?) - } - None => None, - }; - // A deployment that lists status authorities resolves every commitment // through that exact registry. An unlisted source therefore fails closed // instead of falling back to the short-lived offline path, which only @@ -274,7 +269,7 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> let task_grant_status = match &config.task_grant_status { Some(TaskGrantStatus::UncheckedFinalFifteenMinutes) => None, Some(TaskGrantStatus::Authorities(authorities)) => Some(Arc::new( - TaskGrantStatusRegistry::activate( + TaskGrantStatusRegistry::activate_without_peer_policy( &crate::config::task_grant_status_endpoints(authorities), &config.authentication.oidc.provider.audience, &secrets, @@ -301,7 +296,7 @@ pub async fn serve_from_path(path: impl AsRef) -> Result<(), RuntimeError> let (worker_stopped, worker_stops) = mpsc::channel(WORKER_STOP_CAPACITY); let mut workers = Vec::new(); - let metrics = Arc::new(Metrics::default()); + let metrics = Arc::new(Metrics::default().with_refusals(Arc::clone(authenticator.refusals()))); let expiry_store = store.clone(); let expiry_metrics = Arc::clone(&metrics); @@ -614,7 +609,7 @@ pub async fn open_audit( .for_process(process) .map_err(|error| RuntimeError::AuditDestination(error.to_string()))?; } - let writer = AuditWriter::open(destination) + let writer = AuditWriter::open_without_posture(destination) .await .map_err(|error| RuntimeError::AuditDestination(error.operator_description()))?; Ok((audit_profile.key_hasher(), SchedulingAudit::new(writer))) @@ -648,9 +643,8 @@ pub fn secret_resolver(config: &RuntimeConfig) -> Result Result, - hmac_sha256_key: Option, + fallback: ReminderRequestTarget, + purposes: BTreeMap<&'static str, ReminderRequestTarget>, } struct ReminderRequestTarget { template: DataDestinationRequestTemplate, - request_target: String, + keys: DeliveryKeys, } -struct ReminderRequestTargets { - confirmation: ReminderRequestTarget, - change: ReminderRequestTarget, - cancellation: ReminderRequestTarget, - reminder: ReminderRequestTarget, +impl ReminderRequestTarget { + fn render( + &self, + event: RenderedReminderEvent, + attempt_started_at: SystemTime, + ) -> Result { + let timestamp = attempt_started_at + .duration_since(SystemTime::UNIX_EPOCH) + .map_err(|_| DestinationRequestError::InvalidHeaderValue)? + .as_secs(); + let signature = sign(&self.keys, &event.id, timestamp, &event.body) + .map_err(|_| DestinationRequestError::InvalidHeaderValue)?; + self.template.render( + &[], + &[ + b"application/json", + b"application/json", + event.id.as_bytes(), + timestamp.to_string().as_bytes(), + signature.as_bytes(), + ], + None, + Some(event.body), + ) + } } impl ReminderTransport { fn target_for_purpose(&self, purpose: &str) -> Option<&ReminderRequestTarget> { match purpose { - "confirmation" => Some(&self.targets.confirmation), - "change" => Some(&self.targets.change), - "cancellation" => Some(&self.targets.cancellation), - "reminder" => Some(&self.targets.reminder), + "confirmation" | "change" | "cancellation" | "reminder" => { + Some(self.purposes.get(purpose).unwrap_or(&self.fallback)) + } _ => None, } } } -/// Compile one operator-configured destination into the frozen transport the -/// dispatch loop sends through. +fn resolve_delivery_key( + secrets: &SecretResolver, + path: &str, + reference: &SecretReference, +) -> Result { + let secret = secrets + .resolve_binary_reference(reference) + .map_err(|error| { + format!( + "{path} could not be resolved: {error}. {}", + error.suggested_action() + ) + })?; + let bytes = secret.expose_secret(); + DeliveryKey::new(bytes) + .map_err(|error| invalid_delivery_key(path, bytes.len(), bytes.ends_with(b"\n"), error)) +} + +fn key_members(keys: &DeliveryKeys) -> impl Iterator { + std::iter::once((CURRENT_KEY_MEMBER, keys.current())) + .chain(keys.previous().map(|key| (PREVIOUS_KEY_MEMBER, key))) +} + +fn check_delivery_keys( + reminders: &ReminderTransport, + hooks: &ActivatedUrlHookDestinations, +) -> Result<(), String> { + let keys = key_members(&reminders.fallback.keys) + .map(|(member, key)| (format!("{REMINDER_CONFIG_PATH}.{member}"), key)) + .chain(reminders.purposes.iter().flat_map(|(purpose, target)| { + key_members(&target.keys).map(move |(member, key)| { + ( + format!("{REMINDER_CONFIG_PATH}.purposes.{purpose}.{member}"), + key, + ) + }) + })) + .chain(hooks.bindings.iter().flat_map(|(id, destination)| { + key_members(destination.keys()) + .map(move |(member, key)| (format!("destinations.hooks.{id}.{member}"), key)) + })) + .collect::>(); + distinct_delivery_keys(keys.iter().map(|(path, key)| (path.as_str(), *key))) + .map_err(|error| repeated_delivery_key(error.first(), error.second())) +} + +/// Activate the reminder transport and refuse any key reused among reminders +/// and the already activated observer destinations. /// /// # Errors +/// Returns the configuration paths and operator action without key values. +pub fn activate_reminder_delivery( + destination: Option<&ReminderDestinationConfig>, + hooks: &ActivatedUrlHookDestinations, + secrets: &SecretResolver, +) -> Result, String> { + let Some(destination) = destination else { + return Ok(None); + }; + let transport = reminder_transport(destination, secrets)?; + check_delivery_keys(&transport, hooks)?; + Ok(Some(transport)) +} + +/// Compile the fallback and every configured purpose destination into the +/// frozen transport the dispatch loop sends through. /// -/// Returns the operator-facing sentence naming what about the configured -/// destination could not be frozen. +/// # Errors +/// Returns the operator-facing refusal for a destination that cannot activate. pub fn reminder_transport( destination: &ReminderDestinationConfig, secrets: &SecretResolver, ) -> Result { let (origin, _) = reminder_destination_origin_and_path(&destination.url) .ok_or_else(|| "destinations.reminders.url is not a safe destination URL".to_owned())?; - let scheme = origin - .split_once("://") - .map(|(scheme, _)| scheme.to_owned()) - .unwrap_or_default(); - // The configuration check already confines plain http to loopback hosts; - // the transport pins the same rule into the frozen policy. - let profile = match scheme.as_str() { - "https" => DestinationProfile::ProductionHttps, - "http" => DestinationProfile::LoopbackDevelopmentHttp, - _ => return Err("the destination URL scheme is not http(s)".to_owned()), + let profile = if origin.starts_with("https://") { + DestinationProfile::ProductionHttps + } else { + DestinationProfile::LoopbackHttp }; let policy = FixedDestinationPolicy::new("scheduling-reminders", &origin, profile, &[]) .map_err(|_| "the destination could not be frozen as a fixed origin".to_owned())?; - let bearer = destination - .bearer_token_ref - .as_ref() - .map(|reference| { - secrets.resolve(reference).map_err(|error| { - crate::config::describe_secret_failure( - "destinations.reminders.bearerTokenRef", - reference, - &error, - ) - }) - }) - .transpose()?; - let authorization = if bearer.is_some() { - DestinationAuthorizationTemplate::Bearer { - max_value_bytes: REMINDER_BEARER_MAXIMUM_BYTES, + let compile_target = |config_path: &str, + url: &str, + reference: &SecretReference, + previous: Option<&SecretReference>| { + let (_, path) = reminder_destination_origin_and_path(url) + .ok_or_else(|| format!("{config_path}.url is not a safe destination URL"))?; + if !same_reminder_destination_origin(&destination.url, url) { + return Err(format!( + "{config_path}.url must use the fallback URL origin" + )); } - } else { - DestinationAuthorizationTemplate::Forbidden - }; - let hmac_sha256_key = destination - .hmac_sha256_key_ref - .as_ref() - .map(|reference| { - secrets.resolve(reference).map_err(|error| { - crate::config::describe_secret_failure( - "destinations.reminders.hmacSha256KeyRef", - reference, - &error, - ) - }) - }) - .transpose()?; - if hmac_sha256_key.as_ref().is_some_and(|key| { - !(MIN_REMINDER_HMAC_SHA256_KEY_BYTES..=MAX_SECRET_BYTES).contains(&key.len()) - }) { - return Err(format!( - "destinations.reminders.hmacSha256KeyRef must resolve to between {MIN_REMINDER_HMAC_SHA256_KEY_BYTES} and {MAX_SECRET_BYTES} bytes" - )); - } - let signed = hmac_sha256_key.is_some(); - let compile_target = |configured: Option<&str>| { - let configured = configured.unwrap_or(&destination.url); - if !same_reminder_destination_origin(&destination.url, configured) { - return Err( - "destinations.reminders.purposeUrls must use the fallback URL origin".to_owned(), - ); - } - let (_, path) = reminder_destination_origin_and_path(configured).ok_or_else(|| { - "a destinations.reminders purpose URL is not a safe destination URL".to_owned() - })?; - Ok(ReminderRequestTarget { - template: reminder_template(&path, authorization, signed)?, - request_target: path, - }) - }; - Ok(ReminderTransport { - policy, - targets: ReminderRequestTargets { - confirmation: compile_target(destination.purpose_urls.confirmation.as_deref())?, - change: compile_target(destination.purpose_urls.change.as_deref())?, - cancellation: compile_target(destination.purpose_urls.cancellation.as_deref())?, - reminder: compile_target(destination.purpose_urls.reminder.as_deref())?, - }, - bearer, - hmac_sha256_key, - }) -} - -fn reminder_template( - path: &str, - authorization: DestinationAuthorizationTemplate, - signed: bool, -) -> Result { - if signed { - return DataDestinationRequestTemplate::new( + let current_path = format!("{config_path}.{CURRENT_KEY_MEMBER}"); + let previous_path = format!("{config_path}.{PREVIOUS_KEY_MEMBER}"); + let current = resolve_delivery_key(secrets, ¤t_path, reference)?; + let previous = previous + .map(|reference| resolve_delivery_key(secrets, &previous_path, reference)) + .transpose()?; + let keys = DeliveryKeys::new(current, previous) + .map_err(|_| repeated_rotation_key(&previous_path, ¤t_path))?; + let template = DataDestinationRequestTemplate::new( DestinationMethod::ReviewedReadOnlyPost, - path, + &path, &[], &[ - ("accept", REMINDER_ACCEPT_MAXIMUM_BYTES), - ("content-type", REMINDER_CONTENT_TYPE_MAXIMUM_BYTES), - ("ce-specversion", 3), - ("ce-id", REMINDER_EVENT_ID_MAXIMUM_BYTES), - ("ce-source", REMINDER_EVENT_SOURCE_MAXIMUM_BYTES), - ("ce-type", REMINDER_EVENT_TYPE_MAXIMUM_BYTES), - ("ce-time", REMINDER_EVENT_TIME_MAXIMUM_BYTES), - ("ce-dataschema", REMINDER_EVENT_DATASCHEMA_MAXIMUM_BYTES), - ( - "x-registry-event-generation", - REMINDER_DELIVERY_FIELD_MAXIMUM_BYTES, - ), - ( - "x-registry-delivery-attempt", - REMINDER_DELIVERY_FIELD_MAXIMUM_BYTES, - ), - ( - "x-registry-delivery-time", - REMINDER_EVENT_TIME_MAXIMUM_BYTES, - ), - ("idempotency-key", REMINDER_DELIVERY_FIELD_MAXIMUM_BYTES), - ("x-registry-signature", REMINDER_SIGNATURE_MAXIMUM_BYTES), + ("accept", 16), + ("content-type", 16), + ("webhook-id", 256), + ("webhook-timestamp", 20), + ("webhook-signature", 256), ], - authorization, + DestinationAuthorizationTemplate::Forbidden, DestinationBodyTemplate::Required { max_bytes: REMINDER_MAXIMUM_BODY_BYTES, }, REMINDER_MAXIMUM_REQUEST_BYTES, ) - .map_err(|_| "the signed reminder request shape could not be compiled".to_owned()); - } - DataDestinationRequestTemplate::new_with_exact_headers( - DestinationMethod::ReviewedReadOnlyPost, - path, - &[], - &[ - ("accept", b"application/json".as_slice()), - ("content-type", b"application/json".as_slice()), - ], - authorization, - DestinationBodyTemplate::Required { - max_bytes: REMINDER_MAXIMUM_BODY_BYTES, - }, - REMINDER_MAXIMUM_REQUEST_BYTES, - ) - .map_err(|_| "the reminder request shape could not be compiled".to_owned()) + .map_err(|error| { + format!("{config_path}.url could not be compiled as a signed reminder request: {error}") + })?; + Ok(ReminderRequestTarget { template, keys }) + }; + let fallback = compile_target( + REMINDER_CONFIG_PATH, + &destination.url, + &destination.hmac_sha256_key_ref, + destination.previous_hmac_sha256_key_ref.as_ref(), + )?; + let purposes = destination + .purposes + .iter() + .map(|(purpose, entry)| { + compile_target( + &format!("{REMINDER_CONFIG_PATH}.purposes.{purpose}"), + &entry.url, + &entry.hmac_sha256_key_ref, + entry.previous_hmac_sha256_key_ref.as_ref(), + ) + .map(|target| (purpose, target)) + }) + .collect::>()?; + Ok(ReminderTransport { + policy, + fallback, + purposes, + }) } /// Render one due intent as the shared hook envelope in canonical JSON, the @@ -848,10 +855,6 @@ fn reminder_template( /// runtime committed. struct RenderedReminderEvent { id: String, - source: String, - event_type: String, - time: String, - data_schema: String, body: Vec, } @@ -876,107 +879,12 @@ fn reminder_event( let body = envelope .to_canonical_bytes(&EnvelopeLimits::tightened_to(REMINDER_MAXIMUM_BODY_BYTES)) .map_err(|_| RuntimeError::ReminderEvent)?; - let wire: serde_json::Value = - serde_json::from_slice(&body).map_err(|_| RuntimeError::ReminderEvent)?; - let time = wire - .get("time") - .and_then(serde_json::Value::as_str) - .ok_or(RuntimeError::ReminderEvent)? - .to_owned(); Ok(RenderedReminderEvent { id: envelope.id, - source: envelope.source, - event_type: envelope.event_type, - time, - data_schema: envelope.dataschema, body, }) } -fn reminder_idempotency_key(event_id: &str) -> String { - idempotency_key(REMINDER_IDEMPOTENCY_DOMAIN, &[event_id.as_bytes()]) -} - -/// The delivery time a signed attempt carries: the database clock when its -/// lease was taken, as the shared verifier reads it. -fn reminder_delivery_time(moment: SystemTime) -> Result { - OffsetDateTime::from(moment).format(&Rfc3339) -} - -struct SignedReminderEvent { - generation: String, - attempt: String, - delivery_time: String, - idempotency_key: String, - signature: String, -} - -impl SignedReminderEvent { - #[cfg(test)] - fn fields<'a>( - &'a self, - event: &'a RenderedReminderEvent, - request_target: &'a str, - ) -> SignatureFields<'a> { - SignatureFields { - id: &event.id, - source: &event.source, - event_type: &event.event_type, - time: &event.time, - data_schema: &event.data_schema, - generation: &self.generation, - attempt: &self.attempt, - delivery_time: &self.delivery_time, - method: "POST", - request_target, - content_type: "application/json", - idempotency_key: &self.idempotency_key, - body: &event.body, - } - } -} - -/// Sign one rendered event for the leased attempt that carries it: the -/// dispatch generation, the attempt counted from one, and the exact request -/// target the selected purpose URL compiled to. -fn sign_reminder_event( - key: &[u8], - event: &RenderedReminderEvent, - generation: i64, - attempt: i16, - request_target: &str, - delivery_time: String, -) -> Result { - let generation = generation.to_string(); - let attempt = attempt.to_string(); - let idempotency_key = reminder_idempotency_key(&event.id); - let signature = sign_v1( - key, - SignatureFields { - id: &event.id, - source: &event.source, - event_type: &event.event_type, - time: &event.time, - data_schema: &event.data_schema, - generation: &generation, - attempt: &attempt, - delivery_time: &delivery_time, - method: "POST", - request_target, - content_type: "application/json", - idempotency_key: &idempotency_key, - body: &event.body, - }, - )?; - Ok(SignedReminderEvent { - generation, - attempt, - delivery_time, - idempotency_key, - signature, - }) -} - /// How one dispatch attempt's outcome is held, before it is written back. enum Delivery { /// The destination took the event. @@ -1152,7 +1060,7 @@ pub async fn send_claimed_intent_for_test( #[cfg(test)] mod tests { use super::*; - use chrono::{DateTime, TimeZone as _, Utc}; + use chrono::{TimeZone as _, Utc}; use registry_platform_config::SecretProvider; use serde_json::Value; use uuid::Uuid; @@ -1205,186 +1113,260 @@ mod tests { assert_eq!(decoded.id, row.outbox_id.to_string()); } - #[test] - fn a_short_reminder_signing_key_is_refused_at_activation() { - let secret_name = - format!("SCHEDULING_SHORT_REMINDER_{}", Uuid::new_v4().simple()).to_ascii_uppercase(); - std::env::set_var(&secret_name, "too-short"); - let secrets = SecretResolver::new([SecretProvider::Environment], "/private/tmp") - .expect("the reminder secret resolver"); - let destination = ReminderDestinationConfig { - url: "http://127.0.0.1:1/reminders".to_owned(), - purpose_urls: Default::default(), - bearer_token_ref: None, - hmac_sha256_key_ref: Some(format!("secret:env/{secret_name}")), - }; - let error = reminder_transport(&destination, &secrets) - .err() - .expect("short signing material is refused"); - assert!( - error.contains("destinations.reminders.hmacSha256KeyRef"), - "{error}" - ); - assert!(error.contains("between 32 and"), "{error}"); - } + fn reminder_secrets(keys: &[(&str, &[u8])]) -> (tempfile::TempDir, SecretResolver) { + use std::os::unix::fs::PermissionsExt; - fn reminder_destination( - purpose_urls: crate::config::ReminderPurposeUrls, - ) -> ReminderDestinationConfig { - ReminderDestinationConfig { - url: "http://127.0.0.1:1/fallback".to_owned(), - purpose_urls, - bearer_token_ref: None, - hmac_sha256_key_ref: None, + let directory = tempfile::tempdir().unwrap(); + for (name, bytes) in keys { + let path = directory.path().join(name); + std::fs::write(&path, bytes).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); } + let resolver = SecretResolver::new([SecretProvider::File], directory.path()).unwrap(); + (directory, resolver) + } + + fn reminder_destination(origin: &str) -> ReminderDestinationConfig { + serde_json::from_value(serde_json::json!({ + "url": format!("{origin}/fallback"), + "hmacSha256KeyRef": "secret:file/current" + })) + .unwrap() } #[test] - fn reminders_use_the_fallback_or_the_selected_purpose_url() { - let secrets = SecretResolver::new([SecretProvider::Environment], "/private/tmp") - .expect("the test secret resolver"); - let fallback = reminder_transport(&reminder_destination(Default::default()), &secrets) - .expect("fallback transport"); - for purpose in ["confirmation", "change", "cancellation", "reminder"] { + fn invalid_reminder_keys_name_the_path_size_newline_and_action_once() { + let mut overlong = [0x5a; 65]; + overlong[64] = b'\n'; + let mut encoded = [0x5a; 32]; + encoded[..6].copy_from_slice(b"whsec_"); + let cases: &[(&[u8], &str)] = &[ + (&[0x5a; 31], "31 bytes (trailing newline: false). Supply 32 to 64 exact key bytes."), + (&overlong, "65 bytes (trailing newline: true). Supply 32 to 64 exact key bytes."), + (&encoded, "32 bytes (trailing newline: false). Supply the exact key bytes without the whsec_ encoding."), + ]; + for (key, detail) in cases { + let (_directory, secrets) = reminder_secrets(&[("current", key)]); + let error = reminder_transport(&reminder_destination("http://127.0.0.1:1"), &secrets) + .err() + .expect("invalid signing material is refused"); assert_eq!( - fallback.target_for_purpose(purpose).unwrap().request_target, - "/fallback" + error, + format!("destinations.reminders.hmacSha256KeyRef has {detail}") ); } - assert!(fallback - .target_for_purpose("unknown-persisted-purpose") - .is_none()); - - let selected = reminder_transport( - &reminder_destination(crate::config::ReminderPurposeUrls { - confirmation: Some("http://127.0.0.1:1/confirmed".to_owned()), - change: Some("http://127.0.0.1:1/rescheduled".to_owned()), - cancellation: Some("http://127.0.0.1:1/cancelled".to_owned()), - reminder: Some("http://127.0.0.1:1/reminder".to_owned()), - }), - &secrets, - ) - .expect("purpose-specific transport"); - for (purpose, path) in [ - ("confirmation", "/confirmed"), - ("change", "/rescheduled"), - ("cancellation", "/cancelled"), - ("reminder", "/reminder"), + } + + #[test] + fn unavailable_and_empty_reminder_keys_include_the_secret_reason_and_action() { + use registry_platform_config::SecretError; + + for (keys, reason) in [ + (&[][..], SecretError::Unavailable), + (&[("current", &[][..])][..], SecretError::InvalidValue), ] { + let (_directory, secrets) = reminder_secrets(keys); + let error = reminder_transport(&reminder_destination("http://127.0.0.1:1"), &secrets) + .err() + .expect("unavailable or empty signing material is refused"); assert_eq!( - selected.target_for_purpose(purpose).unwrap().request_target, - path + error, + format!( + "destinations.reminders.hmacSha256KeyRef could not be resolved: {reason}. {}", + reason.suggested_action() + ) ); } } #[test] - fn reminder_signature_binds_the_selected_exact_target() { - use registry_platform_crypto::delivery_signature::{verify_v1, VerificationError}; - - const KEY: &[u8] = b"0123456789abcdef0123456789abcdef"; - let secrets = SecretResolver::new([SecretProvider::Environment], "/private/tmp") - .expect("the test secret resolver"); - let transport = reminder_transport( - &reminder_destination(crate::config::ReminderPurposeUrls { - confirmation: Some("http://127.0.0.1:1/alpha/../confirmed".to_owned()), - ..Default::default() - }), - &secrets, - ) - .expect("purpose-specific transport"); - let target = transport - .target_for_purpose("confirmation") - .expect("the typed confirmation target"); - assert_eq!(target.request_target, "/confirmed"); - let row = intent("confirmation"); - let event = reminder_event("registry-north", &row).unwrap(); - let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_788_048_001); - let delivery_time = "2026-08-30T00:00:01Z".to_owned(); - let signed = sign_reminder_event(KEY, &event, 1, 1, &target.request_target, delivery_time) - .expect("the selected target is signed"); - verify_v1( - KEY, - signed.fields(&event, &target.request_target), - &signed.signature, - now, - Duration::from_secs(5), - ) - .expect("the selected exact target verifies"); - assert_eq!( - verify_v1( - KEY, - signed.fields(&event, "/fallback"), - &signed.signature, - now, - Duration::from_secs(5), + fn a_reminder_key_equal_to_an_activated_observer_key_is_refused_after_its_file_is_removed() { + use registry_platform_hooks::delivery::activate_url_hook_destinations; + + for (observer_current, observer_previous, duplicate_member) in [ + (TEST_CURRENT, None, "hmacSha256KeyRef"), + ( + TEST_PREVIOUS, + Some("secret:file/observer-previous"), + "previousHmacSha256KeyRef", ), - Err(VerificationError::InvalidSignature) - ); + ] { + let (directory, secrets) = reminder_secrets(&[ + ("current", &TEST_CURRENT), + ("observer", &observer_current), + ("observer-previous", &TEST_CURRENT), + ]); + let transport = + reminder_transport(&reminder_destination("http://127.0.0.1:1"), &secrets).unwrap(); + let mut hook = serde_json::json!({ + "url": "https://events.example.test/hook", + "hmacSha256KeyRef": "secret:file/observer" + }); + if let Some(previous) = observer_previous { + hook["previousHmacSha256KeyRef"] = serde_json::json!(previous); + } + let hooks = + serde_json::from_value(serde_json::json!({"appointment-events": hook})).unwrap(); + let activated = activate_url_hook_destinations("test", &hooks, &secrets, 1024).unwrap(); + std::fs::remove_file(directory.path().join("observer")).unwrap(); + std::fs::remove_file(directory.path().join("observer-previous")).unwrap(); + let error = check_delivery_keys(&transport, &activated).unwrap_err(); + let first = "destinations.reminders.hmacSha256KeyRef"; + let second = format!("destinations.hooks.appointment-events.{duplicate_member}"); + assert_eq!(error, format!( + "{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there." + )); + } } #[test] - fn reminder_delivery_times_are_canonical_for_every_millisecond_shape() { - use registry_platform_crypto::delivery_signature::verify_v1; + fn a_reminder_previous_key_equal_to_its_current_key_names_both_paths_and_rotation() { + let (_directory, secrets) = reminder_secrets(&[("current", &TEST_CURRENT)]); + let mut destination = reminder_destination("http://127.0.0.1:1"); + destination.previous_hmac_sha256_key_ref = Some(destination.hmac_sha256_key_ref.clone()); + let error = reminder_transport(&destination, &secrets).err().unwrap(); + let previous = "destinations.reminders.previousHmacSha256KeyRef"; + let current = "destinations.reminders.hmacSha256KeyRef"; + assert_eq!(error, format!( + "{previous} holds the same bytes as {current}. To rotate, write 32 new random bytes to the secret {current} references and keep the old bytes behind {previous}." + )); + } - const KEY: &[u8] = b"0123456789abcdef0123456789abcdef"; - let row = intent("reminder"); - let event = reminder_event("registry-north", &row).unwrap(); - for (input, expected) in [ - ("2026-08-30T00:00:01.000Z", "2026-08-30T00:00:01Z"), - ("2026-08-30T00:00:01.010Z", "2026-08-30T00:00:01.01Z"), - ("2026-08-30T00:00:01.100Z", "2026-08-30T00:00:01.1Z"), - ("2026-08-30T00:00:01.120Z", "2026-08-30T00:00:01.12Z"), - ("2026-08-30T00:00:01.123Z", "2026-08-30T00:00:01.123Z"), - ] { - let moment = DateTime::parse_from_rfc3339(input) + const TEST_CURRENT: [u8; 32] = [0x5a; 32]; + const TEST_PURPOSE: [u8; 32] = [0x5b; 32]; + const TEST_PREVIOUS: [u8; 32] = [0x5c; 32]; + + async fn capture_reminders( + purposes: &[&str], + times: &[SystemTime], + ) -> (OutboxRow, Vec) { + use wiremock::{matchers::method, Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(202)) + .mount(&server) + .await; + let (_directory, secrets) = reminder_secrets(&[ + ("current", &TEST_CURRENT), + ("purpose", &TEST_PURPOSE), + ("previous", &TEST_PREVIOUS), + ]); + let mut destination = reminder_destination(&server.uri()); + destination.previous_hmac_sha256_key_ref = + Some(SecretReference::parse("secret:file/previous").unwrap()); + destination.purposes.confirmation = Some( + serde_json::from_value(serde_json::json!({ + "url": format!("{}/confirmed", server.uri()), + "hmacSha256KeyRef": "secret:file/purpose" + })) + .unwrap(), + ); + let transport = reminder_transport(&destination, &secrets).unwrap(); + assert!(transport.target_for_purpose("unknown").is_none()); + let row = intent("confirmation"); + for (&purpose, &time) in purposes.iter().zip(times) { + let request = transport + .target_for_purpose(purpose) .unwrap() - .with_timezone(&Utc); - let delivery_time = reminder_delivery_time(SystemTime::from(moment)).unwrap(); - let signed = - sign_reminder_event(KEY, &event, 1, 1, "/reminder", delivery_time.clone()).unwrap(); - let now = SystemTime::UNIX_EPOCH - + Duration::from_secs(u64::try_from(moment.timestamp()).unwrap()) - + Duration::from_nanos(u64::from(moment.timestamp_subsec_nanos())); - verify_v1( - KEY, - signed.fields(&event, "/reminder"), - &signed.signature, - now, - Duration::ZERO, - ) - .expect("the sender emits a delivery time the shared verifier accepts"); - assert_eq!(delivery_time, expected); + .render(reminder_event("registry-north", &row).unwrap(), time) + .unwrap(); + transport + .policy + .send(request, Duration::from_secs(5)) + .await + .unwrap(); } + (row, server.received_requests().await.unwrap()) } - #[test] - fn reminder_idempotency_is_stable_across_rendered_retry_attempts() { - const KEY: &[u8] = b"0123456789abcdef0123456789abcdef"; - let row = intent("reminder"); - let event = reminder_event("registry-north", &row).unwrap(); - let first = sign_reminder_event( - KEY, - &event, - 1, - 1, - "/reminder", - "2026-08-30T00:00:01Z".to_owned(), + fn captured_header<'a>(request: &'a wiremock::Request, name: &str) -> &'a str { + request.headers[name].to_str().unwrap() + } + + fn signed_content( + request: &wiremock::Request, + ) -> registry_platform_crypto::delivery_signature::SignedContent<'_> { + registry_platform_crypto::delivery_signature::SignedContent { + id: captured_header(request, "webhook-id"), + timestamp: captured_header(request, "webhook-timestamp"), + signature: captured_header(request, "webhook-signature"), + body: &request.body, + } + } + + #[tokio::test] + async fn reminders_use_the_fallback_or_the_selected_purpose_url() { + let (_, requests) = capture_reminders( + &["confirmation", "change", "cancellation", "reminder"], + &[SystemTime::UNIX_EPOCH; 4], ) - .unwrap(); - let retry = sign_reminder_event( - KEY, - &event, - 1, - 2, - "/reminder", - "2026-08-30T00:00:31Z".to_owned(), + .await; + assert_eq!( + requests + .iter() + .map(|request| request.url.path()) + .collect::>(), + ["/confirmed", "/fallback", "/fallback", "/fallback"] + ); + } + + #[tokio::test] + async fn a_reminder_purpose_signs_with_its_own_key() { + use registry_platform_crypto::delivery_signature::verify_authenticity; + + let (_, requests) = capture_reminders(&["confirmation"], &[SystemTime::UNIX_EPOCH]).await; + let keys = |key: &[u8]| DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap(); + verify_authenticity(&keys(&TEST_PURPOSE), signed_content(&requests[0])).unwrap(); + assert!(verify_authenticity(&keys(&TEST_CURRENT), signed_content(&requests[0])).is_err()); + } + + #[tokio::test] + async fn reminders_use_the_outbox_id_as_webhook_id() { + let (row, requests) = capture_reminders( + &["confirmation"; 2], + &[ + SystemTime::UNIX_EPOCH, + SystemTime::UNIX_EPOCH + Duration::from_secs(30), + ], ) - .unwrap(); - assert_eq!(first.idempotency_key, retry.idempotency_key); - assert_ne!(first.attempt, retry.attempt); - assert_ne!(first.delivery_time, retry.delivery_time); - assert_ne!(first.signature, retry.signature); + .await; + for request in &requests { + let envelope: Value = serde_json::from_slice(&request.body).unwrap(); + assert_eq!( + captured_header(request, "webhook-id"), + row.outbox_id.to_string() + ); + assert_eq!(envelope["id"], row.outbox_id.to_string()); + } + assert_ne!( + captured_header(&requests[0], "webhook-signature"), + captured_header(&requests[1], "webhook-signature") + ); + } + + #[tokio::test] + async fn reminder_rendering_converts_the_given_instant_to_unix_seconds() { + let lease = SystemTime::UNIX_EPOCH + Duration::from_millis(1_788_048_001_123); + let (_, requests) = capture_reminders(&["reminder"], &[lease]).await; + assert_eq!( + captured_header(&requests[0], "webhook-timestamp"), + "1788048001" + ); + } + + #[tokio::test] + async fn a_previous_reminder_key_adds_a_second_entry_after_the_current_one() { + let (_, requests) = capture_reminders(&["reminder"], &[SystemTime::UNIX_EPOCH]).await; + let content = signed_content(&requests[0]); + let signature = |key: &[u8]| { + let keys = DeliveryKeys::new(DeliveryKey::new(key).unwrap(), None).unwrap(); + sign(&keys, content.id, 0, content.body).unwrap() + }; + assert_eq!( + content.signature, + format!("{} {}", signature(&TEST_CURRENT), signature(&TEST_PREVIOUS)) + ); } #[test] diff --git a/crates/registry-scheduling/src/runtime/intents.rs b/crates/registry-scheduling/src/runtime/intents.rs index 678188ad0f..d2acf84a20 100644 --- a/crates/registry-scheduling/src/runtime/intents.rs +++ b/crates/registry-scheduling/src/runtime/intents.rs @@ -34,15 +34,9 @@ use registry_platform_dispatch::{ AttemptTimeoutBound, DispatchError, FailureCode, JobPolicy, RetrySchedule, SendOutcome, Sent, UncertainOutcome, }; -use registry_platform_httputil::destination::{ - DestinationAuthorizationValue, DestinationRequestError, -}; use tokio_postgres::{Row, Transaction}; -use super::{ - delivery_of, reminder_delivery_time, reminder_event, sign_reminder_event, Delivery, - ReminderTransport, -}; +use super::{delivery_of, reminder_event, Delivery, ReminderTransport}; use crate::store::{OutboxRow, PostgresStore, StoreError}; /// The delivery-intent outbox table. @@ -508,58 +502,7 @@ impl DispatchTransport for IntentTransport { return refusal(EVENT_UNRENDERABLE); } }; - let authorization = destination - .bearer - .as_ref() - .map(|secret| DestinationAuthorizationValue::bearer(secret.expose_secret().to_vec())) - .transpose(); - let request = match (authorization, &destination.hmac_sha256_key) { - (Ok(authorization), None) => { - target - .template - .render(&[], &[], authorization, Some(event.body)) - } - // A signed delivery binds the event, this lease's generation and - // attempt, the database clock the lease was taken at, and the - // selected purpose's exact request target. - (Ok(authorization), Some(key)) => reminder_delivery_time(job.attempt_started_at) - .map_err(|_| DestinationRequestError::InvalidAuthorization) - .and_then(|delivery_time| { - sign_reminder_event( - key.expose_secret(), - &event, - job.generation, - job.attempt, - &target.request_target, - delivery_time, - ) - .map_err(|_| DestinationRequestError::InvalidAuthorization) - }) - .and_then(|signed| { - target.template.render( - &[], - &[ - b"application/json", - b"application/json", - b"1.0", - event.id.as_bytes(), - event.source.as_bytes(), - event.event_type.as_bytes(), - event.time.as_bytes(), - event.data_schema.as_bytes(), - signed.generation.as_bytes(), - signed.attempt.as_bytes(), - signed.delivery_time.as_bytes(), - signed.idempotency_key.as_bytes(), - signed.signature.as_bytes(), - ], - authorization, - Some(event.body), - ) - }), - (Err(_), _) => Err(DestinationRequestError::InvalidAuthorization), - }; - let request = match request { + let request = match target.render(event, job.attempt_started_at) { Ok(request) => request, Err(error) => { tracing::error!( diff --git a/crates/registry-scheduling/src/schema.rs b/crates/registry-scheduling/src/schema.rs index 4edbe8a3ef..c745bc3008 100644 --- a/crates/registry-scheduling/src/schema.rs +++ b/crates/registry-scheduling/src/schema.rs @@ -271,15 +271,18 @@ mod tests { "DatabaseConfig.{property} must be a secret reference" ); } - for (definition, property) in [ - ("ReminderDestinationConfig", "bearerTokenRef"), - ("UrlHookDestinationConfig", "hmacSha256KeyRef"), + for definition in [ + "ReminderDestinationConfig", + "ReminderPurposeDestinationConfig", + "UrlHookDestinationConfig", ] { - assert_eq!( - document["$defs"][definition]["properties"][property]["$ref"], - "#/$defs/SecretReference", - "{definition}.{property} must be a secret reference" - ); + for property in ["hmacSha256KeyRef", "previousHmacSha256KeyRef"] { + assert_eq!( + document["$defs"][definition]["properties"][property]["$ref"], + "#/$defs/SecretReference", + "{definition}.{property} must be a secret reference" + ); + } } assert_eq!( document["$defs"]["SecretProvidersConfig"]["anyOf"], diff --git a/crates/registry-scheduling/src/service.rs b/crates/registry-scheduling/src/service.rs index d48977b43c..b1a78b56dc 100644 --- a/crates/registry-scheduling/src/service.rs +++ b/crates/registry-scheduling/src/service.rs @@ -19,6 +19,7 @@ use chrono::{DateTime, TimeDelta, Utc}; use registry_platform_audit::{ AuditKeyHasher, AuditRequest, AuthorizationAuditEvent, AuthorizationOutcome, }; +use registry_platform_authcommon::FailedCheck; use registry_platform_calendar::CalendarInterval; use registry_platform_canonical_json::canonicalize_json; use registry_platform_oidc::{ @@ -165,16 +166,41 @@ pub enum CommitmentAnswer { Replay { status_code: u16, receipt: Value }, } +pub use crate::refusal::RefusalCode; + #[derive(Debug, thiserror::Error)] pub enum ServiceError { - /// The refusal the caller sees, in its public projection. Every service - /// failure, internal bound, and cursor verdict lands here too: the edge - /// renders one problem shape. - #[error("the request was refused: {}", .0.code())] + /// The answer the caller sees, in its public projection, for every + /// service failure, internal bound, and cursor verdict that is not a + /// refusal of authority: the edge renders one problem shape. A code for + /// which `RefusalCode::of` answers `Some` is built as `Refused`. + #[error("the request was answered: {}", .0.code())] Problem(ProblemCode), + /// A refusal of authority, with the check it failed. + #[error("the request was refused: {}", .code.problem().code())] + Refused { + code: RefusalCode, + check: FailedCheck, + }, } impl ServiceError { + /// The refusal that conceals a target the caller may not see: the row is + /// absent or foreign, and the answer does not say which. + fn not_visible() -> Self { + Self::Refused { + code: RefusalCode::OperationNotAuthorized, + check: FailedCheck::Visibility, + } + } + + fn operation_refused(check: FailedCheck) -> Self { + Self::Refused { + code: RefusalCode::OperationNotAuthorized, + check, + } + } + fn internal(reason: &'static str) -> Self { tracing::error!(reason, "the Scheduling service hit an internal bound"); Self::Problem(ProblemCode::ServiceUnavailable) @@ -1103,7 +1129,7 @@ impl SchedulingService { let hold = self .hold(hold_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&hold, now).await?; let grant = self .require_permission(caller, &offering, HOLD_RELEASE_ACTION) @@ -1126,7 +1152,7 @@ impl SchedulingService { self.commitment(caller, &actor, &grant, &release_key, &request_hash, now, 0)?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, HOLD_RELEASE_ACTION, @@ -1193,7 +1219,7 @@ impl SchedulingService { let hold = self .hold(hold_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.policy.offering(&hold.offering).ok_or_else(|| { ServiceError::internal("a committed hold names no offering in the policy") })?; @@ -1249,7 +1275,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request(caller, &grant, operation, now, assisted) + .audit_named_request(caller, &grant, operation, now, assisted) .await?; let outcome = match (&supply, confirmation_request.as_ref()) { (ResolvedRequestSupply::Exact(bundle), Some(request)) => { @@ -1566,19 +1592,31 @@ impl SchedulingService { let claim = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; match claim.source_manager.as_ref() { None if admission == DetailAdmission::ReadsScope && claim.is_owned_by(&caller.issuer, &caller.subject) => {} None if claim.owner.is_some() => { let offering = self.claim_offering(&claim, now).await?; - let grant = self + let grant = match self .require_permission(caller, &offering, APPOINTMENT_READ_ACTION) - .await?; + .await + { + // A reads-scope caller carries no task grant, and the + // appointment is another caller's: that is an ownership + // refusal, not a missing grant. + Err(ServiceError::Refused { + check: FailedCheck::TaskGrantMissing, + .. + }) if admission == DetailAdmission::ReadsScope => { + return Err(ServiceError::operation_refused(FailedCheck::Ownership)); + } + other => other?, + }; self.require_current_task_grant(caller, &grant, APPOINTMENT_READ_ACTION, now, true) .await?; } - None => return Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)), + None => return Err(ServiceError::not_visible()), Some(expected) => { let offering = self.claim_offering(&claim, now).await?; let grant = self @@ -1784,7 +1822,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.policy.offering(&appointment.offering).ok_or_else(|| { ServiceError::internal("a committed appointment names no offering in the policy") })?; @@ -1837,7 +1875,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, APPOINTMENT_RESCHEDULE_ACTION, @@ -1914,7 +1952,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&appointment, now).await?; let grant = self .require_permission(caller, &offering, ATTENDANCE_RECORD_ACTION) @@ -1946,7 +1984,7 @@ impl SchedulingService { 0, )?; let (correlation, _request) = self - .audit_request(caller, &grant, ATTENDANCE_RECORD_ACTION, now, false) + .audit_named_request(caller, &grant, ATTENDANCE_RECORD_ACTION, now, false) .await?; let outcome = self .store @@ -1992,7 +2030,7 @@ impl SchedulingService { let appointment = self .booking(appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let offering = self.claim_offering(&appointment, now).await?; let grant = self .require_permission(caller, &offering, APPOINTMENT_CANCEL_ACTION) @@ -2027,7 +2065,7 @@ impl SchedulingService { )?; commitment.source_manager = source_manager; let (correlation, _request) = self - .audit_request( + .audit_named_request( caller, &grant, APPOINTMENT_CANCEL_ACTION, @@ -2079,7 +2117,7 @@ impl SchedulingService { let limit = page_limit(limit); self.owned_booking(caller, appointment_id) .await? - .ok_or(ServiceError::Problem(ProblemCode::OperationNotAuthorized))?; + .ok_or_else(ServiceError::not_visible)?; let context = format!("history:{appointment_id}"); let position = self.resolve_position(cursor, &context, now).await?; let before = match position { @@ -2290,7 +2328,12 @@ impl SchedulingService { /// grant reaches would leave no audit entry. Each refusal is one `response` /// entry with a correlation of its own. What the audit gains is the /// attribution: the answer stays the same closed code, naming neither - /// the bound that failed nor whether a grant was carried at all. + /// the bound that failed nor whether a grant was carried at all. The one + /// later answer that does say a grant was carried is a current-grant + /// refusal for too much lifetime left, and it is given only after this + /// check has passed and only on a route that names no existing hold or + /// appointment, so it tells a caller nothing about which services and + /// locations a grant reaches or which ids exist. async fn require_permission( &self, caller: &Caller, @@ -2303,7 +2346,9 @@ impl SchedulingService { grantless_refusal_record(&self.hasher, &self.scheduling_id, caller, action), ) .await?; - return Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)); + return Err(ServiceError::operation_refused( + FailedCheck::TaskGrantMissing, + )); }; let allowed = grant .bounds() @@ -2334,7 +2379,7 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(ServiceError::operation_refused(FailedCheck::TaskGrantScope)) } } @@ -2376,7 +2421,7 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(ServiceError::operation_refused(FailedCheck::Ownership)) } /// Write one refusal, or one commitment nothing decided, as the @@ -2418,7 +2463,7 @@ impl SchedulingService { ServiceError::internal("the task-grant clock observation is not representable") })?; let verdict = if online_required && self.task_grant_status.is_none() { - Err(TaskGrantError::Refused) + GrantVerdict::Refused } else { task_grant_verdict( self.task_grant_status.as_deref(), @@ -2429,8 +2474,8 @@ impl SchedulingService { .await }; match verdict { - Ok(()) => Ok(()), - Err(TaskGrantError::Refused) => { + GrantVerdict::Current => Ok(()), + refused @ (GrantVerdict::Refused | GrantVerdict::LifetimeTooLong) => { self.record_refusal( Uuid::new_v4(), audit_record( @@ -2444,19 +2489,60 @@ impl SchedulingService { ), ) .await?; - Err(ServiceError::Problem(ProblemCode::OperationNotAuthorized)) + Err(if refused == GrantVerdict::LifetimeTooLong { + ServiceError::Refused { + code: RefusalCode::GrantLifetimeTooLong, + check: FailedCheck::TaskGrantLifetime, + } + } else { + // A deployment that asks a status authority, or one that + // listed none for an operation that needs a current + // status, refuses on status. The offline path refuses an + // expired grant. + ServiceError::operation_refused( + if online_required || self.task_grant_status.is_some() { + FailedCheck::TaskGrantStatus + } else { + FailedCheck::TaskGrantExpired + }, + ) + }) } - Err(TaskGrantError::Unavailable) => { + GrantVerdict::Unavailable => { tracing::warn!("the task-grant authority could not establish current status"); Err(ServiceError::Problem(ProblemCode::ServiceUnavailable)) } - Err(TaskGrantError::Configuration) => { + GrantVerdict::Configuration => { tracing::error!("the activated task-grant status registry became unusable"); Err(ServiceError::Problem(ProblemCode::ServiceUnavailable)) } } } + /// `audit_request` for a route that names an existing hold or + /// appointment. A grant with too much lifetime left answers + /// `operation.not-authorized` there, as an unknown id does, so the answer + /// never says whether the id exists (SCHEDULING-DEC-01). The refusal + /// still counts under `task-grant-lifetime`. + async fn audit_named_request( + &self, + caller: &Caller, + grant: &GrantClaims, + operation: &str, + now: DateTime, + online_required: bool, + ) -> Result<(Uuid, AuditRequest), ServiceError> { + self.audit_request(caller, grant, operation, now, online_required) + .await + .map_err(|error| match error { + ServiceError::Refused { + code: RefusalCode::GrantLifetimeTooLong, + check, + } => ServiceError::operation_refused(check), + other => other, + }) + } + /// Append the `request` entry of one commitment and return the /// correlation its `response` entry will carry, with the handle that owes /// it. It names the caller, the grant, and the operation the capacity @@ -2826,7 +2912,9 @@ impl SchedulingService { CommitError::KeyReused | CommitError::KeyExpired => { Unanswered::Unfinished(key_refusal_reason(&error)) } - CommitError::Unauthorized => Unanswered::Denied("authorization.refused"), + CommitError::Unauthorized + | CommitError::NotAttendable + | CommitError::GrantLapsed => Unanswered::Denied("authorization.refused"), CommitError::Refused(_) | CommitError::HoldCeiling | CommitError::RevisionMismatch @@ -2926,7 +3014,23 @@ impl SchedulingService { .map(|record| unfinished_record(record, reason)), }; self.record_refusal(correlation, record).await?; - Err(ServiceError::Problem(problem)) + Err(match RefusalCode::of(problem) { + // `CommitError::Unauthorized`, `CommitError::NotAttendable` + // and `CommitError::GrantLapsed` are the only commit + // failures that refuse authority: the target is not this + // caller's to change, the appointment takes no attendance + // in its current state, or the grant or its access token + // lapsed inside the transaction. + Some(code) => ServiceError::Refused { + code, + check: match error { + CommitError::GrantLapsed => FailedCheck::TaskGrantExpired, + CommitError::NotAttendable => FailedCheck::Visibility, + _ => FailedCheck::Ownership, + }, + }, + None => ServiceError::Problem(problem), + }) } } } @@ -2977,29 +3081,56 @@ impl SchedulingService { } } +/// The outcome of deciding whether a task grant is current. +#[derive(Debug, PartialEq, Eq)] +enum GrantVerdict { + Current, + /// Expired, inactive, unlisted, or unbound. + Refused, + /// Unexpired on the offline path, with more than + /// `OFFLINE_TASK_GRANT_REMAINING_SECONDS` left. + LifetimeTooLong, + Unavailable, + Configuration, +} + +impl From> for GrantVerdict { + fn from(verdict: Result<(), TaskGrantError>) -> Self { + match verdict { + Ok(()) => Self::Current, + Err(TaskGrantError::Refused) => Self::Refused, + // A development-posture status peer proves no grant state, so it is + // treated like an unreachable authority. + Err(TaskGrantError::Unavailable | TaskGrantError::DevelopmentPeer) => Self::Unavailable, + Err(TaskGrantError::Configuration) => Self::Configuration, + } + } +} + /// Decide whether one verified task grant is current at `now`, in Unix /// seconds. Listed status authorities are authoritative for every source: a /// grant without the signed subjects its status binding needs, or from a /// source no authority is listed for, is refused and never reaches the /// offline path. Without them, the offline path accepts a grant only while it -/// is unexpired with at most fifteen minutes left, and asks no authority. +/// is unexpired with at most fifteen minutes left, and asks no authority. An +/// unexpired grant with more left is `LifetimeTooLong`, distinct from `Refused` +/// so the caller learns to present a shorter-lived grant. async fn task_grant_verdict( status: Option<&TaskGrantStatusRegistry>, subjects: Option>, grant: &GrantClaims, now: u64, -) -> Result<(), TaskGrantError> { +) -> GrantVerdict { match status { Some(status) => match subjects .and_then(|subjects| TaskGrantStatusBinding::from_verified(grant, subjects).ok()) { - Some(binding) => status.check(&binding).await, - None => Err(TaskGrantError::Refused), + Some(binding) => status.check(&binding).await.into(), + None => GrantVerdict::Refused, }, - None if grant.exp() > now && grant.exp() - now <= OFFLINE_TASK_GRANT_REMAINING_SECONDS => { - Ok(()) - } - None => Err(TaskGrantError::Refused), + None if grant.exp() <= now => GrantVerdict::Refused, + None if grant.exp() - now <= OFFLINE_TASK_GRANT_REMAINING_SECONDS => GrantVerdict::Current, + None => GrantVerdict::LifetimeTooLong, } } @@ -3751,7 +3882,9 @@ fn problem_of(error: &CommitError) -> ProblemCode { CommitError::KeyReused => ProblemCode::IdempotencyKeyReused, CommitError::KeyExpired => ProblemCode::IdempotencyExpired, CommitError::HoldCeiling => ProblemCode::CapacityExhausted, - CommitError::Unauthorized => ProblemCode::OperationNotAuthorized, + CommitError::Unauthorized | CommitError::NotAttendable | CommitError::GrantLapsed => { + ProblemCode::OperationNotAuthorized + } CommitError::RevisionMismatch => ProblemCode::RevisionMismatch, CommitError::ObservationInFuture => ProblemCode::RequestUnprocessable, CommitError::CutoffPassed => ProblemCode::CancellationCutoffPassed, @@ -3766,8 +3899,9 @@ fn problem_of(error: &CommitError) -> ProblemCode { /// The decision a stored receipt carries, as its replay's `response` entry /// records it. A success receipt was allowed. A refusal receipt was written /// only for a decision the ledger took, so it keeps the reason its first -/// answer recorded: a lapsed grant is `authorization.refused`, every other -/// ledger refusal `authorization.profile`. +/// answer recorded: an `operation.not-authorized` receipt (a lapsed grant, or +/// a target the caller does not manage) is `authorization.refused`, every +/// other ledger refusal `authorization.profile`. fn replayed_decision(status_code: u16, receipt: &Value) -> (AuthorizationOutcome, &'static str) { if status_code < 400 { return (AuthorizationOutcome::Allowed, "authorization.allowed"); @@ -4462,6 +4596,14 @@ mod tests { problem_of(&CommitError::Unauthorized), ProblemCode::OperationNotAuthorized ); + assert_eq!( + problem_of(&CommitError::NotAttendable), + ProblemCode::OperationNotAuthorized + ); + assert_eq!( + problem_of(&CommitError::GrantLapsed), + ProblemCode::OperationNotAuthorized + ); assert_eq!( problem_of(&CommitError::CutoffPassed), ProblemCode::CancellationCutoffPassed @@ -4751,7 +4893,7 @@ mod tests { "statusResource": "urn:casework:test" })) .expect("the status authority configuration"); - let registry = TaskGrantStatusRegistry::activate( + let registry = TaskGrantStatusRegistry::activate_without_peer_policy( &crate::config::task_grant_status_endpoints(&[status]), STATUS_RESOURCE, &secrets, @@ -4771,23 +4913,23 @@ mod tests { } #[tokio::test] - async fn the_offline_path_accepts_only_an_unexpired_grant_with_at_most_fifteen_minutes_left() { + async fn the_offline_path_tells_a_grant_with_too_much_lifetime_from_an_expired_one() { let now = u64::try_from(at(9, 0).timestamp()).expect("a representable instant"); for (case, expires_at, expected) in [ - ("one second left", now + 1, Ok(())), - ("exactly fifteen minutes left", now + 900, Ok(())), + ("one second left", now + 1, GrantVerdict::Current), ( - "one second more than fifteen minutes left", - now + 901, - Err(TaskGrantError::Refused), + "exactly fifteen minutes left", + now + 900, + GrantVerdict::Current, ), - ("an hour left", now + 3_600, Err(TaskGrantError::Refused)), ( - "expiring at request entry", - now, - Err(TaskGrantError::Refused), + "one second more than fifteen minutes left", + now + 901, + GrantVerdict::LifetimeTooLong, ), - ("expired", now - 60, Err(TaskGrantError::Refused)), + ("a day left", now + 86_400, GrantVerdict::LifetimeTooLong), + ("expiring at request entry", now, GrantVerdict::Refused), + ("expired", now - 60, GrantVerdict::Refused), ] { let grant = verified_grant(STATUS_SOURCE, expires_at, now - 600); for subjects in [None, Some(status_subjects())] { @@ -4813,13 +4955,13 @@ mod tests { let unlisted = verified_grant("https://other-authority.test", now + 600, now); assert_eq!( task_grant_verdict(Some(®istry), Some(status_subjects()), &unlisted, now).await, - Err(TaskGrantError::Refused), + GrantVerdict::Refused, "an unlisted source is refused" ); let unbound = verified_grant(STATUS_SOURCE, now + 600, now); assert_eq!( task_grant_verdict(Some(®istry), None, &unbound, now).await, - Err(TaskGrantError::Refused), + GrantVerdict::Refused, "a grant without signed subjects is refused" ); assert_eq!( @@ -4836,9 +4978,9 @@ mod tests { let mut active = active_answer(&grant); active["grant"]["subjects"] = json!({}); for (response, expected) in [ - (active, Ok(())), - (active_answer(&grant), Err(TaskGrantError::Refused)), - (json!({"active":false}), Err(TaskGrantError::Refused)), + (active, GrantVerdict::Current), + (active_answer(&grant), GrantVerdict::Refused), + (json!({"active":false}), GrantVerdict::Refused), ] { let (server, registry) = listed_authority(wiremock::ResponseTemplate::new(200).set_body_json(response)) @@ -4855,6 +4997,31 @@ mod tests { } } + #[tokio::test] + async fn a_listed_authority_never_answers_lifetime_too_long() { + let now = unix_now(); + let grant = verified_grant(STATUS_SOURCE, now + 86_400, now); + for (case, response, expected) in [ + ( + "active", + wiremock::ResponseTemplate::new(200).set_body_json(active_answer(&grant)), + GrantVerdict::Current, + ), + ( + "inactive", + wiremock::ResponseTemplate::new(200).set_body_json(json!({"active": false})), + GrantVerdict::Refused, + ), + ] { + let (_server, registry) = listed_authority(response).await; + assert_eq!( + task_grant_verdict(Some(®istry), Some(status_subjects()), &grant, now).await, + expected, + "{case}" + ); + } + } + #[tokio::test] async fn a_listed_authority_answer_decides_the_grant() { let now = unix_now(); @@ -4864,17 +5031,17 @@ mod tests { ( "active", wiremock::ResponseTemplate::new(200).set_body_json(active_answer(&grant)), - Ok(()), + GrantVerdict::Current, ), ( "inactive", wiremock::ResponseTemplate::new(200).set_body_json(json!({"active": false})), - Err(TaskGrantError::Refused), + GrantVerdict::Refused, ), ( "unavailable", wiremock::ResponseTemplate::new(503), - Err(TaskGrantError::Unavailable), + GrantVerdict::Unavailable, ), ] { let (server, registry) = listed_authority(response).await; diff --git a/crates/registry-scheduling/src/source_busy.rs b/crates/registry-scheduling/src/source_busy.rs index 0c68cc8e00..488ab9f85d 100644 --- a/crates/registry-scheduling/src/source_busy.rs +++ b/crates/registry-scheduling/src/source_busy.rs @@ -13,6 +13,7 @@ use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, TimeDelta, Utc}; use registry_platform_audit::AuditKeyHasher; +use registry_platform_authcommon::FailedCheck; use registry_platform_canonical_json::canonicalize_json; use registry_scheduling_core::{valid_identifier, MAXIMUM_HORIZON_DAYS}; pub use registry_scheduling_core::{ @@ -209,6 +210,21 @@ impl std::fmt::Debug for AuthorizedBusySource { pub enum BusyAuthorizationError { #[error("the busy import profile is invalid or not authorized")] Profile, + /// The caller is not admitted by the profile it selected, for the check + /// it carries. + #[error("the caller is not admitted by a busy import profile")] + NotAdmitted(FailedCheck), +} + +impl BusyAuthorizationError { + /// The check an operator sees when this refusal answers a request. + #[must_use] + pub fn failed_check(self) -> FailedCheck { + match self { + Self::Profile => FailedCheck::AccessProfile, + Self::NotAdmitted(check) => check, + } + } } /// Validate all source profiles together. Source ids are unique. Profiles may @@ -259,13 +275,21 @@ pub fn authorize_busy_source( identity: BusySourceIdentity, ) -> Result { let (profile_id, profile) = match profile_selector { - Some(profile_id) => profiles - .get_key_value(profile_id) - .ok_or(BusyAuthorizationError::Profile)?, - None => return Err(BusyAuthorizationError::Profile), + Some(profile_id) => { + profiles + .get_key_value(profile_id) + .ok_or(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile, + ))? + } + None => { + return Err(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile, + )) + } }; if !scopes.iter().any(|scope| scope == &profile.scope) { - return Err(BusyAuthorizationError::Profile); + return Err(BusyAuthorizationError::NotAdmitted(FailedCheck::Scope)); } let profile_value = serde_json::to_value((profile_id, profile)).map_err(|_| BusyAuthorizationError::Profile)?; @@ -520,7 +544,9 @@ mod tests { None, identity(), ), - Err(BusyAuthorizationError::Profile) + Err(BusyAuthorizationError::NotAdmitted( + FailedCheck::AccessProfile + )) ); let authorized = authorize_busy_source( &values, diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index 5d57329635..995165e30c 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -90,10 +90,12 @@ pub use resource_availability::{ResourceSupplyImpact, ResourceSupplyImpacts}; pub use source_busy::{resource_interval_is_available, BusyStoreError}; const SCHEDULING_MIGRATION: &str = include_str!("../migrations/0200_scheduling.sql"); +const ACTIVATION_POSTURE_MIGRATION: &str = + include_str!("../migrations/0201_activation_posture.sql"); /// Every schema version, in the order it is applied. The baseline is /// version [`BASELINE_SCHEMA_VERSION`], above every version an earlier /// release applied; each later migration takes the next number. -const SCHEMA_VERSIONS: [i64; 1] = [200]; +const SCHEMA_VERSIONS: [i64; 2] = [200, 201]; /// The baseline schema version. A ledger holding any version below it was /// left by an earlier pre-1.0 release, which this release refuses by name: /// version 100 is the v0.42.0 and v0.43.0 baseline, whose outbox and hook @@ -896,8 +898,18 @@ pub enum CommitError { KeyExpired, #[error("the caller holds more active holds than the hold policy allows")] HoldCeiling, - #[error("the task grant lapsed before the commitment")] + /// The target is not the caller's to change: another caller holds it, or + /// its source manager differs. + #[error("the target is not managed by this caller")] Unauthorized, + /// The appointment is absent or not in a state that takes attendance. + /// The caller may own it, so this is no ownership decision. + #[error("the appointment does not take attendance")] + NotAttendable, + /// The task grant, or the access token that carried it, lapsed before the + /// commitment. + #[error("the task grant lapsed before the commitment")] + GrantLapsed, #[error("the observed revision does not match the current revision")] RevisionMismatch, #[error("the attendance observation time is in the future")] @@ -3862,7 +3874,7 @@ fn check_grant_current_at( ) -> Result<(), CommitError> { match commitment.grant_exp_unix { Some(exp) if now.timestamp() < i64::try_from(exp).unwrap_or(i64::MAX) => Ok(()), - Some(_) => Err(CommitError::Unauthorized), + Some(_) => Err(CommitError::GrantLapsed), // A mutating commitment without a grant never reaches the store: the // service refuses it before the transaction opens. None => Ok(()), diff --git a/crates/registry-scheduling/src/store/activation.rs b/crates/registry-scheduling/src/store/activation.rs index 402dc8c577..636e0b1df0 100644 --- a/crates/registry-scheduling/src/store/activation.rs +++ b/crates/registry-scheduling/src/store/activation.rs @@ -20,12 +20,16 @@ use uuid::Uuid; use super::{ check_policy_publication, current_schema_in, lock_publication, mark_allocation_writer, publish_policy, refuse_combined_conflicts, refuse_pre_1_0_schema, PolicyPublication, - PostgresStore, StoreError, MIGRATION_LOCK_KEY, SCHEDULING_MIGRATION, SCHEMA_VERSIONS, + PostgresStore, StoreError, ACTIVATION_POSTURE_MIGRATION, MIGRATION_LOCK_KEY, + SCHEDULING_MIGRATION, SCHEMA_VERSIONS, }; /// Supported SQL in application order. Keep the version ledger and dispatcher /// aligned: adding a known version without its implementation must not compile. -const SUPPORTED_MIGRATIONS: [(i64, &str); SCHEMA_VERSIONS.len()] = [(200, SCHEDULING_MIGRATION)]; +const SUPPORTED_MIGRATIONS: [(i64, &str); SCHEMA_VERSIONS.len()] = [ + (200, SCHEDULING_MIGRATION), + (201, ACTIVATION_POSTURE_MIGRATION), +]; const _: () = { let mut index = 0; while index < SCHEMA_VERSIONS.len() { @@ -447,15 +451,15 @@ impl PostgresStore { let activation = platform_activation::append_activation( &*transaction, &activation_layout(), - &NewActivation { - activation_id: request.activation_id, - package_digest: request.package_digest, - database_id: request.database_id, - operator_reference_hash: request.operator_reference_hash, - backup_references: request.backup_references, + &NewActivation::without_posture( + request.activation_id, + request.package_digest, + request.database_id, + request.operator_reference_hash, + request.backup_references, role_mode, - runtime_role: Some(request.runtime_role), - }, + Some(request.runtime_role), + ), ) .await .map_err(platform_error)?; @@ -1026,7 +1030,7 @@ pub(super) async fn check_active_package_in( client: &impl GenericClient, expected: &ActivePackage<'_>, ) -> Result { - platform_activation::check_active_package( + platform_activation::check_active_package_without_posture( client, &activation_layout(), expected.database_id, @@ -1041,6 +1045,14 @@ pub(super) async fn check_active_package_in( platform_activation::ActivePackageError::PackageNotActive { active, candidate } => { StoreError::PackageNotActive { active, candidate } } + // Until this product declares a posture it checks as production, so a + // ledger recorded in development is not its active package. + platform_activation::ActivePackageError::PostureMismatch { recorded, .. } => { + StoreError::PackageNotActive { + active: format!("recorded in the {} posture", recorded.as_str()), + candidate: expected.package_digest.to_owned(), + } + } platform_activation::ActivePackageError::Activation(error) => platform_error(error), }) } @@ -1218,7 +1230,7 @@ mod tests { assert!(message.contains("pre-1.0 schema"), "{message}"); assert!(message.contains("fresh database"), "{message}"); } - for applied in [vec![], vec![200]] { + for applied in [vec![], vec![200], vec![200, 201]] { SchemaState { applied, pending: Vec::new(), @@ -1234,10 +1246,14 @@ mod tests { SchemaState::default(), SchemaState { applied: vec![], - pending: vec![200], + pending: vec![200, 201], }, SchemaState { applied: vec![200], + pending: vec![201], + }, + SchemaState { + applied: vec![200, 201], pending: vec![], }, ] { @@ -1256,11 +1272,11 @@ mod tests { }, SchemaState { applied: vec![], - pending: vec![201], + pending: vec![202], }, SchemaState { applied: vec![], - pending: vec![200, 201], + pending: vec![200, 201, 202], }, SchemaState { applied: vec![], diff --git a/crates/registry-scheduling/src/store/attendance.rs b/crates/registry-scheduling/src/store/attendance.rs index c372e4f86e..a134678878 100644 --- a/crates/registry-scheduling/src/store/attendance.rs +++ b/crates/registry-scheduling/src/store/attendance.rs @@ -50,7 +50,7 @@ impl PostgresStore { claim.kind == LedgerKind::Booking && matches!(claim.state, ClaimState::Active | ClaimState::Cancelled) }) - .ok_or(CommitError::Unauthorized)?; + .ok_or(CommitError::NotAttendable)?; let appointment_revision = i64::try_from(request.observed_appointment_revision) .map_err(|_| CommitError::RevisionMismatch)?; if claim.revision != appointment_revision { diff --git a/crates/registry-scheduling/tests/golden/refusal-answers.json b/crates/registry-scheduling/tests/golden/refusal-answers.json new file mode 100644 index 0000000000..09f1f9b31e --- /dev/null +++ b/crates/registry-scheduling/tests/golden/refusal-answers.json @@ -0,0 +1,128 @@ +{ + "credential-malformed": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "credential-missing": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "key-source-unavailable": { + "body": { + "code": "service.unavailable", + "detail": "Scheduling storage is unavailable. Try again after the service recovers.", + "status": 503, + "title": "Scheduling service unavailable", + "type": "https://id.registrystack.org/problems/registry-scheduling/service/unavailable" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": "5", + "status": 503, + "wwwAuthenticate": null + }, + "operation": { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Scheduling profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/profile/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "scope": { + "body": { + "code": "profile.not-authorized", + "detail": "The selected Scheduling profile does not authorize this request.", + "status": 403, + "title": "Profile not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/profile/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "task-grant-lifetime": { + "body": { + "code": "grant.lifetime-too-long", + "detail": "The task grant has more than 900 seconds left before it expires. Present a task grant that expires within 900 seconds.", + "status": 403, + "title": "Task grant lifetime too long", + "type": "https://id.registrystack.org/problems/registry-scheduling/grant/lifetime-too-long" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "task-grant-missing": { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Scheduling authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/operation/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + }, + "token-signature": { + "body": { + "code": "authentication.refused", + "detail": "The bearer credential is missing, invalid, or expired. Sign in again.", + "status": 401, + "title": "Authentication refused", + "type": "https://id.registrystack.org/problems/registry-scheduling/authentication/refused" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 401, + "wwwAuthenticate": "Bearer" + }, + "visibility": { + "body": { + "code": "operation.not-authorized", + "detail": "Your current Scheduling authority does not allow this operation.", + "status": 403, + "title": "Operation not authorized", + "type": "https://id.registrystack.org/problems/registry-scheduling/operation/not-authorized" + }, + "cacheControl": "no-store", + "contentType": "application/problem+json", + "retryAfter": null, + "status": 403, + "wwwAuthenticate": null + } +} diff --git a/crates/registry-scheduling/tests/migration_pins.rs b/crates/registry-scheduling/tests/migration_pins.rs index 6b99623283..69c747b3ce 100644 --- a/crates/registry-scheduling/tests/migration_pins.rs +++ b/crates/registry-scheduling/tests/migration_pins.rs @@ -8,10 +8,16 @@ use std::path::Path; use registry_platform_testing::assert_migration_pins; -const PINS: &[(&str, &str)] = &[( - "0200_scheduling.sql", - "0e488c27a47818f21455292f030940bccc6dd82878fd6fe5baeef7dddda84b6f", -)]; +const PINS: &[(&str, &str)] = &[ + ( + "0200_scheduling.sql", + "0e488c27a47818f21455292f030940bccc6dd82878fd6fe5baeef7dddda84b6f", + ), + ( + "0201_activation_posture.sql", + "70b15bade04de9c5a5cc1d1486a2307c3c8e619c9a1faa0d7dc201316803ac28", + ), +]; #[test] fn every_migration_file_is_pinned_by_its_digest() { diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index e8b18087c5..6c2d85d944 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -20,9 +20,12 @@ use chrono::{DateTime, SecondsFormat, TimeDelta, Timelike, Utc}; use jsonwebtoken::{Algorithm, EncodingKey, Header}; use registry_platform_audit::{AuditHashSecret, AuditKeyHasher}; use registry_platform_config::{SecretProvider, SecretReference, SecretResolver}; -use registry_platform_crypto::delivery_signature::{sign_v1, SignatureFields}; +use registry_platform_crypto::delivery_signature::{ + verify, DeliveryKey, DeliveryKeys, SignedContent, DELIVERY_TOLERANCE, +}; use registry_platform_hooks::delivery::DeliveryOutcome; use registry_platform_hooks::{EnvelopeLimits, HookEnvelope, HookHandlerSource}; +use registry_platform_httputil::probe::{HEALTH_BODY, HEALTH_PATH, READY_BODY, READY_PATH}; use registry_platform_oidc::{ task_grant::{TaskGrantStatusEndpoint, TaskGrantStatusRegistry}, JwksFetcher, JwksFetcherConfig, TokenVerifierConfig, @@ -386,6 +389,7 @@ async fn fixture_publishing_with_hook_and_status( migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let migration_store = PostgresStore::connect_migration(&database, &secrets).expect("the migration store"); @@ -452,6 +456,7 @@ async fn fixture_publishing_with_hook_and_status( "secret:env/{hook_secret_name}" )) .expect("the test hook key reference"), + previous_hmac_sha256_key_ref: None, attempt_timeout_milliseconds: 5_000, maximum_attempts: 1, }, @@ -579,7 +584,7 @@ async fn activated_task_status( "statusResource": "urn:casework:test" })) .expect("the status authority configuration"); - let registry = TaskGrantStatusRegistry::activate( + let registry = TaskGrantStatusRegistry::activate_without_peer_policy( &[TaskGrantStatusEndpoint::from(&status)], AUDIENCE, &secrets, @@ -1914,15 +1919,15 @@ async fn hook_fixture_at(hook_url: &str) -> Fixture { registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: PACKAGE_DIGEST, - database_id: DATABASE_ID, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + PACKAGE_DIGEST, + DATABASE_ID, + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record the fixture activation"); @@ -2237,29 +2242,15 @@ async fn hook_delivery_sends_the_canonical_event_audits_egress_and_refuses_propo request.body, *payload, "the stored canonical bytes are sent" ); - let header = |name: &str| { - request - .headers - .get(name) - .and_then(|value| value.to_str().ok()) - .unwrap_or_else(|| panic!("missing valid {name} header")) - }; - assert_eq!(header("ce-specversion"), "1.0"); - assert_eq!(header("ce-id"), envelope.id); - assert_eq!(header("ce-source"), envelope.source); - assert_eq!(header("ce-type"), "confirmed-observer"); - assert_eq!(header("ce-dataschema"), envelope.dataschema); - let payload_json: Value = serde_json::from_slice(payload).expect("the canonical envelope JSON"); - assert_eq!(header("ce-time"), payload_json["time"]); - assert_eq!(header("x-registry-event-generation"), "1"); - assert_eq!(header("x-registry-delivery-attempt"), "1"); - assert!(!header("x-registry-delivery-time").is_empty()); - let idempotency_key = header("idempotency-key"); - assert!(idempotency_key.starts_with("sha256:")); - assert_eq!(idempotency_key.len(), 71); - let signature = header("x-registry-signature"); - assert!(signature.starts_with("v1=")); - assert_eq!(signature.len(), 46, "v1 plus one HMAC-SHA-256 tag"); + let content = signed_webhook_content(&request.headers, &request.body); + assert_eq!(content.id, envelope.id); + verify( + &webhook_keys(b"0123456789abcdef0123456789abcdef"), + content, + std::time::SystemTime::now(), + DELIVERY_TOLERANCE, + ) + .expect("the captured hook delivery verifies"); let state = fx .admin @@ -2408,15 +2399,15 @@ async fn hook_delivery_is_refused_when_the_activation_record_names_another_datab registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: PACKAGE_DIGEST, - database_id: "another-scheduling-database", - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + PACKAGE_DIGEST, + "another-scheduling-database", + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record an activation naming another database"); @@ -2459,16 +2450,15 @@ async fn hook_delivery_stops_once_the_activation_record_names_another_package() registry_platform_activation::append_activation( &fx.admin, &activation_layout(), - ®istry_platform_activation::NewActivation { - activation_id: Uuid::new_v4(), - package_digest: - "sha256:0000000000000000000000000000000000000000000000000000000000000002", - database_id: DATABASE_ID, - operator_reference_hash: None, - backup_references: &[], - role_mode: RoleMode::Single, - runtime_role: Some("scheduling_test"), - }, + ®istry_platform_activation::NewActivation::without_posture( + Uuid::new_v4(), + "sha256:0000000000000000000000000000000000000000000000000000000000000002", + DATABASE_ID, + None, + &[], + RoleMode::Single, + Some("scheduling_test"), + ), ) .await .expect("record a superseding activation"); @@ -2515,6 +2505,7 @@ async fn changed_retained_hook_destination_binding_is_refused() { .expect("the changed hook URL"), hmac_sha256_key_ref: SecretReference::parse(fx.hook_secret_ref.clone()) .expect("the test hook key reference"), + previous_hmac_sha256_key_ref: None, attempt_timeout_milliseconds: 5_000, maximum_attempts: 1, }, @@ -4922,25 +4913,25 @@ async fn outbox_row(fx: &Fixture, outbox_id: Uuid) -> (String, i32, Option Arc { - // The destination declares no bearer reference, so nothing is resolved; - // the resolver still has to exist, and refuses to be built with no - // provider enabled at all. - let secrets = SecretResolver::new([SecretProvider::Environment], std::path::Path::new("")) - .expect("a resolver this destination asks nothing of"); - Arc::new( - reminder_transport( - &ReminderDestinationConfig { - url: format!("{}/events", destination.uri()), - purpose_urls: Default::default(), - bearer_token_ref: None, - hmac_sha256_key_ref: None, - }, - &secrets, - ) - .expect("the configured destination compiles into a frozen transport"), - ) + transport_to_origin(&destination.uri()) +} + +fn transport_to_origin(origin: &str) -> Arc { + let secret_name = + format!("SCHEDULING_REMINDER_{}", Uuid::new_v4().simple()).to_ascii_uppercase(); + std::env::set_var(&secret_name, REMINDER_TEST_KEY); + let secrets = SecretResolver::new([SecretProvider::Environment], "/private/tmp") + .expect("the reminder test secret resolver"); + let config: ReminderDestinationConfig = serde_json::from_value(json!({ + "url": format!("{origin}/events"), + "hmacSha256KeyRef": format!("secret:env/{secret_name}") + })) + .expect("the reminder destination configuration"); + Arc::new(reminder_transport(&config, &secrets).expect("the reminder transport activates")) } /// The environment records the fixture seeds, minus the named resources: the @@ -5230,8 +5221,8 @@ async fn a_records_swap_checks_the_active_package_under_its_locks() { .execute( "INSERT INTO scheduling_activations(activation_id, apply_order, package_digest, \ predecessor_package_digest, database_id, plan_kind, applied_at, role_mode, \ - runtime_role) SELECT gen_random_uuid(), max(apply_order) + 1, $1, $2, \ - 'records-ledger', 'successor', now(), 'single', current_user \ + runtime_role, posture) SELECT gen_random_uuid(), max(apply_order) + 1, $1, $2, \ + 'records-ledger', 'successor', now(), 'single', current_user, 'production' \ FROM scheduling_activations", &[&second, &first], ) @@ -5890,6 +5881,38 @@ async fn an_allowed_commitment_writes_its_request_before_and_its_response_after( } } +/// The shared probe routes answer their fixed bodies with no token. The +/// older `/healthz` and `/readyz` spellings keep answering an empty 200. +#[tokio::test] +async fn probe_routes_answer_the_shared_bodies_and_the_older_spellings_still_answer() { + let fx = fixture().await; + for (path, expected) in [ + (HEALTH_PATH, Some(HEALTH_BODY)), + (READY_PATH, Some(READY_BODY)), + ("/healthz", None), + ("/readyz", None), + ] { + let response = fx + .http + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .expect("an in-process request always answers"); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + let content_type = response.headers().get("content-type").cloned(); + let body = to_bytes(response.into_body(), 1024) + .await + .expect("a bounded test body"); + match expected { + Some(expected) => { + assert_eq!(content_type.unwrap(), "application/json", "{path}"); + assert_eq!(body.as_ref(), expected.as_bytes(), "{path}"); + } + None => assert!(body.is_empty(), "{path}"), + } + } +} + /// SCHEDULING-SEC-14: a commitment whose request entry the destination /// refuses never opens its capacity transaction. No claim is taken, no /// receipt is stored, and the caller is told the service is unavailable. @@ -5920,6 +5943,12 @@ async fn a_refused_request_entry_opens_no_capacity_transaction() { StatusCode::SERVICE_UNAVAILABLE, "readiness follows the audit destination" ); + let (status, _) = fx.get(READY_PATH, &fx.reader).await; + assert_eq!( + status, + StatusCode::SERVICE_UNAVAILABLE, + "the shared readiness route follows the audit destination" + ); } /// SCHEDULING-SEC-14: the response entry is written after commit. When the @@ -6868,90 +6897,126 @@ async fn a_dispatch_pass_delivers_retries_and_holds_by_what_the_destination_answ ); } -#[tokio::test] -async fn a_signed_reminder_uses_the_shared_event_delivery_contract() { - const SIGNING_KEY: &str = "reminder-delivery-signing-key-0123456789abcdef"; - - let destination = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/events")) - .respond_with(ResponseTemplate::new(202)) - .mount(&destination) - .await; - let fx = fixture().await; - let (appointment, _) = booked(&fx, 90, 200, "dispatch-signed").await; - let secret_name = - format!("SCHEDULING_REMINDER_{}", Uuid::new_v4().simple()).to_ascii_uppercase(); - let bearer_name = - format!("SCHEDULING_REMINDER_BEARER_{}", Uuid::new_v4().simple()).to_ascii_uppercase(); - std::env::set_var(&secret_name, SIGNING_KEY); - std::env::set_var(&bearer_name, "synthetic-reminder-token"); - let secrets = SecretResolver::new([SecretProvider::Environment], "/private/tmp") - .expect("the scheduling reminder secret resolver"); - let destination_config: ReminderDestinationConfig = serde_json::from_value(json!({ - "url": format!("{}/events", destination.uri()), - "hmacSha256KeyRef": format!("secret:env/{secret_name}"), - "bearerTokenRef": format!("secret:env/{bearer_name}") - })) - .expect("the signed reminder destination configuration"); - let transport = reminder_transport(&destination_config, &secrets) - .expect("the signed destination compiles into a frozen transport"); - - bring_intents_due(&fx, pinned_now()).await; - dispatch_due_intents(&fx.store, SCHEDULING_ID, Some(Arc::new(transport))) - .await - .expect("the signed dispatch pass runs"); +fn webhook_keys(bytes: &[u8]) -> DeliveryKeys { + DeliveryKeys::new(DeliveryKey::new(bytes).unwrap(), None).unwrap() +} - let requests = destination - .received_requests() - .await - .expect("the signed reminder request"); - let request = requests - .iter() - .find(|request| String::from_utf8_lossy(&request.body).contains(appointment.as_str())) - .expect("the appointment's signed reminder"); - let event: Value = serde_json::from_slice(&request.body).expect("the canonical reminder event"); +fn signed_webhook_content<'a>( + headers: &'a axum::http::HeaderMap, + body: &'a [u8], +) -> SignedContent<'a> { let header = |name: &str| { - request - .headers + headers .get(name) .and_then(|value| value.to_str().ok()) .unwrap_or_else(|| panic!("missing valid {name} header")) }; - assert_eq!(header("ce-specversion"), "1.0"); - assert_eq!(header("ce-id"), event["id"]); - assert_eq!(header("ce-source"), event["source"]); - assert_eq!(header("ce-type"), event["type"]); - assert_eq!(header("ce-time"), event["time"]); - assert_eq!(header("ce-dataschema"), event["dataschema"]); - assert_eq!(header("x-registry-event-generation"), "1"); - assert_eq!(header("x-registry-delivery-attempt"), "1"); - assert!(!header("x-registry-delivery-time").is_empty()); - assert!(header("idempotency-key").starts_with("sha256:")); - assert_eq!(header("authorization"), "Bearer synthetic-reminder-token"); - let fields = |request_target| SignatureFields { - id: header("ce-id"), - source: header("ce-source"), - event_type: header("ce-type"), - time: header("ce-time"), - data_schema: header("ce-dataschema"), - generation: header("x-registry-event-generation"), - attempt: header("x-registry-delivery-attempt"), - delivery_time: header("x-registry-delivery-time"), - method: "POST", - request_target, - content_type: "application/json", - idempotency_key: header("idempotency-key"), - body: &request.body, - }; - let expected = - sign_v1(SIGNING_KEY.as_bytes(), fields("/events")).expect("the shared signature"); - assert_eq!(header("x-registry-signature"), expected); - assert_ne!( - sign_v1(SIGNING_KEY.as_bytes(), fields("/other")).expect("the target-bound signature"), - expected, - "the exact request target is covered" + // The HTTP client supplies host and framing. + let mut names = headers + .keys() + .map(|name| name.as_str()) + .filter(|name| !matches!(*name, "host" | "content-length")) + .collect::>(); + names.sort_unstable(); + assert_eq!( + names, + [ + "accept", + "content-type", + "webhook-id", + "webhook-signature", + "webhook-timestamp" + ] ); + assert_eq!(header("accept"), "application/json"); + assert_eq!(header("content-type"), "application/json"); + SignedContent { + id: header("webhook-id"), + timestamp: header("webhook-timestamp"), + signature: header("webhook-signature"), + body, + } +} + +#[tokio::test] +async fn a_signed_reminder_uses_the_standard_webhooks_delivery_contract() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let transport = transport_to_origin(&format!("http://{}", listener.local_addr().unwrap())); + let (captured, mut requests) = tokio::sync::mpsc::channel(1); + let receiver = Router::new().route( + "/events", + axum::routing::post( + move |headers: axum::http::HeaderMap, body: axum::body::Bytes| async move { + let (respond, release) = tokio::sync::oneshot::channel(); + captured.send((headers, body, respond)).await.unwrap(); + release.await.unwrap() + }, + ), + ); + let server = tokio::spawn(async move { axum::serve(listener, receiver).await.unwrap() }); + let fx = fixture().await; + let (appointment, _) = booked(&fx, 90, 200, "dispatch-signed").await; + let outbox_id = intent_of(&fx, &appointment, "confirmation").await; + let keys = webhook_keys(REMINDER_TEST_KEY.as_bytes()); + let mut attempts = Vec::new(); + + for response in [StatusCode::SERVICE_UNAVAILABLE, StatusCode::ACCEPTED] { + make_intent_due(&fx, outbox_id).await; + let store = fx.store.clone(); + let transport = Arc::clone(&transport); + let running = tokio::spawn(async move { + dispatch_due_intents(&store, SCHEDULING_ID, Some(transport)).await + }); + + let (headers, body, respond) = + tokio::time::timeout(Duration::from_secs(5), requests.recv()) + .await + .expect("the signed reminder reaches the receiver") + .unwrap(); + let lease_time: DateTime = fx + .admin + .query_one( + "SELECT attempt_started_at FROM scheduling_outbox WHERE outbox_id = $1 AND state = 'leased'", + &[&outbox_id], + ) + .await + .expect("read the lease during delivery") + .get(0); + respond.send(response).unwrap(); + + let event: Value = serde_json::from_slice(&body).expect("the canonical reminder event"); + let content = signed_webhook_content(&headers, &body); + assert_eq!(content.id, outbox_id.to_string()); + assert_eq!(content.id, event["id"]); + assert_eq!(content.timestamp, lease_time.timestamp().to_string()); + verify(&keys, content, lease_time.into(), DELIVERY_TOLERANCE) + .expect("the captured reminder verifies"); + attempts.push((content.id.to_owned(), body, lease_time.timestamp())); + + running + .await + .unwrap() + .expect("the signed dispatch pass runs"); + if response == StatusCode::SERVICE_UNAVAILABLE { + // Ensure a reused timestamp would fail on the second attempt. + tokio::time::sleep(Duration::from_secs(1)).await; + } + } + + assert_eq!(attempts[0].0, attempts[1].0); + assert_eq!(attempts[0].1, attempts[1].1); + assert!(attempts[0].2 < attempts[1].2); + let state: String = fx + .admin + .query_one( + "SELECT state FROM scheduling_outbox WHERE outbox_id = $1", + &[&outbox_id], + ) + .await + .unwrap() + .get(0); + assert_eq!(state, "delivered"); + server.abort(); } /// A receiver can accept an event before the dispatcher loses the database @@ -8834,7 +8899,10 @@ async fn an_unlisted_source_is_refused_and_never_reaches_the_offline_path() { /// SEC-03. On the offline path that `unchecked-final-fifteen-minutes` /// selects, a grant with one second more than fifteen minutes left is refused -/// and one with exactly fifteen minutes left books. +/// with `grant.lifetime-too-long` and one with exactly fifteen minutes left +/// books. The new answer follows the bounds check: a caller with no grant, or +/// whose grant does not cover the offering, still gets +/// `operation.not-authorized`. #[tokio::test] async fn the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime() { let fx = fixture().await; @@ -8849,6 +8917,82 @@ async fn the_offline_path_accepts_at_most_fifteen_minutes_of_remaining_lifetime( ) .await; assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "grant.lifetime-too-long"); + // The refusal is audited under the same reason every grant refusal + // carries, so an audit consumer keyed on it still sees these. + let journal = audit_by_reason(&fx); + assert_eq!( + journal.keys().cloned().collect::>(), + vec!["authorization.refused".to_owned()] + ); + assert_eq!(journal["authorization.refused"]["outcome"], "denied"); + assert_eq!( + journal["authorization.refused"]["operation"], + "appointment.create" + ); + + let a_day_left = agent_token_with_grant_exp(pinned_now().timestamp() + 86_400); + let (status, problem) = fx + .post( + "/v1/appointments", + &a_day_left, + "a-day-left", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "grant.lifetime-too-long"); + + let no_grant = token(json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + })); + let (status, problem) = fx + .post( + "/v1/appointments", + &no_grant, + "no-grant-order", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); + + let mut uncovered = grant_claims(); + uncovered["registry_grant_exp"] = json!(pinned_now().timestamp() + 86_400); + uncovered["registry_grant_bounds"]["permissions"] = json!([{ + "service": "registry-other", + "location": "south-counter", + "actions": ["appointment.create"], + }]); + let mut claims = json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + }); + claims + .as_object_mut() + .expect("claims are an object") + .extend( + uncovered + .as_object() + .expect("grant claims are an object") + .iter() + .map(|(key, value)| (key.clone(), value.clone())), + ); + let (status, problem) = fx + .post( + "/v1/appointments", + &token(claims), + "uncovered-order", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); let at_the_cap = agent_token_with_grant_exp(pinned_now().timestamp() + 900); let (status, booked) = fx @@ -9984,6 +10128,7 @@ async fn refuses_a_pre_1_0_ledger_at_migrate_and_readiness(version: i64) { migration_url_ref: format!("secret:env/{secret_name}"), ca_bundle_ref: None, test_only_plaintext: true, + transport: None, }; let store = PostgresStore::connect_migration(&database, &secrets).expect("the migration store"); diff --git a/crates/registry-scheduling/tests/postgres_commitments/attendance.rs b/crates/registry-scheduling/tests/postgres_commitments/attendance.rs index 5a577a35fa..5775cd50d4 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/attendance.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/attendance.rs @@ -865,3 +865,50 @@ async fn attendance_commit_captures_one_minimized_signed_after_event() { } } } + +/// A caller recording attendance on its own booking after the booking left an +/// attendance state is refused with the same 403 as any other attendance +/// refusal. The check the operator's log line names is `visibility`: the +/// target is the caller's own, so it is not an `ownership` refusal. +#[tokio::test] +async fn attendance_on_the_callers_own_closed_booking_is_not_counted_as_ownership() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let (appointment_id, appointment_revision) = + booked(&fx, 300, 440, "attendance-closed-booking").await; + let appointment_uuid = Uuid::parse_str(&appointment_id).expect("an appointment UUID"); + begin_current_test_writer(&fx.admin).await; + fx.admin + .execute( + "UPDATE scheduling_claims SET state='released' WHERE claim_id=$1", + &[&appointment_uuid], + ) + .await + .expect("the booking leaves its attendance states"); + commit_current_test_writer(&fx.admin).await; + let recorder = attendance_token("attendance-desk", &["attendance.record"], pinned_now()); + let captured = CapturedDiagnosticLogs::default(); + let (status, refusal) = put_attendance( + &fx, + &appointment_id, + &recorder, + "attendance-closed", + appointment_revision, + 0, + "arrived", + pinned_now() - TimeDelta::minutes(5), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refusal}"); + assert_eq!(refusal["code"], "operation.not-authorized"); + let lines: Vec = captured + .text() + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "visibility"); +} diff --git a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs index 83e6c87a57..e3db358684 100644 --- a/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs +++ b/crates/registry-scheduling/tests/postgres_commitments/review_regressions.rs @@ -279,14 +279,388 @@ async fn header_refusals_on_detail_busy_and_operational_routes_log_one_value_fre .expect("an in-process request always answers"); assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{uri}"); let rendered = captured.text(); - let diagnostics = rendered - .lines() - .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) - .filter(|event| event["fields"]["message"] == "Scheduling authentication refused") - .collect::>(); + let diagnostics = refusal_lines(&rendered); assert_eq!(diagnostics.len(), 1, "{uri}"); - assert_eq!(diagnostics[0]["fields"]["stage"], "header", "{uri}"); + // Another scheme is a credential this route does not take. + assert_eq!( + diagnostics[0]["fields"]["failed_check"], "credential-missing", + "{uri}" + ); assert!(!rendered.contains("canary"), "{uri}"); assert!(!rendered.contains("Basic"), "{uri}"); } } + +/// The refusal lines of one captured run: the one fixed message the HTTP +/// edge writes for every refusal. +fn refusal_lines(rendered: &str) -> Vec { + rendered + .lines() + .map(|line| serde_json::from_str::(line).expect("JSON diagnostic")) + .filter(|event| event["fields"]["message"] == "request refused") + .collect() +} + +/// A refusal decided inside the service names the check that refused, in +/// the operator's log line and nowhere in the answer: the same 403 answers a +/// hold that does not exist and a hold the caller holds no task grant for. +#[tokio::test] +async fn service_refusals_log_the_check_that_refused_and_answer_alike() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 300, 440).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "hold-for-refusal-checks", + admission(&fx, OFFERING, slot), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + + let mut answers = Vec::new(); + for (uri, expected) in [ + (format!("/v1/holds/{}", Uuid::new_v4()), "visibility"), + (format!("/v1/holds/{hold_id}"), "task-grant-missing"), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .delete(&uri, &fx.reader) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{uri}"); + assert_eq!(answer["code"], "operation.not-authorized", "{uri}"); + let rendered = captured.text(); + let lines = refusal_lines(&rendered); + assert_eq!(lines.len(), 1, "{uri}: {rendered}"); + assert_eq!(lines[0]["fields"]["failed_check"], expected, "{uri}"); + assert!(!rendered.contains(&hold_id), "{uri}"); + let mut answer = answer; + answer + .as_object_mut() + .expect("a problem body") + .remove("traceId"); + answers.push(answer); + } + assert_eq!( + answers[0], answers[1], + "the check never reaches the caller: a missing and an unreachable hold answer alike" + ); +} + +/// The check a foreign caller's refusal names says why it was refused: a +/// reschedule, a cancellation, and a release of another caller's target are +/// ownership refusals, and a read it holds no grant action for is a grant +/// scope refusal. The answers are the same 403 `operation.not-authorized`. +#[tokio::test] +async fn a_foreign_callers_refusals_name_ownership_and_grant_scope() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 300, 440).await; + let (status, created) = fx + .post( + "/v1/appointments", + &fx.agent, + "foreign-checks-appointment", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let appointment_id = created["appointmentId"].as_str().unwrap().to_owned(); + let held = first_slot(&fx, OFFERING, 480, 620).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "foreign-checks-hold", + admission(&fx, OFFERING, held), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + let stranger = agent_token_for("principal-stranger"); + let other = first_slot(&fx, OFFERING, 640, 700).await; + for (method, uri, key, body, expected) in [ + ( + "POST", + format!("/v1/appointments/{appointment_id}/reschedule"), + Some("foreign-checks-reschedule"), + Some(json!({"observedRevision": 0, "admission": admission(&fx, OFFERING, other)})), + "ownership", + ), + ( + "POST", + format!("/v1/appointments/{appointment_id}/cancel"), + Some("foreign-checks-cancel"), + Some(json!({"observedRevision": 0, "reason": null})), + "ownership", + ), + ( + "DELETE", + format!("/v1/holds/{hold_id}"), + None, + None, + "ownership", + ), + ( + "GET", + format!("/v1/appointments/{appointment_id}"), + None, + None, + "task-grant-scope", + ), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .request(method, &uri, &stranger, key, body) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}"); + assert_eq!(answer["code"], "operation.not-authorized", "{method} {uri}"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1, "{method} {uri}"); + assert_eq!( + lines[0]["fields"]["failed_check"], expected, + "{method} {uri}" + ); + } +} + +/// The task grant the booking agent carries, with a day left on it and the +/// attendance action added: past the offline path's fifteen-minute cap. +fn long_lived_agent_token() -> String { + let mut grant = grant_claims(); + grant["registry_grant_exp"] = json!(pinned_now().timestamp() + 86_400); + grant["registry_grant_bounds"]["permissions"][0]["actions"] + .as_array_mut() + .expect("the actions are a list") + .push(json!("attendance.record")); + let mut claims = json!({ + "sub": "principal-agent", + "azp": CLIENT, + "registry_scopes": "scheduling-read scheduling-explain", + "registry_actor_kind": "service", + }); + claims + .as_object_mut() + .expect("claims are an object") + .extend( + grant + .as_object() + .expect("grant claims are an object") + .iter() + .map(|(key, value)| (key.clone(), value.clone())), + ); + token(claims) +} + +/// SCHEDULING-DEC-01. On a route that names an existing hold or appointment, +/// a grant with too much lifetime left answers `operation.not-authorized`, +/// the same answer an unknown id gives, so the answer never says whether the +/// id exists. The operator's line still names `task-grant-lifetime`. +#[tokio::test] +async fn an_id_addressed_route_answers_an_existing_and_an_unknown_id_alike_under_a_long_grant() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let long = long_lived_agent_token(); + let held = first_slot(&fx, OFFERING, 300, 440).await; + let (status, hold) = fx + .post( + "/v1/holds", + &fx.agent, + "long-grant-hold", + admission(&fx, OFFERING, held), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{hold}"); + let hold_id = hold["holdId"].as_str().unwrap().to_owned(); + let (appointment_id, revision) = booked(&fx, 480, 620, "long-grant-appointment").await; + let other = first_slot(&fx, OFFERING, 640, 700).await; + let unknown = Uuid::new_v4().to_string(); + + let routes = |hold: &str, appointment: &str| { + vec![ + ("release", "DELETE", format!("/v1/holds/{hold}"), None, None), + ( + "confirm", + "POST", + "/v1/appointments".to_owned(), + Some("long-grant-confirm"), + Some(json!({"hold": hold, "admission": null})), + ), + ( + "reschedule", + "POST", + format!("/v1/appointments/{appointment}/reschedule"), + Some("long-grant-reschedule"), + Some( + json!({"observedRevision": revision, "admission": admission(&fx, OFFERING, other)}), + ), + ), + ( + "attendance", + "PUT", + format!("/v1/appointments/{appointment}/attendance"), + Some("long-grant-attendance"), + Some(json!({ + "observedAppointmentRevision": revision, + "observedRevision": 0, + "state": "arrived", + "observedAt": stamp(pinned_now() - TimeDelta::minutes(5)), + })), + ), + ( + "cancel", + "POST", + format!("/v1/appointments/{appointment}/cancel"), + Some("long-grant-cancel"), + Some(json!({"observedRevision": revision, "reason": null})), + ), + ] + }; + let existing_routes = routes(&hold_id, &appointment_id); + let unknown_routes = routes(&unknown, &unknown); + for (existing, missing) in existing_routes.into_iter().zip(unknown_routes) { + let (label, method, uri, key, body) = existing; + let mut answers = Vec::new(); + let mut checks = Vec::new(); + for (target, (_, method, uri, key, body)) in [ + ("existing", (label, method, uri, key, body)), + ("unknown", missing), + ] { + let captured = CapturedDiagnosticLogs::default(); + let (status, mut answer) = fx + .request(method, &uri, &long, key, body) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{label} {target}: {answer}"); + assert_eq!( + answer["code"], "operation.not-authorized", + "{label} {target}" + ); + answer + .as_object_mut() + .expect("a problem body") + .remove("traceId"); + answers.push(answer); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1, "{label} {target}"); + checks.push(lines[0]["fields"]["failed_check"].clone()); + } + assert_eq!( + answers[0], answers[1], + "{label}: an existing id and an unknown id answer alike" + ); + assert_eq!(checks, ["task-grant-lifetime", "visibility"], "{label}"); + } + + // No caller-named id is involved: a new hold keeps the specific code. A + // fresh deployment keeps this line clear of the per-check log limit the + // five routes above used up. + let fx = fixture().await; + let other = first_slot(&fx, OFFERING, 640, 700).await; + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .post( + "/v1/holds", + &long, + "long-grant-new-hold", + admission(&fx, OFFERING, other), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "grant.lifetime-too-long"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "task-grant-lifetime"); +} + +/// A task grant that lapses between the request's admission and the capacity +/// transaction's decision-time re-check is a lapsed grant, not an ownership +/// refusal. +#[tokio::test] +async fn a_grant_that_lapses_inside_the_transaction_is_counted_as_expired() { + use registry_platform_testing::CapturedDiagnosticLogs; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let slot = first_slot(&fx, OFFERING, 90, 200).await; + let door = pinned_now(); + let observations = Arc::new(AtomicUsize::new(0)); + let observed = observations.clone(); + fx.store.pin_clock(Arc::new(move || { + if observed.fetch_add(1, Ordering::SeqCst) == 0 { + door + } else { + door + TimeDelta::minutes(20) + } + })); + let captured = CapturedDiagnosticLogs::default(); + let (status, problem) = fx + .post( + "/v1/appointments", + &fx.agent, + "lapsed-in-transaction", + json!({"hold": null, "admission": admission(&fx, OFFERING, slot)}), + ) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{problem}"); + assert_eq!(problem["code"], "operation.not-authorized"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "task-grant-expired"); +} + +/// A caller with the reads scope and no task grant, reading another +/// caller's appointment, is refused on ownership. +#[tokio::test] +async fn a_reads_scope_caller_reading_another_owners_appointment_is_an_ownership_refusal() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let (appointment_id, _) = booked(&fx, 300, 440, "reads-scope-foreign").await; + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .get(&format!("/v1/appointments/{appointment_id}"), &fx.reader) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "operation.not-authorized"); + let lines = refusal_lines(&captured.text()); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "ownership"); +} + +/// A read refused for its scope names the values the operator declared: the +/// claim that carries scopes and the scope the route needs. The scope the +/// token carries never reaches the line, and the answer is the same 403. +#[tokio::test] +async fn a_scope_refusal_line_names_the_declared_scope_and_none_of_the_tokens() { + use registry_platform_testing::CapturedDiagnosticLogs; + use tracing::instrument::WithSubscriber; + let fx = fixture().await; + let canary = "canary-token-scope-4d8e"; + let holder = operational_token("principal-canary", canary); + let captured = CapturedDiagnosticLogs::default(); + let (status, answer) = fx + .get("/v1/offerings", &holder) + .with_subscriber(captured.subscriber()) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{answer}"); + assert_eq!(answer["code"], "profile.not-authorized"); + let rendered = captured.text(); + assert!(!rendered.contains(canary), "{rendered}"); + let lines = refusal_lines(&rendered); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0]["fields"]["failed_check"], "scope"); + assert_eq!(lines[0]["fields"]["scope_claim"], "registry_scopes"); + assert_eq!(lines[0]["fields"]["required_scope"], "scheduling-read"); + assert!(lines[0]["fields"].get("access_profile").is_none()); +} diff --git a/crates/registry-scheduling/tests/token_characterisation.rs b/crates/registry-scheduling/tests/token_characterisation.rs new file mode 100644 index 0000000000..394b3b6d18 --- /dev/null +++ b/crates/registry-scheduling/tests/token_characterisation.rs @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Characterisation of Scheduling's bearer authentication against the token +//! fixture corpus (`products/platform/conformance/tokens`). +//! +//! Every row of `expected.yaml` with a `scheduling` cell is run through the +//! authenticator the server builds: the verifier profile and the authenticator +//! settings come from a `RuntimeConfig` loaded from a runtime file, the keys +//! from that file's static key source, and the credential goes through +//! `SchedulingAuthenticator::authenticate_read`, the plain read. No database is +//! involved. +//! +//! The authenticator reports a verifier refusal as one error. The stage of that +//! refusal is read by running the same token through a second verifier built +//! from the same configuration and keys, so the stage is the shared verifier's +//! own label. + +use std::collections::BTreeMap; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; + +use registry_platform_authcommon::FailedCheck; +use registry_platform_config::write_package; +use registry_platform_oidc::TokenVerifier; +use registry_platform_testing::{ + ClaimValue, Configuration, FixtureCase, Outcome, TokenCorpus, TokenSigner, +}; +use registry_scheduling::auth::{AuthenticationError, SchedulingAuthenticator}; +use registry_scheduling::config::{package_limits, RuntimeConfig, PACKAGE_COMMAND}; +use registry_scheduling::runtime::secret_resolver; +use registry_scheduling_core::{ + AUTHORED_POLICY_FILE, SCHEDULING_RUNTIME_API_VERSION, SCHEDULING_RUNTIME_KIND, +}; +use serde_json::{json, Value}; + +const ISSUER: &str = "https://identity.example.test"; +const AUDIENCE: &str = "urn:example:scheduling"; +/// The client a fixture without a client claim is configured against: the +/// allowed list always holds one client, as the runtime requires. +const PLACEHOLDER_CLIENT: &str = "journey-app"; +const PLACEHOLDER_SCOPE: &str = "records:get"; +/// A scope no fixture carries, so the explain scope never equals the read scope. +const EXPLAIN_SCOPE: &str = "corpus:explain"; + +fn literal_string(case: &FixtureCase, claim: &str) -> Option { + match case.fixture.claims.get(claim) { + Some(ClaimValue::Literal(Value::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The client the fixture names, from `client_id` or `azp`. +fn fixture_client(case: &FixtureCase) -> String { + literal_string(case, "client_id") + .or_else(|| literal_string(case, "azp")) + .unwrap_or_else(|| PLACEHOLDER_CLIENT.to_owned()) +} + +/// The claim the configuration reads scopes from. +fn scope_claim(case: &FixtureCase) -> &'static str { + if case.configuration == Configuration::Recipe + && case.fixture.claims.contains_key("scp") + && !case.fixture.claims.contains_key("scope") + { + "scp" + } else { + "scope" + } +} + +fn write_private(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write a private file"); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).expect("restrict the file"); +} + +/// The key set a static key source accepts: it refuses a set holding any key +/// that is not RSA or EC, so the corpus's EdDSA key stays out of the file. No +/// admitted algorithm uses it. +fn static_key_set(jwks: &Value) -> Value { + let keys: Vec = jwks["keys"] + .as_array() + .expect("a key set with a keys array") + .iter() + .filter(|key| matches!(key["kty"].as_str(), Some("RSA" | "EC"))) + .cloned() + .collect(); + json!({ "keys": keys }) +} + +fn refusal(stage_label: &str) -> Outcome { + format!("refused/{stage_label}") + .parse() + .expect("a stage the corpus knows") +} + +async fn observe(package_root: PathBuf, case: FixtureCase) -> Outcome { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a runtime directory"); + let secrets = root.path().join("secrets"); + fs::create_dir(&secrets).expect("a secrets directory"); + fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).expect("restrict secrets"); + write_private( + &secrets.join("issuer-jwks"), + &serde_json::to_vec(&static_key_set(&case.jwks)).expect("a key set"), + ); + let claim = scope_claim(&case); + let scope = case + .fixture + .read_scope(claim) + .unwrap_or_else(|| PLACEHOLDER_SCOPE.to_owned()); + let runtime_path = root.path().join("runtime.json"); + fs::write( + &runtime_path, + serde_json::to_vec(&json!({ + "apiVersion": SCHEDULING_RUNTIME_API_VERSION, + "kind": SCHEDULING_RUNTIME_KIND, + "identity": {"databaseId": "token-characterisation"}, + "package": {"root": package_root}, + "listener": {"bind": "127.0.0.1:0", "tlsTermination": "development-loopback", "networkExposure": "private-address"}, + "secretProviders": {"file": {"root": secrets}, "environment": {}}, + "database": { + "runtimeUrlRef": "secret:env/SCHEDULING_RUNTIME_URL", + "migrationUrlRef": "secret:env/SCHEDULING_MIGRATION_URL" + }, + "authentication": {"oidc": { + "issuer": case.issuer, + "audience": case.audience, + "jwksSource": {"type": "static", "documentRef": "secret:file/issuer-jwks"}, + "allowedClients": [fixture_client(&case)], + "scopeClaim": claim, + "readsScope": scope, + "explainScope": EXPLAIN_SCOPE + }}, + "taskGrantStatus": "unchecked-final-fifteen-minutes", + "audit": {"path": root.path().join("audit.jsonl"), "hashKeyRef": "secret:file/audit-key"}, + "destinations": {}, + "retention": {"receiptRetentionDays": 7} + })) + .expect("a runtime document"), + ) + .expect("write the runtime file"); + let config = RuntimeConfig::load(&runtime_path).expect("the runtime configuration loads"); + let resolver = secret_resolver(&config).expect("the secret resolver"); + let (verifier, keys) = config + .oidc_verifier(&resolver) + .await + .expect("the static key source"); + + let authenticator = + SchedulingAuthenticator::new(&config.authentication.oidc, verifier.clone(), keys.clone()); + let token = case.token.expose(); + match authenticator.authenticate_read(token).await { + Ok(caller) => Outcome::Admitted(Some(caller.actor_kind)), + Err(AuthenticationError::Claims(_)) => refusal("claims"), + Err(AuthenticationError::Unavailable) => refusal("unavailable"), + Err(error @ (AuthenticationError::Refused(_) | AuthenticationError::Profile(_))) => { + let reference = TokenVerifier::new(verifier, keys); + match reference.verify(token).await { + Err(failure) => { + // The refusal records the shared verifier's own check, or + // the malformed credential the compact-token admission + // refuses before the verifier runs. + assert!( + matches!( + error, + AuthenticationError::Refused(check) + if check == failure.failed_check() + || check == FailedCheck::CredentialMalformed + ), + "{error:?} does not carry the verifier check" + ); + Outcome::refused_by(&failure) + } + Ok(verified) if matches!(error, AuthenticationError::Profile(_)) => { + if verified.scopes.iter().any(|held| held == &scope) { + refusal("profile") + } else { + assert_eq!(error, AuthenticationError::Profile(FailedCheck::Scope)); + refusal("scope") + } + } + // The credential is not a compact access token, so the + // verifier is never reached. + Ok(_) => { + assert_eq!( + error, + AuthenticationError::Refused(FailedCheck::CredentialMalformed) + ); + refusal("header") + } + } + } + } +} + +/// The standalone example policy, installed as a package the runtime file can name. +fn installed_example_package() -> tempfile::TempDir { + let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().expect("a temp dir")) + .expect("a package directory"); + write_package( + &root.path().join("package"), + &BTreeMap::from([( + AUTHORED_POLICY_FILE.to_owned(), + include_bytes!( + "../../../products/scheduling/examples/standalone-exact-time/scheduling.yaml" + ) + .to_vec(), + )]), + None, + &package_limits(), + PACKAGE_COMMAND, + ) + .expect("the installed example package"); + root +} + +#[tokio::test] +async fn scheduling_authentication_matches_the_token_corpus() { + let corpus = TokenCorpus::load().expect("the token corpus loads"); + let installed = installed_example_package(); + let signer = TokenSigner::new(); + let report = corpus + .run_product_async("scheduling", &signer, ISSUER, AUDIENCE, |case| { + observe(installed.path().join("package"), case) + }) + .await + .expect("every scheduling row is planned and signed"); + let run = report + .rows + .iter() + .filter(|row| row.observed.is_some()) + .count(); + assert!(run > 0, "no scheduling row ran"); + eprintln!( + "scheduling: {run} rows ran, {} differ", + report.mismatches().len() + ); + report.assert_matches(); +} diff --git a/crates/registry-schedulingctl/Cargo.toml b/crates/registry-schedulingctl/Cargo.toml index 1a3502b187..f27ef4de92 100644 --- a/crates/registry-schedulingctl/Cargo.toml +++ b/crates/registry-schedulingctl/Cargo.toml @@ -26,6 +26,7 @@ registry-cli-api.workspace = true registry-platform-audit.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-scheduling.workspace = true registry-scheduling-core.workspace = true @@ -34,6 +35,7 @@ serde_json.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt"] } uuid.workspace = true +zeroize.workspace = true [dev-dependencies] # The database suites reach the runtime's plaintext test connection through @@ -42,6 +44,7 @@ uuid.workspace = true # holding both crates, and the runtime's own database suite would then be # compiled and run by shards that have no server to offer it. chrono.workspace = true +registry-platform-provision = { workspace = true, features = ["test-support"] } tokio-postgres.workspace = true [[test]] @@ -55,3 +58,7 @@ required-features = ["postgres-test"] [[test]] name = "activation_postgres" required-features = ["postgres-test"] + +[[test]] +name = "provision_postgres" +required-features = ["postgres-test"] diff --git a/crates/registry-schedulingctl/src/activation.rs b/crates/registry-schedulingctl/src/activation.rs index 5e0c1bf510..0b2fefa125 100644 --- a/crates/registry-schedulingctl/src/activation.rs +++ b/crates/registry-schedulingctl/src/activation.rs @@ -23,8 +23,8 @@ use registry_platform_audit::AuditWriter; use registry_platform_config::SecretResolver; use registry_scheduling::audit::{with_event_id, SchedulingAudit}; use registry_scheduling::config::RuntimeConfig; -use registry_scheduling::hooks::{ActivatedHooks, HookRuntimeIdentity}; -use registry_scheduling::runtime::open_audit; +use registry_scheduling::hooks::{ActivatedHooks, HookActivationError, HookRuntimeIdentity}; +use registry_scheduling::runtime::{activate_reminder_delivery, open_audit}; use registry_scheduling::store::{ Activation, ActivationRequest, DeployedPolicy, PostgresStore, RoleMode, StoreError, SINGLE_ROLE_STATEMENT, @@ -109,6 +109,9 @@ fn hook_payload_retention(config: &RuntimeConfig) -> Duration { /// The closed code of a candidate whose hook destinations cannot run, which /// apply refuses before it writes anything. pub(crate) const HOOK_DESTINATIONS_CODE: &str = "schedulingctl.activation.hook-destinations"; +const REMINDER_DESTINATIONS_CODE: &str = "schedulingctl.activation.reminder-destinations"; +pub(crate) const HOOK_DESTINATIONS_ACTION: &str = + "Bind every destination the policy hooks name under destinations.hooks. Give each destination its own key by writing 32 new random bytes to another secret and referencing it there."; /// Activate the candidate policy's hooks under one identity. Every /// destination and its signing material is resolved here, so a candidate @@ -254,7 +257,9 @@ fn refusing_audit() -> SchedulingAudit { Ok(()) } } - SchedulingAudit::new(AuditWriter::from_line_sink(Box::new(RefusingSink))) + SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(Box::new( + RefusingSink, + ))) } pub fn plan(config_path: &Path) -> Result { @@ -291,24 +296,30 @@ pub fn plan(config_path: &Path) -> Result { .iter() .map(|refusal| json!({"code": refusal_code(refusal), "message": refusal.to_string()})) .collect::>(); - // Apply resolves the candidate's hook destinations and signing material - // before it writes anything, so plan reports the same refusal. A key is - // resolved only to learn that it exists at a usable size, then dropped. - let hook_refusal = ActivatedHooks::check_destinations( + // Validate the candidate's signing inventory without changing the + // deployment. Use the same reminder activation as the serving runtime. + let delivery_refusal = match ActivatedHooks::activate_destination_bindings( &loaded.policy.hook_declarations(), &loaded.config.destinations.hooks, &loaded.resolver, - ) - .err(); - if let Some(error) = &hook_refusal { - refusals.push(json!({ - "code": HOOK_DESTINATIONS_CODE, - "message": format!( - "{error}; bind every destination the policy hooks name under destinations.hooks, \ - with an hmacSha256KeyRef that resolves to a key of at least 32 bytes, then plan again" - ), - })); - } + ) { + Ok(hooks) => activate_reminder_delivery( + loaded.config.destinations.reminders.as_ref(), + &hooks, + &loaded.resolver, + ) + .err() + .map(|message| json!({"code": REMINDER_DESTINATIONS_CODE, "message": message})), + Err(error) => { + let message = match error { + HookActivationError::SigningMaterial(message) => message, + _ => format!("{error}. {HOOK_DESTINATIONS_ACTION}"), + }; + Some(json!({"code": HOOK_DESTINATIONS_CODE, "message": message})) + } + }; + let delivery_ready = delivery_refusal.is_none(); + refusals.extend(delivery_refusal); Ok(json!({ "ok": true, "command": "plan", @@ -335,7 +346,7 @@ pub fn plan(config_path: &Path) -> Result { "retainedHookBindings": retained_hook_bindings, "runtimeRole": plan.runtime_role, "effectiveRoleMode": plan.effective_role_mode.map(RoleMode::as_str), - "changesPending": plan.changes_pending && hook_refusal.is_none(), + "changesPending": plan.changes_pending && delivery_ready, "refusals": refusals, })) } @@ -429,7 +440,7 @@ fn apply_audited( )) .context("opening the schedulingctl audit destination")?; let audit = match sink { - Some(sink) => SchedulingAudit::new(AuditWriter::from_line_sink(sink)), + Some(sink) => SchedulingAudit::new(AuditWriter::from_line_sink_without_posture(sink)), None => audit, }; let activation_id = Uuid::new_v4(); diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index e6c3251665..11c6694472 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -5,7 +5,8 @@ //! checks every project file offline, and with `--runtime-config` the //! runtime file too, `test` replays every fixture offline, `explain` //! publishes what the runtime would serve, `package` writes the deployment -//! identity the runtime verifies, `plan`, `apply`, and `status` activate a +//! identity the runtime verifies, `provision` creates the roles and the +//! database the runtime file names, `plan`, `apply`, and `status` activate a //! verified package on a deployment's database and report its activation //! ledger, `records apply` performs the one attributable operator write of a //! deployment's live environment records, and `intents` reads the delivery @@ -14,6 +15,7 @@ pub mod activation; pub mod intents; mod project; +mod provision; pub mod records; mod report; mod selected_binary; @@ -73,6 +75,8 @@ enum Command { Package(PackageArgs), /// Report what `apply` would do to a deployment's database, writing nothing. Plan(ActivationArgs), + /// Create the roles and the database the runtime file names, or print the SQL. + Provision(registry_platform_provision::ProvisionArgs), /// Activate the verified package on a deployment's database. Apply(ApplyArgs), /// Report the active package and the activation ledger of a deployment's database. @@ -326,6 +330,7 @@ where Command::Serve(args) => { return serve(args, format, format_requested, stdout, stderr); } + Command::Provision(args) => return provision(&args, format), command => command, }; let command_name = command_path(&command); @@ -416,6 +421,7 @@ fn command_path(command: &Command) -> &'static str { Command::Explain(_) => "explain", Command::Package(_) => "package", Command::Plan(_) => "plan", + Command::Provision(_) => "provision", Command::Apply(_) => "apply", Command::Status(_) => "status", Command::Records(RecordsArgs { @@ -425,12 +431,32 @@ fn command_path(command: &Command) -> &'static str { } } +/// Runs the shared `provision` command, which writes its own report and sets +/// its own exit code. The global `--format` selects its report as it selects +/// every other command's. +fn provision(args: ®istry_platform_provision::ProvisionArgs, format: OutputFormat) -> ExitCode { + let shared = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + registry_platform_provision::run_provision( + "schedulingctl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + shared, + provision::load, + ) +} + fn run(cli: Cli) -> Result { match cli.command { Command::Api(_) | Command::Connection { .. } => { unreachable!("API commands handle their output before report dispatch") } Command::Serve(_) => unreachable!("serve replaces the ctl process before report dispatch"), + Command::Provision(_) => { + unreachable!("provision writes its own report before report dispatch") + } Command::Init(args) => project::init(&args.project, &args.template), Command::Check(args) => { let checked = if args.runtime_config.is_some() { @@ -790,7 +816,7 @@ fn classify_failure(error: &anyhow::Error) -> (u8, Value) { "artifact": "runtime-configuration", "path": "destinations.hooks", "message": format!("{error:#}"), - "suggestedAction": "Bind every destination the policy hooks name under destinations.hooks, with an hmacSha256KeyRef that resolves to a key of at least 32 bytes, then retry.", + "suggestedAction": activation::HOOK_DESTINATIONS_ACTION, }), ); } @@ -1345,13 +1371,23 @@ mod tests { #[test] fn a_hook_destination_apply_cannot_run_is_the_refusal_plan_reports() { - let refused = anyhow::Error::new(HookActivationError::InvalidSigningMaterial) - .context("activating the candidate policy's hook destinations"); + let refused = anyhow::Error::new(HookActivationError::SigningMaterial( + "destinations.hooks.appointment-events.hmacSha256KeyRef has 65 bytes".to_owned(), + )) + .context("activating the candidate policy's hook destinations"); let (exit, diagnostic) = classify_failure(&refused); assert_eq!(exit, DOMAIN_REFUSAL_EXIT); assert_eq!(diagnostic["code"], activation::HOOK_DESTINATIONS_CODE); assert_eq!(diagnostic["artifact"], "runtime-configuration"); assert_eq!(diagnostic["path"], "destinations.hooks"); + assert!(diagnostic["message"] + .as_str() + .unwrap() + .contains("destinations.hooks.appointment-events.hmacSha256KeyRef has 65 bytes")); + assert_eq!( + diagnostic["suggestedAction"], + activation::HOOK_DESTINATIONS_ACTION + ); } #[test] @@ -1374,7 +1410,9 @@ mod tests { } } let audit = registry_scheduling::audit::SchedulingAudit::new( - registry_platform_audit::AuditWriter::from_line_sink(Box::new(Refusing)), + registry_platform_audit::AuditWriter::from_line_sink_without_posture(Box::new( + Refusing, + )), ); // A stream append waits on the Tokio timer. let unavailable = tokio::runtime::Builder::new_current_thread() diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs new file mode 100644 index 0000000000..b31f2fa7de --- /dev/null +++ b/crates/registry-schedulingctl/src/provision.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision`: the shared command over Scheduling's +//! runtime file. The file's two database URLs name the roles, the database +//! and both passwords, so nothing is written twice. + +use std::path::Path; + +use registry_platform_config::describe_secret_failure; +use registry_platform_provision::{ProductDatabase, ProvisionInput, SchemaLayout}; +use registry_platform_yaml::Diagnostic; +use registry_scheduling::config::{startup_report, RuntimeConfig}; +use registry_scheduling_core::SCHEDULING_RUNTIME_KIND; +use zeroize::Zeroizing; + +/// Scheduling keeps its tables in `public`. `provision` gives the migration role +/// USAGE and CREATE on it and the runtime role USAGE, directly. It needs no +/// extension. +fn product() -> ProductDatabase { + ProductDatabase { + product: "scheduling", + layout: SchemaLayout::PublicForMigration, + btree_gist: false, + spatial: None, + } +} + +fn refused(code: &str, path: &str, message: String, action: &str) -> Box { + let mut diagnostic = Diagnostic::error(code, path, message, action); + diagnostic.artifact = Some(SCHEDULING_RUNTIME_KIND.to_owned()); + Box::new(diagnostic) +} + +/// Reads the runtime file exactly as `apply` does and resolves the two +/// database URLs and the CA behind `database.caBundleRef`. +pub(crate) fn load(path: &Path) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| { + refused( + "config.unresolvable", + "arguments", + "the --runtime-config path could not be resolved against the working directory" + .to_owned(), + "Pass --runtime-config as a path that exists.", + ) + })?; + let config = RuntimeConfig::load(&absolute).map_err(|error| { + match startup_report(&absolute, &error) + .and_then(|report| report.diagnostics().first().cloned()) + { + Some(diagnostic) => Box::new(diagnostic), + None => refused( + "config.refused", + "", + error.to_string(), + "Correct the runtime file, then run provision again.", + ), + } + })?; + let secrets = config.secret_providers.resolver().map_err(|error| { + refused( + "config.refused", + "/secretProviders", + error.to_string(), + "Correct secretProviders in the runtime file, then run provision again.", + ) + })?; + let resolve = |member: &str, reference: &str| { + secrets.resolve(reference).map_err(|error| { + refused( + "config.refused", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + "Check the secret provider and that the secret exists, then run provision again.", + ) + }) + }; + let url = |member: &str, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refused( + "config.refused", + &format!("/database/{member}"), + format!("database.{member} is not UTF-8 text"), + "Put a PostgreSQL URL in the secret, then run provision again.", + ) + }) + }; + let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; + let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let ca_pem = config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve("caBundleRef", reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()); + Ok(ProvisionInput { + product: product(), + migration_url, + runtime_url, + ca_pem, + }) +} diff --git a/crates/registry-schedulingctl/tests/activation_postgres.rs b/crates/registry-schedulingctl/tests/activation_postgres.rs index d557442899..a9c596e615 100644 --- a/crates/registry-schedulingctl/tests/activation_postgres.rs +++ b/crates/registry-schedulingctl/tests/activation_postgres.rs @@ -398,7 +398,10 @@ async fn plan_on_an_empty_database_reports_the_initial_activation_and_writes_not assert!(report["activePackage"].is_null(), "{report}"); assert_eq!(report["databaseIdCheck"], "initial"); assert_eq!(report["schemaVersion"], 0); - assert_eq!(report["pendingSchemaVersions"], serde_json::json!([200])); + assert_eq!( + report["pendingSchemaVersions"], + serde_json::json!([200, 201]) + ); assert_eq!(report["policy"]["revisionAdvances"], true); assert_eq!(report["policy"]["revision"], 2); assert_eq!(report["retainedHookBindings"], "none-retained"); @@ -445,13 +448,26 @@ async fn plan_reports_a_hook_destination_apply_cannot_sign_for() { "schedulingctl.activation.hook-destinations" ); let message = refusals[0]["message"].as_str().unwrap(); - assert!(message.contains("signing secret"), "{message}"); + let path = "destinations.hooks.appointment-events.hmacSha256KeyRef"; + let reason = if key.is_some() { + "9 bytes" + } else { + "the referenced secret is unavailable" + }; + assert!(message.contains(path), "{message}"); + assert!(message.contains(reason), "{message}"); + let action = if key.is_some() { + "Supply 32 to 64 exact key bytes." + } else { + "Create the secret under the configured provider, or correct the name." + }; + assert!(message.ends_with(action), "{message}"); assert!(!report.to_string().contains("too-short"), "{report}"); let refused = apply(&config).expect_err("apply refuses the same destination"); - assert!( - format!("{refused:#}").contains("signing secret"), - "{refused:#}" - ); + let message = format!("{refused:#}"); + assert!(message.contains(path), "{message}"); + assert!(message.contains(reason), "{message}"); + assert!(!message.contains("too-short"), "{message}"); assert_eq!(deployment.tables().await, 0, "apply created a table"); } @@ -463,6 +479,43 @@ async fn plan_reports_a_hook_destination_apply_cannot_sign_for() { deployment.drop().await; } +#[tokio::test] +async fn plan_refuses_invalid_reminder_keys_and_keys_shared_with_observers() { + let deployment = Deployment::single("activation_plan_reminder_keys").await; + let package = deployment.package("package", POLICY); + let observer_secret = format!("{}_OBSERVER_KEY", deployment.audit_secret); + let reminder_secret = format!("{}_REMINDER_KEY", deployment.audit_secret); + let config = deployment.config("runtime.yaml", &package, ConfigOptions::default()); + let mut text = std::fs::read_to_string(&config).unwrap(); + text.push_str(&format!( + "destinations:\n hooks:\n appointment-events:\n url: http://127.0.0.1:9/events\n hmacSha256KeyRef: secret:env/{observer_secret}\n reminders:\n url: http://127.0.0.1:9/reminders\n hmacSha256KeyRef: secret:env/{reminder_secret}\n" + )); + std::fs::write(&config, text).unwrap(); + let first = "destinations.reminders.hmacSha256KeyRef"; + let second = "destinations.hooks.appointment-events.hmacSha256KeyRef"; + std::env::set_var(&observer_secret, "k".repeat(32)); + for (size, expected) in [ + (31, format!("{first} has 31 bytes (trailing newline: false). Supply 32 to 64 exact key bytes.")), + (32, format!("{first} and {second} resolve to the same key bytes. Give {second} its own key by writing 32 new random bytes to another secret and referencing it there.")), + ] { + std::env::set_var(&reminder_secret, "k".repeat(size)); + let report = plan(&config); + assert_eq!(report["changesPending"], false, "{report}"); + let refusals = report["refusals"].as_array().unwrap(); + assert_eq!(refusals.len(), 1, "{report}"); + assert_eq!(refusals[0]["code"], "schedulingctl.activation.reminder-destinations"); + assert_eq!(refusals[0]["message"], expected); + } + std::env::set_var(&reminder_secret, "r".repeat(32)); + let report = plan(&config); + assert_eq!(report["changesPending"], true, "{report}"); + assert_eq!(report["refusals"], serde_json::json!([])); + std::env::remove_var(&observer_secret); + std::env::remove_var(&reminder_secret); + assert_eq!(deployment.tables().await, 0, "plan created a table"); + deployment.drop().await; +} + #[tokio::test] async fn apply_records_one_row_per_activation_and_a_previous_package_is_a_new_row() { let deployment = Deployment::single("activation_history").await; @@ -490,7 +543,10 @@ async fn apply_records_one_row_per_activation_and_a_previous_package_is_a_new_ro .as_str() .unwrap() .starts_with("single-role mode")); - assert_eq!(initial["schemaVersionsApplied"], serde_json::json!([200])); + assert_eq!( + initial["schemaVersionsApplied"], + serde_json::json!([200, 201]) + ); assert_eq!(initial["effects"]["schedulingIdAdopted"], true); assert_eq!(initial["effects"]["policyRevision"], 2); assert_eq!(initial["effects"]["policyRevisionAdvanced"], true); @@ -586,7 +642,7 @@ async fn apply_records_one_row_per_activation_and_a_previous_package_is_a_new_ro assert_eq!(history[2]["planKind"], "successor"); assert_eq!(history[0]["roleMode"], "single"); assert!(history[0]["runtimeRole"].is_string(), "{report}"); - assert_eq!(report["schemaVersion"], 200); + assert_eq!(report["schemaVersion"], 201); assert_eq!(report["roleMode"], "single"); assert!(report["roleModeStatement"].is_string()); deployment.drop().await; @@ -633,7 +689,10 @@ async fn successor_activation_checks_retained_hook_bindings_on_the_version_100_b ); let initial = apply(&initial_config).expect("the initial package activates"); - assert_eq!(initial["schemaVersionsApplied"], serde_json::json!([200])); + assert_eq!( + initial["schemaVersionsApplied"], + serde_json::json!([200, 201]) + ); assert_eq!(initial["applyOrder"], 1); let config = RuntimeConfig::load(&initial_config).expect("the runtime configuration loads"); @@ -1616,10 +1675,10 @@ async fn denied(client: &tokio_postgres::Client, statement: &str) -> bool { } const LEDGER_INSERT: &str = "INSERT INTO scheduling_activations(activation_id, apply_order, \ - package_digest, database_id, plan_kind, applied_at, role_mode, runtime_role) \ + package_digest, database_id, plan_kind, applied_at, role_mode, runtime_role, posture) \ VALUES(gen_random_uuid(), 99, \ 'sha256:0000000000000000000000000000000000000000000000000000000000000000', \ - 'scheduling-activation-test', 'initial', now(), 'split', 'intruder')"; + 'scheduling-activation-test', 'initial', now(), 'split', 'intruder', 'production')"; #[tokio::test] async fn a_runtime_role_that_can_write_the_ledger_is_refused_at_startup_until_apply_reissues_its_grants( diff --git a/crates/registry-schedulingctl/tests/provision_cli.rs b/crates/registry-schedulingctl/tests/provision_cli.rs new file mode 100644 index 0000000000..6f6addbe10 --- /dev/null +++ b/crates/registry-schedulingctl/tests/provision_cli.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision` without a database: print mode reads the runtime +//! file and writes the script without connecting or printing a password, and +//! the administrator flags refuse the combinations the shared command +//! refuses. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::Path; +use std::process::{Command, Output}; + +const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; +const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; + +/// A runtime file over a built package, whose secret files name a migration +/// and a runtime login on one server that does not exist, so a connection +/// attempt could only fail. +fn write_runtime(directory: &Path) -> String { + let secrets = directory.join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + for (name, value) in [ + ( + "migration-database-url", + format!( + "postgresql://scheduling_migration:{MIGRATION_PASSWORD}@db.invalid:5432/scheduling" + ), + ), + ( + "runtime-database-url", + format!( + "postgresql://scheduling_runtime:{RUNTIME_PASSWORD}@db.invalid:5432/scheduling" + ), + ), + ("audit-key", "5a".repeat(16)), + ( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#.to_owned(), + ), + ] { + let path = secrets.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + // The loader verifies the package the file names, as `apply` does. + let project = directory.join("project"); + let package = directory.join("package"); + for arguments in [ + vec![ + "init", + project.to_str().unwrap(), + "--template", + "standalone-exact-time", + ], + vec![ + "package", + project.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ], + ] { + let output = ctl(&arguments); + assert_eq!(output.status.code(), Some(0), "{arguments:?}"); + } + let runtime = directory.join("runtime.yaml"); + std::fs::write( + &runtime, + format!( + "\ +apiVersion: id.registrystack.org/formats/scheduling/runtime/v1alpha1 +kind: SchedulingRuntimeConfig +package: + root: {package} +identity: + databaseId: registry-scheduling-ctl-test +listener: + bind: 127.0.0.1:0 + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:scheduling + allowedClients: [scheduling-test-client] + jwksSource: + type: static + documentRef: secret:file/jwks.json +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url +taskGrantStatus: unchecked-final-fifteen-minutes +audit: + path: {audit} + hashKeyRef: secret:file/audit-key +retention: + receiptRetentionDays: 2 +", + package = package.display(), + secrets = secrets.display(), + audit = directory.join("audit.ndjson").display(), + ), + ) + .unwrap(); + runtime.display().to_string() +} + +fn ctl(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_schedulingctl")) + .args(arguments) + .output() + .unwrap() +} + +fn scratch() -> tempfile::TempDir { + tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap() +} + +#[test] +fn print_sql_writes_the_script_and_no_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!(stderr.is_empty(), "{stderr}"); + for name in ["scheduling_migration", "scheduling_runtime"] { + assert!(stdout.contains(name), "the script names {name}: {stdout}"); + } + assert!( + stdout.contains("CREATE DATABASE \"scheduling\""), + "{stdout}" + ); + assert!(stdout.contains("CREATE ROLE"), "{stdout}"); + assert!(stdout.contains("\\password"), "{stdout}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the script holds no password"); + } +} + +#[test] +fn print_sql_as_json_reports_nothing_executed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(report["command"], "provision"); + assert_eq!(report["product"], "scheduling"); + assert_eq!(report["executed"], false); + assert_eq!(report["status"], "complete"); + assert_eq!(report["database"], "scheduling"); + for statement in report["statements"].as_array().unwrap() { + assert_eq!(statement["outcome"], "not-run", "{statement}"); + } + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!stdout.contains(secret), "the report holds no password"); + } + + // The command's own flag, after the verb, selects the same report. + let after = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--format", + "json", + ]); + assert_eq!(after.status.code(), Some(0)); + assert_eq!(String::from_utf8(after.stdout).unwrap(), stdout); +} + +#[test] +fn both_administrator_flags_are_refused() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + for (arguments, message) in [ + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + "/nonexistent/admin-url", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + "conflicting use of --admin-url-file", + ), + ( + vec![ + "provision", + "--runtime-config", + &runtime, + "--print-sql", + "--admin-url-env", + "SCHEDULING_ADMIN_URL", + ], + "conflicting use of --print-sql", + ), + ( + vec!["provision", "--runtime-config", &runtime], + "missing required argument --admin-url-file, --admin-url-env", + ), + ] { + let output = ctl(&arguments); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{arguments:?}: {stderr}"); + assert!(output.stdout.is_empty(), "{arguments:?}"); + assert!(stderr.contains(message), "{arguments:?}: {stderr}"); + } +} + +/// Runs `provision --print-sql --format json` over the runtime file and +/// returns the exit code, the first diagnostic and the whole output. +fn refusal(runtime: &str) -> (Option, serde_json::Value, String) { + let output = ctl(&[ + "provision", + "--runtime-config", + runtime, + "--print-sql", + "--format", + "json", + ]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + let report: serde_json::Value = + serde_json::from_str(&stdout).unwrap_or_else(|error| panic!("{error}: {stdout}{stderr}")); + let diagnostic = report["diagnostics"][0].clone(); + ( + output.status.code(), + diagnostic, + format!("{stdout}{stderr}"), + ) +} + +fn assert_refused_at( + (code, diagnostic, output): (Option, serde_json::Value, String), + path: &str, +) { + assert_eq!(code, Some(1), "{output}"); + assert_eq!(diagnostic["code"], "config.refused", "{output}"); + assert_eq!(diagnostic["path"], path, "{output}"); + for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { + assert!(!output.contains(secret), "the refusal holds no password"); + } +} + +#[test] +fn a_missing_runtime_url_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); +} + +#[test] +fn a_missing_migration_url_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/migration-database-url")).unwrap(); + assert_refused_at(refusal(&runtime), "/database/migrationUrlRef"); +} + +#[test] +fn a_runtime_url_secret_that_is_not_text_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let path = directory.path().join("secrets/runtime-database-url"); + let mut bytes = RUNTIME_PASSWORD.as_bytes().to_vec(); + bytes.extend([0xff, 0xfe]); + std::fs::write(&path, bytes).unwrap(); + assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); +} + +#[test] +fn a_missing_ca_bundle_secret_is_refused_without_a_password() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let document = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = document.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/postgres-ca.pem\n", + ); + assert_ne!(document, with_ca, "the runtime file names the CA bundle"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_refused_at(refusal(&runtime), "/database/caBundleRef"); +} diff --git a/crates/registry-schedulingctl/tests/provision_postgres.rs b/crates/registry-schedulingctl/tests/provision_postgres.rs new file mode 100644 index 0000000000..cd5942f7fc --- /dev/null +++ b/crates/registry-schedulingctl/tests/provision_postgres.rs @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `schedulingctl provision` against a real server, then `apply` and the +//! runtime on what it created. +//! +//! `PROVISION_TEST_DATABASE_URL` names a disposable PostgreSQL 17 superuser +//! URL with `sslmode=verify-full`, and `PROVISION_TEST_DATABASE_CA` the PEM +//! file its certificate chains to. The administrator sessions of this suite +//! use verified TLS, so the server must offer it. Without the variables the +//! test fails on the spot: a skipped database test is not database +//! verification. +#![cfg(feature = "postgres-test")] + +use std::os::unix::fs::PermissionsExt as _; +use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +use registry_platform_provision::test_support::{connect_verified, provision_test_env}; +use serde_json::Value; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use uuid::Uuid; + +/// One deployment directory and the superuser session that creates the +/// roles `provision` is run from. +struct Deployment { + directory: tempfile::TempDir, + admin: tokio_postgres::Client, +} + +impl Deployment { + async fn new() -> Self { + let (url, ca_pem) = provision_test_env(); + let admin = connect_verified(&url, &ca_pem, None).await; + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let secrets = directory.path().join("secrets"); + std::fs::create_dir(&secrets).unwrap(); + std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); + let deployment = Self { directory, admin }; + deployment.secret("audit-key", &"5a".repeat(16)); + // The runtime verifies tokens against a static key set, so it starts + // without reaching the issuer. + deployment.secret( + "jwks.json", + r#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"}]}"#, + ); + deployment + } + + fn path(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + + fn runtime(&self) -> String { + self.path("runtime.yaml").display().to_string() + } + + /// Write or replace the secret file `name` with `value`. + fn secret(&self, name: &str, value: &str) { + let path = self.path("secrets").join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + /// Write the runtime document over `package`, listening on `bind`, with + /// the database connections verified against the CA secret. + fn write_runtime(&self, package: &std::path::Path, bind: &str) { + let document = format!( + "\ +apiVersion: id.registrystack.org/formats/scheduling/runtime/v1alpha1 +kind: SchedulingRuntimeConfig +package: + root: {package} +identity: + databaseId: registry-scheduling-ctl-test +listener: + bind: {bind} + tlsTermination: development-loopback +secretProviders: + file: + root: {secrets} +authentication: + oidc: + issuer: https://identity.example.test + audience: urn:example:scheduling + allowedClients: [scheduling-test-client] + jwksSource: + type: static + documentRef: secret:file/jwks.json +database: + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/postgres-ca.pem +taskGrantStatus: unchecked-final-fifteen-minutes +audit: + path: {audit} + hashKeyRef: secret:file/audit-key +retention: + receiptRetentionDays: 2 +", + package = package.display(), + secrets = self.path("secrets").display(), + audit = self.path("audit.ndjson").display(), + ); + std::fs::write(self.path("runtime.yaml"), document).unwrap(); + } +} + +/// Run the built binary with `--format json` and return its exit code and +/// report. +fn ctl(arguments: &[&str]) -> (i32, Value) { + let output = Command::new(env!("CARGO_BIN_EXE_schedulingctl")) + .args(["--format", "json"]) + .args(arguments) + .output() + .unwrap(); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("{error}: {}", String::from_utf8_lossy(&output.stdout))); + (output.status.code().unwrap(), report) +} + +/// Read one HTTP status code from `GET path`, or none when nothing answers. +async fn http_status(address: &str, path: &str) -> Option { + let mut stream = tokio::net::TcpStream::connect(address).await.ok()?; + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .ok()?; + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.ok()?; + let text = String::from_utf8_lossy(&response); + text.split_whitespace().nth(1)?.parse().ok() +} + +/// `provision` as the operate page runs it: from the administrator URL of a +/// non-superuser that holds only `CREATEROLE` and `CREATEDB`, over a runtime +/// file whose two URLs name the roles and the database. `apply` then +/// activates the package over the migration credential, and the runtime +/// starts over the runtime credential and answers its readiness route. +#[tokio::test] +async fn provision_then_apply_then_serve_with_split_roles() { + let deployment = Deployment::new().await; + let project = deployment.path("project").display().to_string(); + let (code, report) = ctl(&["init", &project, "--template", "standalone-exact-time"]); + assert_eq!(code, 0, "{report:#}"); + let package = deployment.path("package"); + let (code, report) = ctl(&["package", &project, "--output", package.to_str().unwrap()]); + assert_eq!(code, 0, "{report:#}"); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let bind = format!("127.0.0.1:{port}"); + deployment.write_runtime(&package, &bind); + let runtime = deployment.runtime(); + + let (base_url, ca) = provision_test_env(); + deployment.secret("postgres-ca.pem", &String::from_utf8_lossy(&ca)); + + let suffix = Uuid::new_v4().simple().to_string()[..8].to_owned(); + let (owner, migration, runtime_role, database) = ( + format!("scheduling_owner_{suffix}"), + format!("scheduling_mig_{suffix}"), + format!("scheduling_rt_{suffix}"), + format!("scheduling_db_{suffix}"), + ); + let password = |purpose: &str| format!("{purpose}-{}", Uuid::new_v4().simple()); + let (owner_password, migration_password, runtime_password) = ( + password("owner"), + password("migration"), + password("runtime"), + ); + deployment + .admin + .batch_execute(&format!( + "CREATE ROLE {owner} LOGIN PASSWORD '{owner_password}' NOSUPERUSER CREATEROLE CREATEDB" + )) + .await + .unwrap(); + + let base = registry_platform_provision::admin_config(&base_url, Some(&ca)) + .expect("PROVISION_TEST_DATABASE_URL is a valid administrator URL"); + let (host, port) = (base.host(), base.port()); + let url = |role: &str, password: &str, database: &str| { + format!("postgresql://{role}:{password}@{host}:{port}/{database}") + }; + deployment.secret( + "migration-database-url", + &url(&migration, &migration_password, &database), + ); + deployment.secret( + "runtime-database-url", + &url(&runtime_role, &runtime_password, &database), + ); + let admin_file = deployment.path("admin-url"); + std::fs::write(&admin_file, url(&owner, &owner_password, "postgres")).unwrap(); + std::fs::set_permissions(&admin_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let (code, provisioned) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{provisioned:#}"); + assert_eq!(provisioned["status"], "complete"); + assert_eq!(provisioned["executed"], true); + assert_eq!(provisioned["roleMode"], "split"); + assert_eq!(provisioned["database"], database.as_str()); + for secret in [&owner_password, &migration_password, &runtime_password] { + assert!( + !provisioned.to_string().contains(secret.as_str()), + "the report holds no password" + ); + } + + let (code, again) = ctl(&[ + "provision", + "--runtime-config", + &runtime, + "--admin-url-file", + admin_file.to_str().unwrap(), + ]); + assert_eq!(code, 0, "a second run converges: {again:#}"); + for statement in again["statements"].as_array().unwrap() { + assert_ne!( + statement["outcome"], "created", + "a second run creates nothing: {statement}" + ); + } + + let (code, applied) = ctl(&["apply", "--runtime-config", &runtime]); + assert_eq!(code, 0, "{applied:#}"); + assert_eq!(applied["roleMode"], "split"); + + let server = tokio::spawn({ + let runtime = runtime.clone(); + async move { registry_scheduling::runtime::serve_from_path(&runtime).await } + }); + let mut ready = None; + for _ in 0..300 { + if server.is_finished() { + break; + } + ready = http_status(&bind, "/readyz").await; + if ready == Some(200) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + if server.is_finished() { + let outcome = server.await.expect("the server task does not panic"); + panic!("the service stopped instead of serving: {outcome:?}"); + } + assert_eq!(ready, Some(200), "the service never reported ready"); + server.abort(); + + for statement in [ + format!("DROP DATABASE {database} WITH (FORCE)"), + format!("DROP ROLE {runtime_role}"), + format!("DROP ROLE {migration}"), + format!("DROP ROLE {owner}"), + ] { + deployment.admin.batch_execute(&statement).await.unwrap(); + } +} diff --git a/crates/registry-stack-client-node/README.md b/crates/registry-stack-client-node/README.md index 254a48dd1e..f78d91072c 100644 --- a/crates/registry-stack-client-node/README.md +++ b/crates/registry-stack-client-node/README.md @@ -125,13 +125,14 @@ attempt under the key was answered and may have committed: reconcile that attempt before choosing a new key. See [Unknown outcomes](https://docs.registrystack.org/reference/client-api/#unknown-outcomes-and-the-same-key-retry). -`breg.verifyHookDelivery({ method, path, headers, body, key })` authenticates -the exact bytes of one Version 1 hook delivery. The result returns -`deliveryTime` and `idempotencyKey`; the receiver must bound clock skew and -deduplicate once-only effects on authenticated `source` plus `id`, or on an -application business key. See +`breg.verifyHookDelivery({ headers, body, key, previousKey })` authenticates a +Standard Webhooks delivery and returns its event attributes, signed Unix seconds +as a decimal string, and exact body. The optional previous key supports rotation. +The default freshness window is 300 seconds in either direction. Choose +`maxSkewSeconds` (1 to 3600) for a custom window or `callerEnforcedFreshness: true` +to enforce the window yourself. Deduplicate on authenticated `source` and `id`. [Verify a hook delivery](https://docs.registrystack.org/reference/client-api/#verify-a-hook-delivery) -for a receiver example. +shows a receiver example. ## Versioning diff --git a/crates/registry-stack-client-node/__test__/facade.test-d.ts b/crates/registry-stack-client-node/__test__/facade.test-d.ts index e24a697d68..49cda74e0a 100644 --- a/crates/registry-stack-client-node/__test__/facade.test-d.ts +++ b/crates/registry-stack-client-node/__test__/facade.test-d.ts @@ -47,12 +47,11 @@ void bregClient.registryContract('reader').then((metadata) => { } }) breg.verifyHookDelivery({ - method: 'POST', - path: '/hooks/registry', - headers: { 'X-Registry-Signature': 'v1=opaque' }, + headers: { 'webhook-signature': 'v1,opaque' }, body: Buffer.from('{}'), key: Buffer.alloc(32), -}).deliveryTime.toUpperCase() + previousKey: Buffer.alloc(32, 1), +}).timestamp.toUpperCase() // @ts-expect-error Structural validation uses its explicit canonical name. void discovery.validateSelection declare const selection: discovery.EvidenceServiceSelection diff --git a/crates/registry-stack-client-node/breg/client.d.ts b/crates/registry-stack-client-node/breg/client.d.ts index 4c283e7481..0c321103b2 100644 --- a/crates/registry-stack-client-node/breg/client.d.ts +++ b/crates/registry-stack-client-node/breg/client.d.ts @@ -14,40 +14,57 @@ export type SafeInteger = number export type HookVerificationRefusalCode = | 'missing-header' - | 'invalid-delivery-time' | 'duplicate-header' - | 'body-too-large' - | 'invalid-key' + | 'invalid-content-type' + | 'invalid-id' + | 'invalid-timestamp' + | 'stale-delivery' | 'malformed-signature' - | 'signature-mismatch' | 'unsupported-version' + | 'signature-mismatch' + | 'body-too-large' + | 'invalid-key' + | 'invalid-envelope' + | 'id-mismatch' export interface HookDeliveryInput { - method: string - path: string headers: Readonly> /** Exact bytes in a non-shared backing store. */ body: Buffer /** Secret bytes in a non-shared backing store. */ key: Buffer + /** Previous secret bytes during key rotation, in a non-shared backing store. */ + previousKey?: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. With + * neither this nor `callerEnforcedFreshness`, the window is 300 seconds. + * Cannot be combined with `callerEnforcedFreshness`. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed. The caller enforces its + * own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } export interface VerifiedHookDelivery { readonly id: string + /** Signed Unix seconds as a decimal string. */ + readonly timestamp: string readonly source: string readonly type: string readonly time: string readonly dataschema: string - readonly generation: string - readonly attempt: string - readonly deliveryTime: string - readonly idempotencyKey: string readonly body: Buffer } /** - * Authenticate one exact Base Registry Engine Version 1 hook delivery. - * Apply delivery-time skew and idempotency policy before acting on the body. + * Authenticate one exact Base Registry Engine Standard Webhooks delivery. The + * delivery time must be within 300 seconds of the receiver clock unless + * `maxSkewSeconds` or `callerEnforcedFreshness` says otherwise; a time outside + * the window is refused with code `stale-delivery`. Deduplicate on source and id + * before acting on the body. */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-stack-client-node/breg/client.js b/crates/registry-stack-client-node/breg/client.js index c5af4483ca..d5fe4108a0 100644 --- a/crates/registry-stack-client-node/breg/client.js +++ b/crates/registry-stack-client-node/breg/client.js @@ -64,7 +64,7 @@ function inputError(kind) { }); } -function plainDataObject(value, expectedFields) { +function plainDataObject(value, expectedFields, optionalFields = []) { if (value === null || typeof value !== 'object' || Array.isArray(value) || isProxy(value)) { throw inputError('invalid-request'); } @@ -72,10 +72,10 @@ function plainDataObject(value, expectedFields) { if (prototype !== Object.prototype && prototype !== null) throw inputError('invalid-request'); const keys = Reflect.ownKeys(value); if (keys.some((key) => typeof key !== 'string') - || keys.length !== expectedFields.length - || keys.some((key) => !expectedFields.includes(key))) throw inputError('invalid-request'); + || keys.some((key) => !expectedFields.includes(key) && !optionalFields.includes(key)) + || expectedFields.some((field) => !keys.includes(field))) throw inputError('invalid-request'); const result = Object.create(null); - for (const field of expectedFields) { + for (const field of keys) { const descriptor = Object.getOwnPropertyDescriptor(value, field); if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { throw inputError('invalid-request'); @@ -107,15 +107,24 @@ function hookHeaders(value) { function verifyHookDelivery(value) { try { - const input = plainDataObject(value, ['method', 'path', 'headers', 'body', 'key']); - if (typeof input.method !== 'string' || typeof input.path !== 'string' - || !Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) - || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer)) { + const input = plainDataObject( + value, + ['headers', 'body', 'key'], + ['previousKey', 'maxSkewSeconds', 'callerEnforcedFreshness'], + ); + if (!Buffer.isBuffer(input.body) || !Buffer.isBuffer(input.key) + || isSharedArrayBuffer(input.body.buffer) || isSharedArrayBuffer(input.key.buffer) + || (input.previousKey !== undefined && (!Buffer.isBuffer(input.previousKey) + || isSharedArrayBuffer(input.previousKey.buffer))) + || (input.maxSkewSeconds !== undefined && !Number.isSafeInteger(input.maxSkewSeconds)) + || (input.callerEnforcedFreshness !== undefined + && typeof input.callerEnforcedFreshness !== 'boolean')) { throw inputError('invalid-request'); } input.headers = hookHeaders(input.headers); input.body = Buffer.from(input.body); input.key = Buffer.from(input.key); + if (input.previousKey !== undefined) input.previousKey = Buffer.from(input.previousKey); return native.verifyHookDelivery(input); } catch (error) { throw normalize(error, 'invalid-request'); diff --git a/crates/registry-stack-client-node/breg/index.d.ts b/crates/registry-stack-client-node/breg/index.d.ts index 2d308a4fbd..05e3fe4270 100644 --- a/crates/registry-stack-client-node/breg/index.d.ts +++ b/crates/registry-stack-client-node/breg/index.d.ts @@ -368,11 +368,21 @@ export declare function eventRecordView(argumentsJson: string): string /** Exact BReg hook request supplied by a receiver. */ export interface HookDeliveryInput { - method: string - path: string headers: Record body: Buffer key: Buffer + previousKey?: Buffer + /** + * Window around the receiver clock, in whole seconds from 1 to 3600. + * With neither this nor `callerEnforcedFreshness`, the window is 300 + * seconds. + */ + maxSkewSeconds?: number + /** + * Check only that the delivery time is well formed; the caller enforces + * its own window. Cannot be combined with `maxSkewSeconds`. + */ + callerEnforcedFreshness?: boolean } /** Validated product result serialized before the JavaScript number boundary. */ @@ -414,16 +424,18 @@ export interface RawOutcome { /** Authenticated BReg hook metadata and exact body. */ export interface VerifiedHookDelivery { id: string + timestamp: string source: string type: string time: string dataschema: string - generation: string - attempt: string - deliveryTime: string - idempotencyKey: string body: Buffer } -/** Verify a BReg Version 1 hook signature without applying receiver policy. */ +/** + * Verify a BReg Standard Webhooks delivery. The delivery time must fall within + * 300 seconds of the receiver clock unless `maxSkewSeconds` or + * `callerEnforcedFreshness` says otherwise. Deduplication stays with the + * caller. + */ export declare function verifyHookDelivery(input: HookDeliveryInput): VerifiedHookDelivery diff --git a/crates/registry-stack-client-node/scheduling/client.d.ts b/crates/registry-stack-client-node/scheduling/client.d.ts index 85c57ef2f3..4978b07c7a 100644 --- a/crates/registry-stack-client-node/scheduling/client.d.ts +++ b/crates/registry-stack-client-node/scheduling/client.d.ts @@ -316,6 +316,7 @@ export type SchedulingProblemCode = | 'cursor.expired' | 'cursor.invalid' | 'eligibility.unavailable' + | 'grant.lifetime-too-long' | 'hold.expired' | 'hold.released' | 'hook.unavailable' diff --git a/crates/registry-stack-client/src/lib.rs b/crates/registry-stack-client/src/lib.rs index 7f16c860c1..7135bf53be 100644 --- a/crates/registry-stack-client/src/lib.rs +++ b/crates/registry-stack-client/src/lib.rs @@ -6,8 +6,8 @@ pub mod breg { pub use registry_breg_client::{ event_record_view, event_record_view_from_json, verify_hook_delivery, - BRegActionApplication, BRegActionBinding, BRegActionBounds, BRegActionDescriptor, - BRegActionError, BRegActionInputBinding, BRegActionInputDescriptor, + verify_hook_delivery_at, BRegActionApplication, BRegActionBinding, BRegActionBounds, + BRegActionDescriptor, BRegActionError, BRegActionInputBinding, BRegActionInputDescriptor, BRegActionInvocationRequest, BRegActionMode, BRegActionReceipt, BRegActionReferenceInputDescriptor, BRegActionResultEffectDescriptor, BRegActionResultReference, BRegActionReview, BRegActionTargetConditions, @@ -15,22 +15,22 @@ pub mod breg { BRegContinuation, BRegContinuationProjection, BRegCreateBinding, BRegCreateRequest, BRegCreationRevision, BRegDirectWrite, BRegEtag, BRegEventRecordDescriptor, BRegEventRecordError, BRegEventRecordEvidence, BRegEventRecordView, BRegHookDelivery, - BRegHookVerificationError, BRegIdempotencyKey, BRegListRequest, BRegLookupRequest, - BRegMetadata, BRegMetadataOperation, BRegMetadataSelectionError, BRegMutationRequestError, - BRegOperationKind, BRegPage, BRegPatchBinding, BRegPatchBuilder, BRegPatchRequest, - BRegPreparedAction, BRegPreparedCreate, BRegPreparedProposal, BRegProbeStatus, - BRegProblemCode, BRegProposal, BRegProposalApplication, BRegProposalAttachment, - BRegProposalAttachmentValue, BRegProposalCollection, BRegProposalDecision, - BRegProposalDecisionStatus, BRegProposalGetBinding, BRegProposalLink, BRegProposalPage, - BRegProposalQuery, BRegProposalResultReference, BRegProposalReviewBinding, - BRegProposalReviewContext, BRegProposalReviewDocument, BRegProposalReviewHandoff, - BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, BRegProposalReviewResult, - BRegProposalReviewSubject, BRegProposalState, BRegProposalSubmission, - BRegProposalSubmissionApplication, BRegProposalTurn, BRegProtocolFailure, BRegRawDocument, - BRegRecordFormat, BRegRecordOptions, BRegRecoveryHint, BRegRequestError, - BRegResponseMetadata, BRegVerifiedHookDelivery, BaseRegistryClient, - BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, ReviewProgressCode, - Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, + BRegHookFreshness, BRegHookVerificationError, BRegIdempotencyKey, BRegListRequest, + BRegLookupRequest, BRegMetadata, BRegMetadataOperation, BRegMetadataSelectionError, + BRegMutationRequestError, BRegOperationKind, BRegPage, BRegPatchBinding, BRegPatchBuilder, + BRegPatchRequest, BRegPreparedAction, BRegPreparedCreate, BRegPreparedProposal, + BRegProbeStatus, BRegProblemCode, BRegProposal, BRegProposalApplication, + BRegProposalAttachment, BRegProposalAttachmentValue, BRegProposalCollection, + BRegProposalDecision, BRegProposalDecisionStatus, BRegProposalGetBinding, BRegProposalLink, + BRegProposalPage, BRegProposalQuery, BRegProposalResultReference, + BRegProposalReviewBinding, BRegProposalReviewContext, BRegProposalReviewDocument, + BRegProposalReviewHandoff, BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, + BRegProposalReviewResult, BRegProposalReviewSubject, BRegProposalState, + BRegProposalSubmission, BRegProposalSubmissionApplication, BRegProposalTurn, + BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, + BRegRecoveryHint, BRegRequestError, BRegResponseMetadata, BRegVerifiedHookDelivery, + BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, + ReviewProgressCode, Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, }; } diff --git a/crates/registry-thunderid-tooling/Cargo.toml b/crates/registry-thunderid-tooling/Cargo.toml index 8951f1afdb..074165ce02 100644 --- a/crates/registry-thunderid-tooling/Cargo.toml +++ b/crates/registry-thunderid-tooling/Cargo.toml @@ -20,6 +20,7 @@ workspace = true base64.workspace = true getrandom.workspace = true registry-platform-config.workspace = true +registry-platform-loopback.workspace = true registry-platform-crypto = { workspace = true, optional = true } registry-platform-httputil = { workspace = true, optional = true } registry-platform-oidc = { workspace = true, optional = true } diff --git a/crates/registry-thunderid-tooling/src/description.rs b/crates/registry-thunderid-tooling/src/description.rs index 5a6ddb0ef5..734555dc4d 100644 --- a/crates/registry-thunderid-tooling/src/description.rs +++ b/crates/registry-thunderid-tooling/src/description.rs @@ -324,10 +324,32 @@ fn private_file_name(path: &std::path::Path) -> bool { .all(|part| matches!(part, std::path::Component::Normal(_))) } +/// A host a development profile may reach over plain HTTP: loopback, or the +/// name Docker gives the host machine. +fn development_host(host: &str) -> bool { + registry_platform_loopback::loopback_host(host).is_some() || host == "host.docker.internal" +} + +/// Whether an address names the development issuer's listener: a loopback +/// host in any spelling (a literal, its IPv4-mapped form or the name +/// `localhost`) on the listener's port, with no path or the root path. +fn names_development_listener(address: &str, port: u16) -> bool { + url::Url::parse(address).is_ok_and(|url| { + url.scheme() == "http" + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()) + && url.port() == Some(port) + && matches!(url.path(), "" | "/") + }) +} + fn local_url(value: &str) -> bool { url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" - && url.host_str() == Some("127.0.0.1") + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_literal(host).is_some()) && url.port().is_some_and(|port| port != 0) && url.username().is_empty() && url.password().is_none() @@ -619,20 +641,17 @@ impl IssuerDescription { && (url.scheme() == "https" || (development && url.scheme() == "http" - && matches!( - url.host_str(), - Some("127.0.0.1" | "localhost" | "host.docker.internal") - ))) + && url.host_str().is_some_and(development_host))) }); if !valid { return refuse("exchange issuer and JWKS URLs require HTTPS or an explicit development host"); } } - let own_issuer = match profile { - Profile::Development => format!("http://127.0.0.1:{}", self.port), - Profile::Deployment { issuer } => issuer.to_owned(), + let names_this_issuer = match profile { + Profile::Development => names_development_listener(&issuer.issuer, self.port), + Profile::Deployment { issuer: own } => issuer.issuer == own, }; - if issuer.issuer == own_issuer { + if names_this_issuer { return refuse("an external exchange issuer cannot name this issuer"); } } @@ -965,6 +984,86 @@ pub(crate) fn all_distinct(ids: impl IntoIterator) -> bool { mod tests { use super::*; + #[test] + fn local_urls_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", false), + ("LOCALHOST", false), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + local_url(&format!("http://{host}:3000")), + loopback, + "{host}" + ); + } + assert!(!local_url("http://127.0.0.1"), "a port is required"); + } + + #[test] + fn an_exchange_issuer_cannot_name_the_listener_in_any_loopback_spelling() { + let port = crate::testing::synthetic_description().port; + for host in [ + "127.0.0.1", + "127.0.0.2", + "[::1]", + "[::ffff:127.0.0.1]", + "localhost", + "LOCALHOST", + ] { + for path in ["", "/"] { + let mut description = exchange_description(); + description.exchange_issuers[0].issuer = format!("http://{host}:{port}{path}"); + description.exchange_issuers[0].jwks_endpoint = + format!("http://{host}:{port}/jwks"); + assert!( + matches!( + description.validate(), + Err(ToolingError::InvalidDescription { + reason: "an external exchange issuer cannot name this issuer" + }) + ), + "{host}{path}" + ); + } + } + let mut description = exchange_description(); + description.exchange_issuers[0].issuer = format!("http://127.0.0.1:{}", port + 1); + description.exchange_issuers[0].jwks_endpoint = + format!("http://127.0.0.1:{}/jwks", port + 1); + assert!( + description.validate().is_ok(), + "another loopback port is another issuer" + ); + } + + #[test] + fn development_hosts_are_loopback_or_the_docker_host_name() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!(development_host(host), loopback, "{host}"); + } + assert!(development_host("host.docker.internal")); + assert!(!development_host("host.docker.internal.")); + } + pub(super) fn exchange_description() -> IssuerDescription { let mut description = crate::testing::synthetic_description(); description.exchange_issuers.push(ExchangeIssuer { @@ -984,6 +1083,20 @@ mod tests { description } + /// This crate keeps its own member list so the checks-only build links no + /// signing library. It must stay the platform's list. + #[test] + fn the_private_member_list_is_the_platform_list() { + assert_eq!( + PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>(), + registry_platform_crypto::PRIVATE_JWK_MEMBERS + .into_iter() + .collect::>() + ); + } + #[test] fn a_machine_clients_jwks_may_carry_no_private_key_material() { for member in PRIVATE_JWK_MEMBERS { diff --git a/crates/registry-thunderid-tooling/src/grant.rs b/crates/registry-thunderid-tooling/src/grant.rs index 3baddfc13c..009eb26948 100644 --- a/crates/registry-thunderid-tooling/src/grant.rs +++ b/crates/registry-thunderid-tooling/src/grant.rs @@ -41,7 +41,9 @@ fn endpoint(address: &str) -> Result { || url.fragment().is_some() || !(url.scheme() == "https" || (url.scheme() == "http" - && matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")))) + && url + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some()))) || url.host_str().is_none() { return Err(refused( @@ -147,7 +149,7 @@ pub async fn acquire( "Casework refused the grant; check its approval, client, expiry and revocation", )); } - registry_platform_httputil::validate_response_headers(response.headers()) + registry_platform_httputil::validate_response_headers_without_peer_policy(response.headers()) .map_err(|_| refused("the Casework assertion headers exceed their bounds"))?; if response .headers() @@ -216,6 +218,28 @@ mod tests { scopes: vec!["records:get".into()], } } + #[test] + fn plain_http_endpoints_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!( + endpoint(&format!("http://{host}:8100")).is_ok(), + loopback, + "{host}" + ); + } + } + #[test] fn connection_refuses_ambiguous_or_unprotected_endpoints_and_scopes() { assert!(connection().validate().is_ok()); diff --git a/crates/registry-thunderid-tooling/src/grant_file.rs b/crates/registry-thunderid-tooling/src/grant_file.rs index 4effa06c8b..f7252bc2be 100644 --- a/crates/registry-thunderid-tooling/src/grant_file.rs +++ b/crates/registry-thunderid-tooling/src/grant_file.rs @@ -126,10 +126,7 @@ fn assertion_key( "no secret of the referenced name exists under its provider", "Create the key file under secretProviders.file.root, or set the environment variable the reference names.", ), - SecretError::UnsafeFile => ( - "the referenced key file is not a regular file you own with mode 0400 or 0600 and a single link", - "Make the key file a regular file you own, with mode 0400 or 0600 and a single link.", - ), + SecretError::UnsafeFile(check) => (check.message(), check.suggested_action()), SecretError::InvalidValue => ( "the referenced secret is empty, holds a NUL byte, or is larger than 64 KiB", "Store the client's private assertion key as one JWK under this reference.", diff --git a/crates/registry-thunderid-tooling/src/identity_facts.rs b/crates/registry-thunderid-tooling/src/identity_facts.rs index 152b5ae716..845f8dca53 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts.rs @@ -479,14 +479,16 @@ pub(crate) fn https_url(value: &str) -> bool { }) } -/// An `https` URL, or `http` to 127.0.0.1, without user information, query -/// or fragment. A facts document may describe a development issuer. +/// An `https` URL, or `http` to a loopback address literal, without user +/// information, query or fragment. A facts document may describe a development issuer. fn issuer_url(value: &str) -> bool { https_url(value) || (Url::new(value).is_ok() && url::Url::parse(value).is_ok_and(|url| { url.scheme() == "http" - && url.host_str() == Some("127.0.0.1") + && url.host_str().is_some_and(|host| { + registry_platform_loopback::loopback_literal(host).is_some() + }) && url.username().is_empty() && url.password().is_none() && url.query().is_none() @@ -570,7 +572,7 @@ fn check(document: &Document, facts: &IdentityFacts) -> Vec { error( "/issuer", "identity.facts.invalid-issuer", - "the issuer is neither https nor http to 127.0.0.1, or carries user information, a query or a fragment", + "the issuer is neither https nor http to a loopback host, or carries user information, a query or a fragment", "Write the issuer URL the product trusts.", ); } diff --git a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs index a41d110a78..59c27f4ddc 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs @@ -528,3 +528,22 @@ fn every_set_list_refuses_a_repeat_at_the_repeat() { ); } } + +#[test] +fn an_http_issuer_follows_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", false), + ("LOCALHOST", false), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + assert_eq!(issuer_url(&format!("http://{host}:8091")), loopback, "{host}"); + } + assert!(issuer_url("https://id.registry.example")); +} diff --git a/crates/registry-thunderid-tooling/src/task_connection.rs b/crates/registry-thunderid-tooling/src/task_connection.rs index 3f5d7219d5..800e808cf8 100644 --- a/crates/registry-thunderid-tooling/src/task_connection.rs +++ b/crates/registry-thunderid-tooling/src/task_connection.rs @@ -122,7 +122,9 @@ fn valid_endpoint(url: &Url) -> bool { parsed.query().is_none() && parsed.fragment().is_none() && (url.is_https() - || matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))) + || parsed + .host_str() + .is_some_and(|host| registry_platform_loopback::loopback_host(host).is_some())) } fn valid_scope(scope: &str) -> bool { @@ -309,6 +311,25 @@ clients: - records:get "; + #[test] + fn plain_http_endpoints_follow_the_shared_loopback_rule() { + for (host, loopback) in [ + ("127.0.0.1", true), + ("127.0.0.2", true), + ("[::1]", true), + ("[::ffff:127.0.0.1]", true), + ("localhost", true), + ("LOCALHOST", true), + ("a.localhost", false), + ("localhost.", false), + ("10.0.0.1", false), + ("example.com", false), + ] { + let url = Url::new(format!("http://{host}:8090")).expect("a URL"); + assert_eq!(valid_endpoint(&url), loopback, "{host}"); + } + } + fn read(text: &str) -> Result, Report> { super::read("task-connection.yaml", text.as_bytes()).map(|_| Vec::new()) } diff --git a/deploy/helm/registry-stack/README.md b/deploy/helm/registry-stack/README.md index b6cc039a79..82887e1746 100644 --- a/deploy/helm/registry-stack/README.md +++ b/deploy/helm/registry-stack/README.md @@ -77,6 +77,11 @@ update. No BReg, Casework, or Evidence Pod sets `fsGroup`. Kubelet can otherwise recursively change an existing owner-only audit or authority volume root. +Because no Pod sets `fsGroup`, the chart stages each Secret into a memory-backed volume owned by +the runtime user at mode `0400`, which the runtime's secret-file rule accepts. A deployment without +owner-only volumes can mount the Secret directly with `defaultMode: 0440` and `fsGroup` instead, +which the rule also accepts. + ## BReg input contract Set these references when `breg.enabled` is true: diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index 7bb1a4ea8b..862c3cddd6 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -1043,6 +1043,7 @@ export default defineConfig({ items: [ { label: 'Architecture', slug: 'explanation/architecture' }, { label: 'Where each rule lives', slug: 'explanation/where-each-rule-lives' }, + { label: 'Where authority lives', slug: 'explanation/where-authority-lives' }, { label: 'Data minimization', slug: 'explanation/data-minimization-and-purpose-limitation' }, { label: 'DPI safeguards', slug: 'explanation/dpi-safeguards-alignment' }, { label: 'Retired products', slug: 'decisions/registry-relay-retirement-2026-10-03' }, @@ -1054,7 +1055,7 @@ export default defineConfig({ items: [ { label: 'Overview', slug: 'reference' }, { label: 'Errors and status codes', slug: 'reference/errors' }, - { label: 'Signed hook deliveries', slug: 'reference/delivery-signing' }, + { label: 'Receive signed deliveries', slug: 'reference/delivery-signing' }, { label: 'Environment variables', slug: 'reference/environment-variables' }, { label: 'Configuration files', slug: 'reference/configuration-files' }, { label: 'API overview', slug: 'reference/apis' }, diff --git a/docs/site/scripts/breg-event-reference.test.mjs b/docs/site/scripts/breg-event-reference.test.mjs index 6d918cb6ec..7609d7078f 100644 --- a/docs/site/scripts/breg-event-reference.test.mjs +++ b/docs/site/scripts/breg-event-reference.test.mjs @@ -80,8 +80,8 @@ test('Proposal payload fields match the closed native schema and omit retired re test('header lookup covers the exact platform event request header inventory', () => { const source = read('../../../crates/registry-platform-httputil/src/destination.rs'); - const start = source.indexOf('pub fn event_delivery('); - const end = source.indexOf('pub fn render_event(', start); + const start = source.indexOf('const SIGNED_EVENT_HEADERS'); + const end = source.indexOf('fn closed_signed_event_headers(', start); assert.ok(start >= 0 && end > start); const names = [...source.slice(start, end).matchAll(/name: "([^"]+)"/g)] .map((match) => match[1]).sort(); diff --git a/docs/site/scripts/check-messaging-tutorial.test.mjs b/docs/site/scripts/check-messaging-tutorial.test.mjs index 085c33e202..d3bbeafe40 100644 --- a/docs/site/scripts/check-messaging-tutorial.test.mjs +++ b/docs/site/scripts/check-messaging-tutorial.test.mjs @@ -118,7 +118,8 @@ test('the Author page replays in the tutorial project, after the tutorial', asyn // The local first run is fully executable with the supplied source binaries. // Hosted operation remains outside this gate, and every omitted fence is -// named so that the report does not overstate its coverage. +// named so that the report does not overstate its coverage. The installer +// fence carries its own test-skip reason on the page, so it is not counted. test('the gate executes the local journey and names the hosted fences it omits', async () => { const { code, output } = await runGate(); assert.equal(code, 0, output); @@ -133,8 +134,8 @@ test('the gate executes the local journey and names the hosted fences it omits', assert.deepEqual( [...new Set(hostedUnexecuted)], [ - 'Install the binaries', 'Check the runtime file', + 'Provision PostgreSQL', 'Record and serve the package', 'Operate messages', 'Erase expired data on demand', diff --git a/docs/site/scripts/evidence-gateway-docs.test.mjs b/docs/site/scripts/evidence-gateway-docs.test.mjs index 5d8d2e229e..d4310ce1e2 100644 --- a/docs/site/scripts/evidence-gateway-docs.test.mjs +++ b/docs/site/scripts/evidence-gateway-docs.test.mjs @@ -116,6 +116,11 @@ test('names exactly the metrics the OID4VCI delivery front end renders', () => { ); const rendered = new Set([...observability.matchAll(/"(evidence_oid4vci_\w+)"/g)].map((match) => match[1])); assert.ok(rendered.size > 0, 'expected observability.rs to name metric families'); + // The shared refusal recorder renders `_request_refusals_total` for + // the prefix the service gives it. + for (const match of observability.matchAll(/RefusalRecorder::new\("(evidence_oid4vci)"\)/g)) { + rendered.add(`${match[1]}_request_refusals_total`); + } const page = readFileSync(resolve(docsRoot, 'configure/evidence-oid4vci.mdx'), 'utf8'); const metricsSection = page.split(/^## Metrics$/m)[1]?.split(/^## /m)[0] ?? ''; diff --git a/docs/site/scripts/generate-cli-reference.mjs b/docs/site/scripts/generate-cli-reference.mjs index 971ab2fe3d..418000cc2b 100644 --- a/docs/site/scripts/generate-cli-reference.mjs +++ b/docs/site/scripts/generate-cli-reference.mjs @@ -33,6 +33,8 @@ export const expectedBinaries = [ 'caseworkctl', 'coordinator', 'coordinatorctl', + 'discovery', + 'discoveryctl', 'documents', 'documentsctl', 'evidence', @@ -77,6 +79,7 @@ const groups = [ { title: 'Registry Casework', binaries: ['casework', 'caseworkctl'] }, { title: 'Registry Scheduling', binaries: ['scheduling', 'schedulingctl'] }, { title: 'Registry Messaging', binaries: ['messaging', 'messagingctl'], product: 'registry-messaging' }, + { title: 'Registry Discovery', binaries: ['discovery', 'discoveryctl'] }, { title: 'Document Store', binaries: ['documents', 'documentsctl'], product: 'registry-documents' }, { title: 'Registry Evidence', binaries: ['evidence', 'evidencectl'] }, { title: 'Evidence credential delivery', binaries: ['evidence-oid4vci'] }, diff --git a/docs/site/src/content/docs/configure/adapter-jobs.mdx b/docs/site/src/content/docs/configure/adapter-jobs.mdx index 8f211969a4..47691269f6 100644 --- a/docs/site/src/content/docs/configure/adapter-jobs.mdx +++ b/docs/site/src/content/docs/configure/adapter-jobs.mdx @@ -25,7 +25,7 @@ Delivery is not approval, and approval is not application: a job reports what it It is also the buffer a retry reads again. Source data is not registry authority. - The Adapter ingestion job reads the source, compares items, maps for the direct destination, hands off, keeps the source position and reports status. - It holds a source credential and, per destination, a BReg credential or a signing key. + It holds a source credential and either a BReg credential or signing keys for the Coordinator triggers. It holds no other product's client or credential, and it has no steps, branches, waits or business timers. - Coordinator, when used, owns admission, one Run per item, lookup, choice, waits, recovery of its own commands and reaching a person. No product depends on it. @@ -293,7 +293,7 @@ There are exactly two destinations, chosen per job by what its items need. | | Direct to BReg | Signed event to Coordinator | | --- | --- | --- | | Use when | The item maps to one BReg operation with no lookup: an immediate Action, or a Proposal start and submit | The item needs a lookup, a choice between operations, a wait, a person, or a write outside BReg | -| Adapter holds | The BReg client behind the `direct-breg` feature, and a BReg credential | A signing key, no product client and no Coordinator crate | +| Adapter holds | The BReg client behind the `direct-breg` feature, and a BReg credential | One signing key per trigger, no product client and no Coordinator crate | | Mapping runs | In the job, as a Rhai script | In the workflow, as a Rhai Function on the same engine | | Retry identity | Command keys derived from the job, the item key and its sequence | An event ID derived from the same three | | Accepted means | BReg committed the Action, or the Proposal is submitted | Coordinator admitted the event and opened a Run | @@ -346,7 +346,14 @@ A metadata mismatch or operation refusal never selects another operation or dest {/* Evidence: crates/registry-adapter-core/src/job.rs RevisedEventReceiver */} {/* Evidence: crates/registry-adapter-core/src/job.rs revised_receiver_refuses_the_registration_trigger */} -The job sends one signed event per item, in the platform's `HookEnvelope` format signed with `sign_v1`. +{/* Evidence: crates/registry-adapter-connectors/src/coordinator_event.rs a_signed_event_signs_id_timestamp_and_the_exact_body */} +{/* Evidence: crates/registry-adapter-connectors/src/coordinator_event.rs a_rotating_trigger_sends_the_current_signature_first */} +{/* Evidence: crates/registry-adapter-job/src/runtime_destination.rs resolve_destination_keys */} + +The job sends one event per item as a canonical JSON `HookEnvelope` in a Standard Webhooks POST to `/v1/events/{workflow}/{trigger}`. +The request carries `accept: application/json`, `content-type: application/json`, `webhook-id`, `webhook-timestamp`, and `webhook-signature`. +The signature covers the envelope ID, the send time in Unix seconds, and the exact body bytes. +The receiver accepts a `webhook-timestamp` up to 300 seconds before or after its own clock. It admits one Run of a reviewed workflow through `workflow.eventTriggers`. Admission and Run commit together, and a repeat of the same event recovers the same Run. The workflow maps, resolves the target, calls one typed operation such as `breg.submit-proposal/v1`, and follows the outcome with `wait-for`. @@ -354,7 +361,7 @@ Coordinator recovers its own commands, and the job tracks only the admission. The event data has one fixed wrapper: `job: {id, version}`, `key`, `sequence`, `digest`, `item` (the declared projection), and `priorRunId` only when known. Event identity and event time are stable for one item sequence. -Transport time, signature and the monotonically increasing delivery attempt are renewed for retry. +Each retry keeps the envelope ID as `webhook-id` and signs with the time of that send as `webhook-timestamp`. The job tracks the delivery attempt in its item table. The selected public receiver identity is frozen durably before sending. A pending sequence with a frozen receiver cannot be retargeted by configuration changes: when the selected receiver differs, the pass stops as `adapter.job.coordinator-receiver-changed` without advancing position, and restoring the original receiver permits recovery. A rescan of an item whose refusal answered its last attempt clears its frozen receiver, and the receiver selected when the item is next sent is frozen in its place. @@ -363,8 +370,17 @@ A rescan sends it only to that receiver with that body, and a changed receiver o A possibly accepted item on a job with no revised trigger has no receiver to select: it is held as `adapter.job.revised-item` and sent nowhere, even when its revised event was sent and that answer was lost, and restoring the revised trigger does not resend a held item. `destination.revisedReceiver` optionally selects a revised-item `trigger`, `eventType` and `dataSchema` inside the same workflow and runtime binding. -Its trigger must be distinct from the registration trigger. -Without it, revised items remain held. +Its trigger must be distinct from the registration trigger. Without a revised receiver, revised items remain held. +Set `hmacSha256KeyRef` on the runtime destination for the registration trigger. +When the job declares a revised receiver, set `revisedReceiver.hmacSha256KeyRef` on the runtime destination for that trigger. Omit the runtime block when the job has no revised receiver. + +Generate a separate key file for each trigger with `(umask 077; openssl rand -hex 32 | tr -d '\n' > key)`. +Use distinct current and previous key bytes across all destinations and triggers in the runtime file. +Each key must contain 32 to 64 exact bytes. Supply the same key file to the Coordinator trigger that receives the event. +To rotate a trigger's key, set its `hmacSha256KeyRef` to the new key and set `previousHmacSha256KeyRef` in the same block to the old key. +The job sends two `v1,` signature entries, separated by a space, with the current key first. +Remove the previous reference after the receiving trigger has switched to the current key. + A revised event may have no prior Run ID after an uncertain admission. The workflow must handle that case without creating a second registration or acquiring a person's authority. @@ -414,7 +430,7 @@ The job keeps no payload at rest, so there is nothing to seal and no vault to ru | No payload in the item table | A dump or backup exposes personal data | A retry needs the source; a source that deletes early loses the item | | Field projection | A whole form reaches BReg, Coordinator, or their operators | One declared field list | | Narrow grants | An ingestion credential approves or applies | BReg Start, Submit and Get, or one Action; no Apply, no List | -| Signed events, Coordinator destination only | A forged event starts a Run | One rotatable signing key; a clock within 30 seconds | +| Signed events, Coordinator destination only | A forged event starts a Run | One rotatable signing key per trigger and a synchronized clock | | Value-free logs and status | Personal data reaches log aggregation | None | Four properties are never cut: @@ -462,7 +478,7 @@ Aggregate `status` names only a count and a code, so it points you to `inspect` The mode packages as one native companion executable on PostgreSQL. For a small IT team, a direct job adds one binary, one database, one source credential and one BReg credential. -A Coordinator job swaps the BReg credential for a signing key and a clock within 30 seconds of Coordinator's. +A Coordinator job needs a signing key per trigger and a clock synchronized with Coordinator's. ## Webhook ingress @@ -484,7 +500,7 @@ The KoboToolbox example adds a webhook trigger with `job.hook.yaml` and `job-run Configure the KoboToolbox webhook to send `POST` requests to the public HTTPS URL whose path is `/hooks/kobo-submissions`, using HTTP Basic authentication. Each source binding has its own Basic credentials through secret references, and finite request-rate and burst bounds. -Put the exact username and password in the two files referenced by `hookIngress.sources.kobo-submissions`, with the file permissions the platform secret provider requires (mode `0400` or `0600`). +Put the exact username and password in the two files referenced by `hookIngress.sources.kobo-submissions`, with the file permissions the platform secret provider requires, in the [secret file rule](../../security/hardening-checklist/#secret-files) (for example mode `0400` or `0600` for a file the service user owns). Write them without a trailing newline, for example `printf '%s' "$PASSWORD" > hook-password`, because the host refuses a value that ends with a newline. The Adapter resolves and captures them at host startup, and `adapter-job check` resolves them too. A missing, unsafe or malformed credential is therefore refused with the runtime member and the secret reference named, instead of failing later as a `401`. diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 29d445fb14..20bab82d87 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -671,9 +671,10 @@ Response custody and terminal audit remain one PostgreSQL transaction. {/* Evidence: crates/registry-adapter/tests/oauth_served_route.rs */} {/* TODO[evidence]: allowedClients admission and the required non-empty list have no test located by symbol in the files searched */} -Every facade call is authenticated with an OIDC bearer token through the platform block, as in every Registry Stack product. +Every facade operation call is authenticated with an OIDC bearer token through the platform block, as in every Registry Stack product. It is authorised by the Adapter's own access profiles: named bindings of scopes to concrete facade operations and record types, declared in the project. -The facade accepts no API keys, no Basic authentication and no anonymous calls. +The facade accepts no API keys, no Basic authentication and no anonymous operation calls. +The one exception is the two listener probes, `GET /health` and `GET /ready`, which answer anyone with a fixed body and read nothing the caller names. [Probe health and readiness](../../operate/adapter/#probe-health-and-readiness) describes them. The Adapter inherits no authorisation from any product and grants none to any source. The caller's token is never forwarded upstream. @@ -689,6 +690,28 @@ Any admitted client with a matching scope sees every record that the deployment' Record-level authorisation is not built. Admitting a client means trusting it with the full reach of the deployment credential. +A refused facade or payment request is counted and logged under the check that refused it, never under a caller value. +`adapter_request_refusals_total{check}` rises by one and the log carries one `request refused` line with the fixed `failed_check` label, for example `credential-missing`, `token-signature`, `token-client`, `scope`, `operation` or `ownership`. +The answer to the caller is unchanged. +The line is rate limited per check, so a flood of one kind of refusal cannot fill the log. +See [Scrape metrics](../../operate/adapter/#scrape-metrics). + +### Plain HTTP, private ranges and loopback + +An origin is plain HTTP only inside the loopback exception or inside the private ranges the runtime config declares in `allowedPrivateCidrs`. +Loopback means a `127.0.0.0/8` address, `::1`, an IPv4-mapped form of a `127.0.0.0/8` address, or the exact name `localhost`. +A payment provider connection takes only the address literals, never the name. +The name is pinned: the connection goes only to loopback addresses. +`a.localhost` and `localhost.` are named hosts. +An omitted or empty `allowedPrivateCidrs` admits no private address. +An origin plain HTTP names by host name, with no range declared, fails the runtime check with `adapter.runtime.insecure-origin`. +The text names the fix: serve the origin over TLS, declare the range the host resolves to, or use a loopback origin. + +**Breaking, for ingestion job hosts.** Before this change a job host whose runtime document named a plain `http://` endpoint by host name, with `allowedPrivateCidrs` omitted or empty, reached every private address the name resolved to. +Now that job fails the runtime check with `adapter.runtime.insecure-origin`. +To migrate, add the smallest range that contains the endpoint to `allowedPrivateCidrs`, serve the endpoint over HTTPS, or bind it on loopback. +The served facade is not affected: it already refused an empty list at load. + ### Upstream authentication {/* Evidence: crates/registry-adapter-core/src/auth.rs EndpointAuthentication */} diff --git a/docs/site/src/content/docs/configure/api-connections.mdx b/docs/site/src/content/docs/configure/api-connections.mdx index 55ac4570b8..51457be496 100644 --- a/docs/site/src/content/docs/configure/api-connections.mdx +++ b/docs/site/src/content/docs/configure/api-connections.mdx @@ -61,7 +61,8 @@ takes effect on the next invocation. An OAuth connection acquires its token auto A manually supplied token still needs renewal through its issuing system. Credential files must belong to the account running `rstack`, be regular files with a single -hard link, and have permissions `0400` or `0600`. Setup checks the supplied file before saving +hard link, and have permissions `0400` or `0600`. The rest of the rule is in +[Secret files](../../security/hardening-checklist/#secret-files). Setup checks the supplied file before saving the connection. For a deployment with a private certificate authority, add `--ca-file /path/to/ca.pem` during setup. diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index 8e945811e2..7c92423b51 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -65,8 +65,7 @@ accessProfiles: operations: [create, get, list, patch] readableFields: [operator-code, status, jurisdiction] writableFields: [operator-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` When the token fails any of these checks, or the profile does not grant the operation, BReg @@ -125,13 +124,38 @@ under an `in` boundary can move a row between the caller's allowed values, which points out. Write `rowBoundaries: unrestricted` only for deliberately registry-wide authority. +When many grants reach rows the same way, declare the boundaries once under `rowBoundarySets` and +reference the set wherever `rowBoundaries` is written. The facility template declares one set, and +every grant above refers to it: + +```yaml title="registry.yaml" test-excerpt="facility/registry.yaml" +rowBoundarySets: + same-jurisdiction: + - {field: jurisdiction, claim: jurisdiction, operator: equals} +``` + +A reference is the whole value of `rowBoundaries`. It works on record permissions, on Action and +Proposal targets, in a Record type's `accessRequirements`, and on a module's profiles. A mapping of +that shape anywhere else, such as inside a structured field schema, is ordinary data and stays as +written. Each grant still writes its own `rowBoundaries`, so the reach of a grant stays visible +where it is granted. A grant that omits `rowBoundaries` is still refused. References, inline lists, +and `unrestricted` can sit side by side in one profile. + +A set holds at least one boundary. An empty list and `unrestricted` are both refused as a set, +because an empty list would read as every row. Write `unrestricted` on the grant instead. A set is +local to the file that declares it, so a module cannot reference a set from its project. A +reference to a set the file does not declare is refused with +`breg.row-boundary-set.reference-invalid`. BReg expands every reference when it reads the file, so +the compiled package is the same as one that writes each list inline. + A derived field is computed under the same boundaries. A profile that reads one needs a read grant with the same `rowBoundaries` on every other Record type its SQL reads. See [Grant the Record types the SQL reads](../breg/#grant-the-record-types-the-sql-reads). An agent is held to a narrower rule. A token from an agent, or one acting for another principal, cannot create, patch, or delete Records directly, with or without a task grant; it reaches them -through [Actions and Proposals](../breg-actions/) instead. +through [Actions and Proposals](../breg-actions/) instead. For where each kind of authority is +decided across the stack, see [Where authority lives](../../explanation/where-authority-lives/). For a task-grant token, row-boundary claims other than `sub` resolve only from the grant's signed `identity` object, never from other token claims. To pin a grant to its subject, author a row @@ -164,8 +188,7 @@ and the facility grant has no `readPaths` entry: - recordType: facility operations: [get, list] readableFields: [facility-code, name, address-line, city, postal-code, status, jurisdiction] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` Direct operator reads apply the operator permission's jurisdiction boundary. A related read uses @@ -176,8 +199,7 @@ the facility permission's authority instead. Add the optional path grant to see readableFields: [facility-code, name, address-line, city, postal-code, status, jurisdiction] + readPaths: + - {path: operators, readableFields: [operator-code, status, jurisdiction]} - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` Check the edited project: @@ -187,7 +209,7 @@ bregctl check facility ``` ```text test-excerpt -warning[breg.access.profile-related-disclosure] /registry.yaml:237:15 /accessProfiles/facility-reader/permissions/records/1/readPaths/0 +warning[breg.access.profile-related-disclosure] /registry.yaml:241:15 /accessProfiles/facility-reader/permissions/records/1/readPaths/0 profile `facility-reader` can read `operator` records linked to `facility` through `facility-assignment` on read path `operators`; it sees fields jurisdiction, operator-code, status under its own `facility` row boundaries, and access profiles declared for `operator` do not apply next: Remove fields that these readers should not see from this read path's readableFields, or remove the read path; use a direct permission on the related record type when its own row boundaries should apply. 0 errors, 1 warning in 3 files @@ -242,8 +264,7 @@ entry is an alternative set of fields, and a list must pin every field of at lea + requiredFilters: + - fields: [facility-code] + - fields: [city, status] - rowBoundaries: - - {field: jurisdiction, claim: jurisdiction, operator: equals} + rowBoundaries: {rowBoundarySet: same-jurisdiction} ``` With this grant, `GET /v1/records/facilities?$filter=facilityCode eq 'F-001'` runs, and so does diff --git a/docs/site/src/content/docs/configure/breg-actions.mdx b/docs/site/src/content/docs/configure/breg-actions.mdx index 41cd0c4d25..9816c34d98 100644 --- a/docs/site/src/content/docs/configure/breg-actions.mdx +++ b/docs/site/src/content/docs/configure/breg-actions.mdx @@ -108,6 +108,47 @@ condition input. When `requiredConditionKeys` is empty, omit `preconditions`. The [immediate Action API contract](../../reference/breg-api/#immediate-actions) gives the request rules. +### Write in one call with `concurrency: current-revision` + +An Action that declares `concurrency: current-revision` sends no condition. The caller invokes it +in one request with no `preconditions`, and the descriptor's `requiredConditionKeys` is empty. +BReg evaluates the commit guards against the Record it locks for the write, and patches that same +row, so a concurrent update is never overwritten. + +```yaml +approve-application: + execution: {mode: immediate, concurrency: current-revision} + inputs: + - {id: application, apiName: applicationId, type: reference, target: application, required: true, classification: internal} + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + plan: + type: fixed + effects: + - id: approve + target: {fromInput: application} + operation: patch + set: + status: {value: approved} +``` + +The guard is the only protection against a stale write, so `bregctl check` holds the Action to +these rules: + +- Every Record the Action patches needs an `equals` or `isNull` guard that the Action's own write + makes false. Here the guard wants `submitted` and the write sets `approved`, so a second call + finds the guard false and answers `412`. +- A patch sets constants with `value` or clears a field. It cannot write a value from `fromInput` + or `fromEffect` into an existing Record, because a value the caller chose from a stale view would + overwrite a concurrent update. A create effect can still take caller values. +- A `revision: unchanged` guard is refused, because it needs the condition this mode removes. +- A function plan that writes an existing Record is refused. +- A Proposal cannot declare `concurrency`. + +Omit `concurrency` for the default, which asks the caller for a condition. Turning `current-revision` +on for an existing Action is a reviewed change, because it alters what protects the Record. + A Record type can require a Proposal for an operation: ```yaml title="registry.yaml" test-excerpt="facility/registry.yaml" @@ -395,7 +436,7 @@ The webhook receiver example shows durable acceptance and deduplication for an a ### Shift a date guard by an offset -A date guard may shift the registry-local date by a signed whole-day offset: +A date guard may shift the registry-local date by a signed whole-day offset, or by a signed whole number of calendar months: ```yaml commitGuards: @@ -407,6 +448,20 @@ commitGuards: ``` An absent or zero `currentDateOffsetDays` compares with today. +Use `currentDateOffsetMonths` instead when the window is a calendar span, such as a licence that must be valid for three more months: + +```yaml +commitGuards: + targets: + - input: licence + field: valid-through + currentDate: on-or-after + currentDateOffsetMonths: 3 +``` + +A month offset keeps the day of the month and clamps to the last day of a shorter month, so January 31 plus one month is February 28, or February 29 in a leap year. +`currentDateOffsetMonths` requires `currentDate`, accepts -12000 through 12000, and cannot be combined with `currentDateOffsetDays` on the same guard. +A shift that leaves the years 1 through 9999 fails the guard closed. The bounded offset applies to the same local date for advisory availability and for commit or Proposal Apply re-evaluation. A Proposal Plan evaluates `today()` once, when the Proposal starts. @@ -414,9 +469,10 @@ Its commit guards check `currentDate` again when the Proposal is applied. If approval crosses midnight or takes days, the date the Plan used and the date the guard compares against are different days. Write the guard offset with that gap in mind. -{/* Evidence: crates/registry-breg/src/model.rs current_date_offset_days; - crates/registry-breg/src/immediate_actions.rs current_date_offset_days; - crates/registry-breg/tests/immediate_action_requirements.rs current_date_offset_days. */} +{/* Evidence: crates/registry-breg/src/model.rs current_date_offset_days and current_date_offset_months; + crates/registry-breg/src/immediate_actions.rs current_date_offset_days and current_date_offset_months; + crates/registry-breg/src/commit_guard.rs shift_date; + crates/registry-breg/tests/immediate_action_requirements.rs current_date_offset_days and current_date_offset_months. */} ### Compare a stored field with an input @@ -483,9 +539,26 @@ It returns the observed target revision with `available: true`, or with `availab A guard may declare an optional, stable LocalId `reason` of at most 64 characters. The response exposes it as `guardReason` only when every guard fact and every row-boundary fact for the selected target is readable. The generic `reason` remains `guard-not-satisfied`. +A guard with a `reason` may also declare a `label`, the sentence a person sees when that guard refuses. +`label` is constant display text of at most 256 bytes and is refused without a `reason`: + +```yaml +commitGuards: + targets: + - input: application + field: status + equals: submitted + reason: not-submitted + label: Only a submitted application can be approved. +``` + +The label travels exactly where `guardReason` travels, and nowhere else. +An immediate Action refusal and a Proposal Submit or Apply refusal answer `412 action.guard_failed` with the label as `detail`, and the availability response carries it as `guardLabel`. +The answer for a guard whose facts the caller cannot read stays the fixed `precondition.failed` body, so a label never discloses a hidden guard. +A label is presentation copy: rewording one needs no reviewed migration and does not change the Action revision a frozen Proposal binds. If a declared input needed by a guard is absent, `available` is `null`, the reason is `input-required`, and `missingInputs` names only declared API input names. -If a guard or row boundary depends on a fact the caller cannot read, or the profile lacks Get authority for the target Record type, the answer is `available: null` with `observedRevision: null`, `not-disclosed`, and no `guardReason` or `missingInputs`: +If a guard or row boundary depends on a fact the caller cannot read, or the profile lacks Get authority for the target Record type, the answer is `available: null` with `observedRevision: null`, `not-disclosed`, and no `guardReason`, `guardLabel`, or `missingInputs`: ```json { diff --git a/docs/site/src/content/docs/configure/breg-mcp.mdx b/docs/site/src/content/docs/configure/breg-mcp.mdx index 071fcee6ab..2ac283fe4e 100644 --- a/docs/site/src/content/docs/configure/breg-mcp.mdx +++ b/docs/site/src/content/docs/configure/breg-mcp.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: reference locale: en standards_referenced: [] @@ -450,8 +450,8 @@ calls BReg or the issuer. ### Install or run the images -Each release publishes both services as `linux-amd64` binaries, verified as -[Obtain the runtime](../../operate/breg/#obtain-the-runtime) describes, and as images under +Each release publishes both services as binaries for Linux amd64, Linux arm64, and macOS arm64, +verified as [Obtain the runtime](../../operate/breg/#obtain-the-runtime) describes, and as images under `ghcr.io/registrystack/`. Deploy both from one tag, and images by digest. Each image runs as the Distroless `nonroot` user and reads `/etc//runtime.yaml`. Mount @@ -517,7 +517,9 @@ standard error from `breg-review`, so collect both. | Service | Level | Message | |---|---|---| | `breg-mcp` | info | `tool call`, with `request_id`, `tool`, and `outcome` | -| `breg-mcp` | warn | `the access-token key set is unavailable` | +| `breg-mcp` | info | `request refused`, with `failed_check` (the check that refused the request) and `suppressed`. At most five lines per check per minute | +| `breg-mcp` | error | `the gateway could not admit a request`, at most once a minute | +| `breg-mcp` | error | `the static key set was refused`, with the reason, at startup | | `breg-mcp` | error | `tool audit request refused` or `tool audit response refused` | | `breg-review` | warn | `a rate limit refused a request` | | `breg-review` | warn | `the registry declined a review request` or `the registry could not answer a review` | @@ -528,7 +530,9 @@ Neither service logs a token, secret, cookie, or field value. {/* Evidence: crates/registry-breg-mcp/src/main.rs, LOG_VARIABLE, main; crates/registry-breg-review/src/main.rs, LOG_VARIABLE; crates/registry-breg-mcp/src/gateway.rs, call; - crates/registry-mcp-edge/src/inbound.rs, authenticate; + crates/registry-mcp-edge/src/inbound.rs, authenticate, refuse; + crates/registry-mcp-edge/src/server.rs, require_resource_host; + crates/registry-breg-mcp/src/runtime.rs, static_key_fetcher; crates/registry-breg-review/src/pages.rs, review, submit; crates/registry-breg-review/src/lib.rs, Problem. */} diff --git a/docs/site/src/content/docs/configure/breg-proposals.mdx b/docs/site/src/content/docs/configure/breg-proposals.mdx index 29615ebaa2..3c8e6ee239 100644 --- a/docs/site/src/content/docs/configure/breg-proposals.mdx +++ b/docs/site/src/content/docs/configure/breg-proposals.mdx @@ -407,7 +407,7 @@ Any other result leaves the Proposal `submitted` until it is applied or cancelle | `approved`, automatic application | The built-in executor applies the frozen effects. `applicationStatus` reads `applied`, or `blocked` with a recovery hint when an executor refuses them. | | `approved`, manual application | The `apply` link becomes available. An authorised caller applies before the approval's `availableUntil`. | | `rejected` | The Proposal is `rejected`, a terminal state. Every command link reads `review-rejected` with recovery `receipt-only`: Submit, Edit, Revise, Rebase, Apply, Retry and Cancel answer 409 `proposal.rejected`, also after a package activation changes the Action revision; an attachment upload or removal is an Edit and answers the same. Start a new Proposal to propose the work again. | -| `changes-requested` | The Proposal stays `submitted`. Apply reads `review-changes-requested` with recovery `revise`. Revise submits the corrected version. | +| `changes-requested` | The Proposal stays `submitted`. Apply reads `review-changes-requested` with recovery `revise`. Revise returns the Proposal to `draft` under a new submission version. The caller corrects it, and Submit sends the corrected version for a new Review. | | `answered` | Apply reads `review-ended` with recovery `revise`. An answer is not a decision on a change. | | `cancelled` or `superseded` by the provider | Apply reads `review-ended` with recovery `revise`. A round BReg withdrew also reads as ended; a late approval cannot restore Apply authority. | diff --git a/docs/site/src/content/docs/configure/casework-completion-receivers.mdx b/docs/site/src/content/docs/configure/casework-completion-receivers.mdx index 63a5bee97f..5908d804ab 100644 --- a/docs/site/src/content/docs/configure/casework-completion-receivers.mdx +++ b/docs/site/src/content/docs/configure/casework-completion-receivers.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -29,23 +29,44 @@ Casework sends a POST with a JSON body that carries exactly these business field The body contains event, request and result identifiers and a completion time. It carries no review decision and no source record payload. -The request carries these headers: - -- `Idempotency-Key` is the string form of `eventId`. -- `Registry-Recipient-Binding` is the producer's configured recipient binding. -- The destination presents either `Authorization: Bearer ` or the configured named secret header. - -Compare the expected secret and recipient before you accept a wake. -Make sure your HTTP framework logs redact credential headers. - -{/* Evidence: crates/registry-casework/src/runtime.rs deliver_review_completion; - crates/registry-casework/src/config.rs ReviewCompletionAuthConfig */} +Casework sends `Accept: application/json` and `Content-Type: application/json` with these delivery headers: + +- `registry-recipient-binding` identifies the producer's configured recipient. +- `webhook-id` is the string form of `eventId`. +- `webhook-timestamp` is the attempt time in Unix seconds, in decimal. +- `webhook-signature` carries one or two space-separated `v1,` signatures, with the current key first. + +Check each delivery in this order. + +1. Match `registry-recipient-binding` to your configured recipient and select its signing keys. + Require a single header value for the binding and for each of the three `webhook-*` headers. + Return the same 401 response for an unknown binding and a bad signature. + This unsigned binding only selects keys. + Use distinct keys for each recipient so a substituted binding selects a different key. +2. Read the raw body with a size limit. +3. Verify the Standard Webhooks HMAC-SHA256 signature over the exact bytes of `webhook-id + "." + webhook-timestamp + "." + body`. + Give a Standard Webhooks library the raw key bytes. + Accept a valid signature for either configured key and require the signed timestamp to be within 300 seconds of your clock in either direction. +4. Require the `application/json` content type. +5. Parse the JSON strictly as the five fields above. + Require the `review.completed` type, valid UUIDs and a valid completion timestamp. + Refuse duplicate, unknown or missing members. +6. Require `eventId` to equal `webhook-id`. + +For canonical hook envelopes, the maintained Rust verifier is `registry_platform_hooks::receiver::verify_hook_delivery`. +For the Casework completion body shown above, use `registry_platform_crypto::delivery_signature::verify` and then parse the authenticated bytes as described in steps 4 through 6. +See the receiver procedure and tested example in the [delivery signing reference](../../reference/delivery-signing/). + +{/* Evidence: crates/registry-casework/src/runtime.rs deliver_review_completion, review_completion_signs_the_exact_bytes_it_sends; + crates/registry-casework/tests/review_payment_fixture_postgres.rs receive_completion; + crates/registry-platform-crypto/src/delivery_signature.rs verify; + crates/registry-platform-hooks/src/receiver.rs verify_hook_delivery */} ### Acknowledgement Any 2xx response acknowledges delivery. Casework decides from the status line and drops the response without reading its body, including an unfinished stream. -Use an empty 204 for compatibility with releases through 0.43.0, which required that response. +An empty 204 response is sufficient. Casework does not follow redirects. {/* Evidence: crates/registry-casework/src/runtime.rs completion_acknowledged */} @@ -53,9 +74,9 @@ Casework does not follow redirects. ### At-least-once delivery Delivery is at-least-once: after a lost acknowledgement Casework can send again. -The same `eventId`, payload, recipient binding and idempotency key survive retries. -Receivers must durably deduplicate by `eventId` before they acknowledge. -This does not provide exactly-once delivery or exactly-once business effects. +The same `webhook-id`, payload and recipient binding survive retries. +Casework signs each attempt with its own timestamp. +Store the verified event ID and payload durably before acknowledging, and use the event ID to deduplicate retries. {/* Evidence: crates/registry-casework/tests/review_postgres.rs at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhausts_bounded_retries */} @@ -80,70 +101,25 @@ A stale lease owner cannot settle or log another owner's attempt as exhausted. crates/registry-casework/tests/review_postgres.rs completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner */} {/* TODO[evidence]: defaults 5000, 30 and 12 are in default_review_completion_* functions; no test asserts the default values */} -## Durable receiver examples +## Persist the wake -Create an adopter-owned inbox in the receiver database: +Create an inbox in your receiver database. ```sql CREATE TABLE completion_inbox ( event_id uuid PRIMARY KEY, - payload text NOT NULL + payload jsonb NOT NULL ); ``` -These framework-neutral handlers assume your HTTP adapter has bounded the JSON body, rejected duplicate members, checked the five fields and their UUID and time types, and normalised header names to lowercase. -Pass an operator-resolved secret and recipient; never use event fields to select credentials or authority. -Return 503 when the database cannot commit. -Keep inbox entries until your own reconciliation is complete and your replay policy permits erasure. - -Python with a psycopg connection: - -```python -import hmac -import json - - -def receive_completion(headers, event, db, secret, recipient): - if not hmac.compare_digest(headers.get("authorization", ""), "Bearer " + secret): - return 401 - if headers.get("registry-recipient-binding") != recipient: - return 403 - if event["type"] != "review.completed" or headers.get("idempotency-key") != event["eventId"]: - return 400 - payload = json.dumps(event, sort_keys=True, separators=(",", ":")) - with db.transaction(): - db.execute("INSERT INTO completion_inbox VALUES (%s,%s) ON CONFLICT DO NOTHING", - (event["eventId"], payload)) - stored = db.execute("SELECT payload FROM completion_inbox WHERE event_id=%s", - (event["eventId"],)).fetchone()[0] - if stored != payload: - return 409 - return 204 # The commit completed before acknowledgement. -``` - -Node with a `pg` pool (the SQL statement autocommits before its promise resolves): - -```javascript -const { timingSafeEqual } = require('node:crypto'); - -async function receiveCompletion(headers, event, pool, secret, recipient) { - const got = Buffer.from(headers.authorization ?? ''); - const expected = Buffer.from(`Bearer ${secret}`); - if (got.length !== expected.length || !timingSafeEqual(got, expected)) return 401; - if (headers['registry-recipient-binding'] !== recipient) return 403; - if (event.type !== 'review.completed' || headers['idempotency-key'] !== event.eventId) return 400; - const payload = JSON.stringify({ type: event.type, eventId: event.eventId, - requestId: event.requestId, resultId: event.resultId, completedAt: event.completedAt }); - await pool.query('INSERT INTO completion_inbox VALUES ($1,$2) ON CONFLICT DO NOTHING', - [event.eventId, payload]); - const stored = await pool.query('SELECT payload FROM completion_inbox WHERE event_id=$1', - [event.eventId]); - return stored.rows[0].payload === payload ? 204 : 409; -} -``` +After verification, insert the event under its verified `webhook-id` in a transaction. +If the ID already exists, compare the stored payload and acknowledge an identical event. +Return 409 if the payload differs. +Acknowledge only after the transaction commits. +Return 503 if the database cannot confirm the commit. -A database error must reach your HTTP adapter as a safe 503; do not acknowledge an uncertain insert. -For named-header authentication, compare the configured header's raw value with the secret instead of constructing a bearer value. +Keep inbox entries through your reconciliation and retry window. +Retries carry fresh signatures, so a 300-second signature window alone cannot bound inbox retention. ## Read the result diff --git a/docs/site/src/content/docs/configure/casework.mdx b/docs/site/src/content/docs/configure/casework.mdx index 1dd9295bfd..a9ee1dcc69 100644 --- a/docs/site/src/content/docs/configure/casework.mdx +++ b/docs/site/src/content/docs/configure/casework.mdx @@ -408,7 +408,7 @@ The same producer reads `GET /v1/review-requests/{requestId}/result` or its resu A `ReviewResult` repeats the subject, policy and submission digest, and carries a terminal status such as `approved`, `rejected`, `answered`, `cancelled` or `superseded`. A decided result names its `outcome` and any `publicReason`; a cancelled or superseded one carries neither. -A completion destination, when configured, receives an authenticated wake with event, request and result identifiers. +A completion destination, when configured, receives a Standard Webhooks-signed wake with event, request and result identifiers. Delivery is at-least-once. A wake carries no decision payload; the producer fetches the result and authorises any later mutation independently. [Receive Casework completion wakes](../casework-completion-receivers/) defines the wake. diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index 67c68bd5fe..3fb8d69b1f 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -473,12 +473,12 @@ The event source owns event meaning and disclosure, and product event names and The receiving workflow uses the same finite execution engine and independently authorised downstream connections as an explicit start. The receiver is `POST /v1/events/{workflow}/{trigger}`. -It accepts the HookEnvelope Registry Stack products share, with its v1 delivery signature, under the operator's `eventSources` key binding. +It accepts the shared HookEnvelope signed with Standard Webhooks using the key configured for that workflow and trigger under `eventSources`. - The authenticated source URI, the event ID, and the trigger bind admission independently of the local source alias, and the canonical event bytes bind exact retries. - The admission, the run, and its durable job commit together. A repeated exact delivery recovers the same run before evaluating any changed mapping, and changed event bytes conflict. -- The delivery attempt time must be fresh within 30 seconds. +- The signed Unix timestamp must be within 300 seconds in either direction. The immutable event time may be older after an outage. - Acknowledgement is an empty HTTP 204 and never a source mutation proposal. An admitted event grants no source mutation authority. @@ -488,8 +488,9 @@ An event workflow that writes back to its own source must select meaningful stat Ordinary product API calls do not propagate event causation across products, so the envelope's hop bound alone does not prevent those loops. The [product events example](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/product-events) admits committed BReg events, and a conforming alternate-source fixture, through the same signed event contract. -{/* Evidence: crates/registry-coordinator/src/event_trigger_tests.rs substituted_signature_destination_source_and_contract_are_refused, - stale_delivery_noncanonical_body_and_header_body_disagreement_are_refused, +{/* Evidence: crates/registry-coordinator/src/event_trigger_tests.rs a_delivery_for_another_trigger_is_refused_by_that_triggers_key, + the_event_window_is_300_seconds_in_both_directions, + an_authentic_noncanonical_body_is_refused, exact_event_identity_survives_retry_replay_and_old_commit_time, event_admission_is_atomic_deduplicated_and_recovers_after_restart_and_activation; crates/registry-coordinator/tests/breg_event_native.rs native_proposal_event_admits_one_run_without_conferring_apply_authority. */} diff --git a/docs/site/src/content/docs/configure/discovery.mdx b/docs/site/src/content/docs/configure/discovery.mdx index c9f2c5da69..7afb3472a7 100644 --- a/docs/site/src/content/docs/configure/discovery.mdx +++ b/docs/site/src/content/docs/configure/discovery.mdx @@ -30,28 +30,33 @@ checkout root for the commands that run beside it. ## Install the binaries -Releases from v0.38.0 publish Linux amd64 assets `discovery--linux-amd64` and -`discoveryctl--linux-amd64`, with `` from the -[latest release](https://github.com/registrystack/registry-stack/releases/latest). Authenticate -them through the release's `SHA256SUMS` as the -[verification guide](https://github.com/registrystack/registry-stack/blob/main/release/VERIFY.md) -describes, then install them under their plain names: +From v0.44.0, each release publishes `discovery` and `discoveryctl` for Linux amd64, Linux arm64, +and macOS arm64, with an installer. Choose a tag, normally the +[latest release](https://github.com/registrystack/registry-stack/releases/latest), and +authenticate the assets with the +[verification guide](https://github.com/registrystack/registry-stack/blob/main/release/VERIFY.md). +Linux assets are executables named `--linux-`. macOS assets are `.tar.gz` +bundles that carry the executable, its AWS-LC-FIPS libraries, and notices. +Install the pair from one tag with the release-pinned installer: ```sh test-skip="installs release assets; the runner serves the binaries under test" -tag="${TAG:?set TAG to the published release tag}" -mkdir -p ~/.local/bin -for binary in discovery discoveryctl; do - install -m 0755 "${binary}-${tag}-linux-amd64" "$HOME/.local/bin/${binary}" -done +tag="vX.Y.Z" +bash "discovery-${tag:?set tag to the release tag}-install.sh" +"${DISCOVERY_INSTALL_DIR:-$HOME/.local/bin}/discovery" --version +"${DISCOVERY_INSTALL_DIR:-$HOME/.local/bin}/discoveryctl" --version ``` -On another platform, build them from a checkout as the tutorial does. The release also publishes -the image `ghcr.io/registrystack/discovery:`; deploy it by the digest the release manifest -records, not by the tag. It runs `discovery` as a nonroot user and reads -`/etc/registry-discovery/runtime.yaml`. Mount that file and the package directory read-only; -Discovery writes nothing. +The installer puts both binaries in `~/.local/bin`. Set `DISCOVERY_INSTALL_DIR` to change that. +The version checks run the binaries by that path, so they work before the directory is on your +`PATH`. Neither path needs a Rust toolchain. -{/* Evidence: release/scripts/release_roster.py, DISCOVERYCTL_FIRST_RELEASE; +The release also publishes the image `ghcr.io/registrystack/discovery:` for linux/amd64. +Deploy it by the digest the release manifest records, not by the tag. It runs `discovery` as a +nonroot user and reads `/etc/registry-discovery/runtime.yaml`. Mount that file and the package +directory read-only. Discovery writes nothing. + +{/* Evidence: release/scripts/release_roster.py, ADDITIONAL_PLATFORM_BUILDS and ADDITIONAL_INSTALLERS; + crates/registry-discovery/install.sh, DISCOVERY_INSTALL_DIR; release/docker/Dockerfile.discovery, ENTRYPOINT, CMD, and "writes nothing"; release/VERIFY.md. */} ## Approve HTTPS origins diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index 124a789b12..9b0fb9620c 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-20" +last_reviewed: "2026-11-27" doc_type: how-to persona: - operator @@ -121,8 +121,8 @@ client; a flow where people request their own credential must not be given offer crates/registry-evidence-oid4vci/src/offer.rs, SelectorValueOrigin::Request. */} `privateKeyRef` and `audit.hashKeyRef` follow the [secret reference grammar](../../reference/environment-variables/#secret-references). -Both key files must be regular files owned by the service user, mode `0400` or `0600`, with a -single link. The audit key produces stable pseudonyms for the authenticated offer client, subject, +Both key files must meet the [secret file rule](../../security/hardening-checklist/#secret-files), +for example regular files owned by the service user, mode `0400` or `0600`, with a single link. The audit key produces stable pseudonyms for the authenticated offer client, subject, or both without storing their raw identities. Preserve it for as long as those records must remain correlatable. A file destination is the durable journal; use `stdout` only when the deployment collector durably accepts and preserves every line. Every key has the bounds and default its @@ -136,7 +136,7 @@ schema gives it, and `check` also enforces the rules a schema cannot hold: - A reference must name a provider the file enables, and `secretProviders.file.root` must be absolute. -{/* Evidence: crates/registry-platform-config/src/secrets.rs, validate_file_metadata; +{/* Evidence: crates/registry-platform-config/src/secrets.rs, judge_file; crates/registry-evidence-oid4vci/src/config.rs, evidence.oid4vci.nonce-lifetime, evidence.oid4vci.listener-port, evidence.oid4vci.metrics-address, evidence.oid4vci.metrics-shared-binding, evidence.oid4vci.secret-provider-disabled, @@ -246,7 +246,7 @@ front of those three paths as well. Check that the defaults suit your wallet tra upgrade a busy deployment, and raise them in `rateLimits` rather than behind the proxy alone. {/* Evidence: crates/registry-evidence-oid4vci/src/service.rs, Limits, admit, limiter_refusal, offer_limiter_key, wallet_endpoint, - build_app, normalize_rejections, security_headers; + build_app, normalize_rejections, security_headers_without_posture; crates/registry-evidence-oid4vci/src/config.rs, RateLimitsConfig, maximum_request_bytes; products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json, rateLimits, offersPerPrincipalPerMinute, walletRequestsPerMinute; @@ -264,6 +264,7 @@ Set `metricsListener.bind` to serve Prometheus text at `/metrics` on a private a | `evidence_oid4vci_store_entries` | Entries in the fullest bounded offer, ledger, or token keyspace | | `evidence_oid4vci_store_capacity` | Refusal threshold for each bounded keyspace | | `evidence_oid4vci_cleanup_expired_total` | Expired in-memory entries released by cleanup | +| `evidence_oid4vci_request_refusals_total` | Requests refused, by the check that failed, with every check published at zero. Each refusal also writes one `request refused` log line with `failed_check`, at most five per check per minute. Neither carries a token, claim or client | {/* Evidence: crates/registry-evidence-oid4vci/src/observability.rs, Outcome, ALL, render_metrics. */} diff --git a/docs/site/src/content/docs/configure/module-conventions.mdx b/docs/site/src/content/docs/configure/module-conventions.mdx index 355b7704c9..82ae743ece 100644 --- a/docs/site/src/content/docs/configure/module-conventions.mdx +++ b/docs/site/src/content/docs/configure/module-conventions.mdx @@ -44,16 +44,16 @@ Render's correlation key is not a deduplication promise. ## Receive signed delivery -Use the [delivery signing contract](../../reference/delivery-signing/) -for exact header and byte rules. Verify the original body bytes before parsing them, compare the -signature in constant time, and bind deduplication to the verified delivery identity and payload. +Follow [Receive signed deliveries](../../reference/delivery-signing/) for the header and byte rules. +Verify the raw body before parsing it and compare the signature in constant time. +Check that `webhook-id` equals the ID in the signed body. +Deduplicate on the sender identity and `webhook-id`. A completion wake announces that a result can be read; read that result from its authoritative product and correlate it to the request you accepted. -The deterministic [cross-language fixtures](https://github.com/registrystack/registry-stack/blob/main/crates/registry-platform-crypto/tests/fixtures/delivery-signatures.json) -come from that owning implementation. Run their exact bytes, key, and expected signatures through -your language's implementation, including the negative cases, before sending or accepting live -traffic. The owning drift test ensures the fixtures and signing implementation agree. +Run the [signature vectors](https://github.com/registrystack/registry-stack/blob/main/crates/registry-platform-crypto/tests/fixtures/standard-webhooks.json) +through your implementation before sending or accepting live traffic. +The tests check the vectors against the signing code and an independent Standard Webhooks library. ## Try the Python composition diff --git a/docs/site/src/content/docs/configure/request-an-access-token.mdx b/docs/site/src/content/docs/configure/request-an-access-token.mdx index 92d87c3df6..1b900996f4 100644 --- a/docs/site/src/content/docs/configure/request-an-access-token.mdx +++ b/docs/site/src/content/docs/configure/request-an-access-token.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-17" +last_reviewed: "2026-11-27" doc_type: how-to persona: - consumer or verifier @@ -109,8 +109,7 @@ Existing bounded multi-audience tokens remain accepted where the owning profile A token without the target audience grants no access to that resource. Casework task-client profiles keep their narrower audience rules. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs AuthenticationStage; - crates/registry-messaging/src/auth.rs access_token_profile, AUDIENCE. */} +{/* Evidence: crates/registry-messaging/src/auth.rs access_token_profile, AUDIENCE. */} {/* TODO[evidence]: the multi-audience acceptance rule and the Casework task-client audience rule have no single code anchor. */} ## Token profile each service accepts @@ -190,13 +189,13 @@ A hostname that resolves to loopback is not a literal-loopback exception. Public invalid-credential responses remain a generic 401 `authentication.refused`. Authenticated profile and route failures keep their documented 403 or concealment, and a verifier outage keeps its product's 503. -Internal verification stages are fixed labels: header, algorithm, token-type, key, signature, issuer, audience, time, client, scope, profile, and unavailable. -Each verifier emits at most one diagnostic per stage per minute. +Each refusal writes one `request refused` log line with a fixed `failed_check` label, and the product counts it by that label where it serves metrics. +A verifier writes at most five lines per check per minute, and the next line reports how many refusals of that check the window counted but did not log. These logs contain no credential, claim, issuer, audience, scope, key, or subject values. Use the selected configuration and safe local validation to identify the mismatched field, and never add token contents to runtime logs. Local fixture validation names the field or rule and the expected profile category without printing input values. -{/* Evidence: crates/registry-platform-oidc/src/diagnostics.rs AuthenticationStage, AuthenticationDiagnostics; +{/* Evidence: crates/registry-platform-authcommon/src/refusal.rs failed_check; crates/registry-adapter-core/src/problem.rs AUTHENTICATION_REFUSED_PROBLEM. */} ## Troubleshooting diff --git a/docs/site/src/content/docs/configure/scheduling.mdx b/docs/site/src/content/docs/configure/scheduling.mdx index 3e1b5f61d8..cb4e5ae2ca 100644 --- a/docs/site/src/content/docs/configure/scheduling.mdx +++ b/docs/site/src/content/docs/configure/scheduling.mdx @@ -204,7 +204,7 @@ cancellation sends only `appointmentId`, `revision`, and `state`. `check` refuse with `scheduling.project.unsupported-hook-projection`, so a hook never sends the station, the caller, or the cancellation reason. A cancellation intent sent to the reminder destination does carry the reason. Delivery happens after the appointment commits, -at least once, signed with HMAC-SHA256, and the receiver's answer never changes a booking. +at least once, signed with Standard Webhooks, and the receiver's answer never changes a booking. {/* Evidence: crates/registry-scheduling-core/src/policy.rs, HookPolicy and ObserverTrigger; crates/registry-scheduling/src/hooks.rs; crates/registry-schedulingctl/src/project.rs, check() @@ -316,15 +316,17 @@ A reminder whose appointment was cancelled or moved to a newer revision is set a With no reminder destination configured, each intent stays readable in the outbox and is set aside as local when it falls due, never pretended delivered. Adopting the product does not require wiring a notification bus first. -You can sign reminder delivery with the optional `destinations.reminders.hmacSha256KeyRef`. -Signed delivery uses the shared CloudEvents delivery headers and an HMAC-SHA-256 signature that binds the request target, the envelope bytes, and the delivery metadata. -`destinations.reminders.url` is the fallback for every purpose. -The optional closed `purposeUrls` block selects separate `confirmation`, `change`, `cancellation`, and `reminder` endpoints on that fallback URL's origin, and missing purposes keep using the fallback. -The runtime compiles every effective endpoint at startup and signs the exact selected path, so a proxy cannot reroute a signed event to another typed receiver. -The event identity and idempotency key stay fixed across retries, while the attempt and delivery time change. -Configure the matching trusted source and key at the receiver. -The optional `destinations.reminders.bearerTokenRef` authenticates access to the destination independently and can be used with signing, and omitting the signing key keeps bearer-only delivery. -A valid event signature proves origin and integrity; it does not grant appointment-read or message-send authority. +Reminders use Standard Webhooks with the required `destinations.reminders.hmacSha256KeyRef`. +The runtime signs the canonical envelope bytes, the outbox id carried in `webhook-id`, and the +lease time in Unix seconds carried in `webhook-timestamp`. The receiver reads the signature from +`webhook-signature` and deduplicates by `webhook-id`, which stays fixed across retries. + +`destinations.reminders.url` is the fallback for every purpose. The optional `purposes` block +configures separate destinations for `confirmation`, `change`, `cancellation`, or `reminder`. +Each must share the fallback URL's origin and use its own signing key. Configure the matching +trusted source and key at the receiver for each URL. Follow the +[delivery signing guide](../../reference/delivery-signing/) to generate exact key bytes without a +trailing newline and rotate keys with `previousHmacSha256KeyRef`. ### Appointment observers @@ -341,7 +343,7 @@ A policy may declare `phase: after` with a URL handler for exactly four triggers The runtime refuses conditions, principals, Rhai or Wasm handlers, unknown triggers, and fields outside that table. It captures one canonical event and its delivery row in the same transaction as the appointment change. An after-commit worker then POSTs it to the deployment-bound destination. -Delivery is at least once, signed with HMAC-SHA256, retried within fixed product ceilings, and audited without payload values. +Delivery is at least once, signed with Standard Webhooks, retried within fixed product ceilings, and audited without payload values. Each attempt's audit entry is accepted before the request leaves, or the delivery stays pending and nothing is sent. A receiver response is observation only: Registry Scheduling deterministically refuses every proposal and never turns it into a booking, reschedule, or cancellation. @@ -355,7 +357,7 @@ Retained payloads expire after `retention.hookPayloadRetentionDays`, and termina [Registry Scheduling configuration reference](../../reference/scheduling-configuration/#retention) states the exact cleanup rules. {/* Evidence: crates/registry-scheduling/src/hooks.rs; crates/registry-scheduling-core/src/policy.rs ObserverTrigger; - crates/registry-scheduling/src/config.rs reminder_purpose_urls_are_typed_and_optional; + crates/registry-scheduling/src/config.rs reminder_purposes_are_typed_and_optional; crates/registry-scheduling/tests/postgres_commitments/attendance.rs attendance_commit_captures_one_minimized_signed_after_event; crates/registry-platform-dispatch/src/retry.rs. */} {/* TODO[evidence]: the envelope member table (causation root and hop, dataschema) has no single test that asserts every member. */} diff --git a/docs/site/src/content/docs/explanation/where-authority-lives.mdx b/docs/site/src/content/docs/explanation/where-authority-lives.mdx new file mode 100644 index 0000000000..0b7d04a87e --- /dev/null +++ b/docs/site/src/content/docs/explanation/where-authority-lives.mdx @@ -0,0 +1,87 @@ +--- +title: Where authority lives +description: Which of the token, the configuration and the records decides who a caller is, what a profile may do, and which rows and teams a caller reaches, and what holds today. +status: current +owner: registry-docs +source_repos: + - registry-stack +last_reviewed: "2026-11-27" +doc_type: explanation +locale: en +standards_referenced: [] +--- + +Every Registry Stack product asks the same three questions about a request. Each question has one +home. Knowing the home tells you where to change an answer, and which answer takes effect first. + +## One rule + +- The token says who the caller is. Your issuer signs it, and the product verifies it. +- Configuration says what a profile may do. The access profile lists operations, fields and purposes. +- Records say which rows and which teams. Today this holds only in part, as the next sections show. + +A caller cannot widen its own reach. A request field is never an authorisation decision, and a +product inherits no authority from another product. + +{/* Evidence: crates/registry-breg/src/access.rs; crates/registry-platform-oidc/src/lib.rs. */} + +## Row authority today comes from token claims + +A [row boundary](../../reference/glossary/#row-boundary) compares a Record field with a claim in +the verified token. Base Registry Engine (BReg) declares it with `rowBoundaries` on a record +permission. The rows a caller reaches therefore depend on what your issuer put in the token. + +This has two consequences. + +- Your issuer must be one you trust to assert the claim. +- A change to a caller's reach takes effect when the caller next receives a token, not when you + change a record. + +The compiled form shows the limit of this design. An empty list of boundaries permits every row, and +the authored `rowBoundaries: unrestricted` compiles to that empty list. + +See [BReg access profiles](../../configure/breg-access/) for the fields and examples. + +{/* Evidence: crates/registry-breg/src/contract.rs row_boundaries; crates/registry-breg/src/access.rs; + crates/registry-breg/src/authority.rs. */} + +## Membership boundaries read records, for reads only + +A membership boundary moves the decision into records. A row is readable only while a current, +active membership Record names the caller. Deactivate the membership and the next request no longer +sees the row. No token expiry is involved. + +Membership boundaries support `get`, `lookup`, `list`, `revisions` and `snapshot` only. Today BReg +refuses a profile that combines a membership boundary with any other operation, or with +`writableFields`. The compiler reports `breg.access.membership-read-only` and tells you to use a +separate, directly authorised profile for writes and proposal application. + +So a registry that must restrict writes by team still uses `rowBoundaries` and token claims for the +write profile. Membership records cannot yet carry write authority. + +Two more limits apply today: + +- A profile with a membership boundary cannot enable spatial bounding-box queries. +- A profile declares at most eight membership boundaries. + +{/* Evidence: crates/registry-breg/src/membership.rs validate(); + crates/registry-breg/tests/membership_access.rs membership_boundaries_refuse_unenforced_authority_paths. */} + +## Casework keeps BReg disclosure under the reviewer's identity + +Registry Casework decides who may review a task. It does not decide what a reviewer may see in +BReg. When Casework shows a reviewer the current record, BReg answers under the reviewer's own +identity and its own access profile. Casework adds no disclosure authority. + +Today, by default, Casework forwards the reviewer's bearer token to BReg for that read. A provider +that declares `humanSourceAuthentication` can use a separate source credential for the same +reviewer instead. On either path BReg applies its own profile to the identity it receives. + +{/* Evidence: crates/registry-casework/src/review.rs; crates/registry-casework-breg/src/lib.rs human_display(); + crates/registry-casework/src/http/source_credentials.rs. */} + +## Continue + +- [BReg access profiles](../../configure/breg-access/) +- [Where each rule lives](../where-each-rule-lives/) +- [Security model](../../security/) diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index e4152a6375..54a6ed1227 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -37,14 +37,17 @@ Authenticate the checksum bundle as `release/VERIFY.md` at the tag you install d install the binaries with the release-pinned installer or as an `rstack` component: ```sh -bash adapter--install.sh -adapterctl --version +tag="vX.Y.Z" +bash "adapter-${tag:?set tag to the release tag}-install.sh" +"${ADAPTER_INSTALL_DIR:-$HOME/.local/bin}/adapterctl" --version rstack install adapter rstack adapter check --help ``` The installer puts the two binaries in `~/.local/bin`; set `ADAPTER_INSTALL_DIR` to change that. +The version check runs `adapterctl` by that path, so it works before the directory is on your +`PATH`. `rstack install adapter` installs the same two binaries into an `rstack` generation, and `rstack adapter` runs `adapterctl`. Neither path needs a Rust toolchain. @@ -59,6 +62,52 @@ You build it from a reviewed source checkout (see [Build the job host](#build-th {/* Evidence: docs/site/src/data/cli-reference.yaml source_build_only_binaries. */} +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords and the database. They are the URLs in +`database.migrationUrlRef` and `database.runtimeUrlRef`. +Put both URLs in their secret files, then run `adapterctl provision` once as a PostgreSQL role that +can create roles and databases: + +```sh +adapterctl provision --runtime-config runtime.yaml --admin-url-file admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. +The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. +To pass the URL in an environment variable instead, use `--admin-url-env NAME`. +The connection requires TLS and verifies the server certificate. +Set `database.caBundleRef` in the runtime file to trust a private CA. +The command never prints the administrator URL or a password. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Gives the migration role `USAGE` and `CREATE` on the `public` schema, and takes `CREATE` on it + from `PUBLIC`. + +Run it again at any time. +It creates only what is missing. +It refuses a role that exists with a different password than its URL holds, and tells you which role. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. +The command connects to nothing and prints the script, with a `\password` prompt after each +`CREATE ROLE` so the script holds no password. +Add `--format json` for a report of each statement and its outcome. + +`provision` grants the runtime role nothing beyond `CONNECT`. +`adapter serve` grants the table privileges when it starts, as the next section describes. +An administrator that is not a superuser becomes a member of the roles it creates, holding +`ADMIN OPTION`, and that membership does not stop the grant. + +{/* Evidence: crates/registry-adapterctl/src/provision.rs; + crates/registry-adapterctl/tests/provision_cli.rs; + crates/registry-adapterctl/tests/provision_postgres.rs provision_then_serve_with_split_roles. */} + ## Grant the runtime database role The facade journals every request and, when it serves a write, keeps idempotency state in @@ -75,11 +124,22 @@ When the certificate comes from a private CA, name that CA with `adapter serve` migrates through `database.migrationUrlRef` and serves through `database.runtimeUrlRef`. The migration role owns the tables. -Give the runtime role only the grants its deployment uses. -The Adapter refuses a runtime role at startup, naming each missing grant and table, before it -listens. -In the statements that follow, `adapter` stands for the schema on the runtime role's search path and -`runtime` for that role: +After it migrates and before it grants anything, `adapter serve` connects as the runtime role and reads +that session's role name. +When it differs from the migration session's role name, `adapter serve` grants the runtime session's +role the privileges its deployment uses. +The grants run in one transaction, then `adapter serve` checks them and refuses to listen if one is +missing. +A runtime connection that fails stops startup before any grant. +The runtime role must already exist, be able to log in and hold `CONNECT` on the database. +When both sessions run as the same role, `adapter serve` issues no grant and the single role keeps +every privilege it owns. +The runtime role's search path must reach the same schema as the migration role's. + +The statements below are equivalent to what `adapter serve` runs for the facade tables, with +`adapter` standing for the schema on the migration role's search path and `runtime` for the runtime +role. +`adapter serve` issues only the grants the role still lacks: ```sql -- Every deployment: append journal events, run audit.retentionDays, report readiness. @@ -98,16 +158,76 @@ GRANT SELECT, INSERT, UPDATE ON adapter_idempotency_async_artifacts TO runtime; GRANT SELECT, INSERT ON adapter_idempotency_resume_bindings TO runtime; ``` -The runtime role needs no grant on `adapter_idempotency_schema_migrations`; only the migration role -reads it. +The Adapter grants nothing else: no default privileges, and nothing on +`adapter_idempotency_schema_migrations`, which only the migration role reads. +It never revokes a grant, so a feature you remove from a deployment leaves its earlier grants in +place until you revoke them. + +When you start `adapter serve` with `--payments-config`, the same grant step covers the payment +tables, in the same transaction as the facade tables. +`adapter serve` without a project (payments only) runs the grant step on its own and also grants +`USAGE` on the schema. +The statements below are equivalent to what it runs for them. +The G2P statements apply when `payments.yaml` declares disbursement connections, and only the +grants the role still lacks are issued: + +```sql +GRANT SELECT, INSERT, UPDATE ON adapter_payment_attempts TO runtime; +GRANT SELECT, INSERT ON adapter_payment_commands, adapter_payment_events TO runtime; +GRANT USAGE ON SEQUENCE adapter_payment_events_sequence_seq TO runtime; + +-- When payments.yaml declares disbursement connections. +GRANT SELECT, INSERT, UPDATE ON adapter_g2p_attempts TO runtime; +GRANT SELECT, INSERT ON adapter_g2p_commands, adapter_g2p_events TO runtime; +GRANT USAGE ON SEQUENCE adapter_g2p_events_sequence_seq TO runtime; -{/* Evidence: crates/registry-adapter/src/serve.rs required, missing_table_privileges; +-- When you serve payments without a project. +GRANT USAGE ON SCHEMA adapter TO runtime; +``` + +When `adapter serve` makes no grant for the reasons below, grant these yourself. +The payment host then refuses to start until the runtime role holds them. + +`adapter serve` makes no automatic grant in two cases: + +- The runtime role lacks a privilege and has members that would inherit it. + `adapter serve` leaves that decision to you: grant the privileges above to the runtime role + yourself, and startup then passes the check. + A member that holds `ADMIN OPTION` on the runtime role and has no members of its own does not + count, because it can already grant the role to itself. + A role with `CREATEROLE` that is not a superuser and created the runtime role is such a member. +- The migration role does not own an object it must grant on, for example a table that an earlier + role created. + PostgreSQL ignores or refuses a grant its issuer has no right to make, so `adapter serve` rolls + the grants back and refuses to start. + Run the statements above as the object's owner, or make the migration role the owner. + +When the runtime role holds every privilege in the migration schema and startup still reports one +missing, the runtime session's search path resolves a different schema. + +{/* Evidence: crates/registry-adapter/src/serve.rs runtime_requirements, grant_runtime_privileges; + crates/registry-adapter/src/payments/store.rs RUNTIME_GRANTS, RUNTIME_SEQUENCE; + crates/registry-adapter/src/payments/g2p_store.rs RUNTIME_GRANTS, RUNTIME_SEQUENCE; + crates/registry-adapter/src/payments/http.rs PreparedPayments; crates/registry-adapter/src/journal.rs RUNTIME_PRIVILEGES; crates/registry-adapter/src/idempotent.rs WRITE_RUNTIME_GRANTS, RECOVERY_RUNTIME_GRANTS, RESUME_RUNTIME_GRANTS; crates/registry-adapter/tests/postgres_journal_retention_served.rs - a_write_runtime_role_without_idempotency_grants_is_refused_by_name, - a_resumable_write_runtime_role_needs_the_recovery_grants_and_serves_on_first_run. */} + serve_grants_exactly_the_required_privileges, single_role_serve_issues_no_grant, + a_runtime_url_naming_public_is_refused_and_grants_nothing, + a_runtime_role_with_members_is_granted_nothing_and_refused, + a_runtime_role_whose_only_member_administers_it_is_granted_its_privileges, + a_provisioned_runtime_role_is_granted_its_privileges, + a_provisioned_runtime_role_with_a_plain_member_is_granted_nothing_and_refused, + an_administrator_with_members_of_its_own_blocks_the_grant, + a_migration_role_that_does_not_own_the_tables_fails_startup_and_grants_nothing, + serve_grants_the_collection_tables_beside_a_project, + serve_grants_the_g2p_tables_when_disbursements_are_declared_beside_a_project, + the_payments_only_host_grants_the_collection_tables_and_schema_usage, + the_payments_only_host_grants_the_g2p_tables_when_disbursements_are_declared, + a_single_role_payments_host_issues_no_grant, + a_payments_runtime_role_with_members_is_granted_nothing_and_refused, + a_migration_role_that_does_not_own_a_payment_table_fails_startup_and_grants_nothing. */} ## Operate an ingestion job @@ -179,8 +299,12 @@ Prepare the source and one destination: narrowly scoped BReg credential. The `kobotoolbox-breg` example is the BReg project that matches the job's mapping and access profile. -4. For the Coordinator job, configure the reviewed event trigger and workflow, provision its signing - key, and keep the host clock within 30 seconds of Coordinator's. +4. For the Coordinator job, configure the reviewed workflow and its event triggers. Provision a separate + private file of 32 to 64 exact key bytes per trigger. Give each receiving Coordinator trigger + the same key file as the job uses for it. + Keep the host clock synchronized with Coordinator's. See + [Signed event to Coordinator](../../configure/adapter-jobs/#signed-event-to-coordinator) + for the runtime key references and rotation. Choose one destination before the first pass. Do not run both jobs against one form, and do not fall back from a refusal to the other destination. @@ -750,6 +874,26 @@ The stop report prints the same fix as its `next` step. {/* TODO[evidence]: no test names adapter.job.page-bytes-bound or the maximumRowsPerPage times maximumRowBytes memory ceiling; only the code that raises the stop is cited. */} +## Probe health and readiness + +The facade listener answers two probes without authentication, for load balancers and +orchestrators: + +- `GET /health` answers 200 `{"status":"ok"}` and does no work. +- `GET /ready` answers 200 `{"status":"ready"}` when the journal migrations match the binary + and the runtime role holds its journal privileges, and 503 `{"status":"not-ready"}` otherwise. + It reads the journal store and never contacts a source. + +The bodies are fixed and do not vary with the project. They tell a caller that an Adapter is +listening and whether its journal is usable, and nothing more. Because `/health` and `/ready` +belong to the listener, a project operation whose path is one of them is unserved, with the +reason code `adapter.operation.reserved-facade-path` in the effective contract. + +{/* Evidence: crates/registry-adapter/src/facade.rs; + crates/registry-adapter/src/journal.rs ready; + crates/registry-adapter/tests/health_routes.rs; + crates/registry-adapter-engine/src/load.rs ReservedFacadePath. */} + ## Scrape metrics Neither the facade listener nor the hook ingress serves metrics. Set `metricsListener.bind` in the @@ -771,6 +915,7 @@ Facade series: | --- | --- | --- | --- | | `adapter_http_requests_total` | counter | `route` (route template, or `unmatched`), `method`, `status` (`1xx`, `2xx`, `3xx`, `4xx`, `5xx`, `other`) | Answered facade requests. | | `adapter_upstream_failures_total` | counter | `class` (`upstream`, `upstream.http`, `upstream.timeout`, `upstream.connection`, `upstream.malformed`, `upstream.too-large`, `upstream.redirect`, `breaker.open`, `throttle.rejected`, `credential.rejected`, `egress.refused`) | Calls to the source that failed, by error class. It counts failed exchanges, status polls, bounded-wait polls and recovery checks. | +| `adapter_request_refusals_total` | counter | `check` (the 45 shared failed-check labels, all present at zero, for example `credential-missing`, `token-signature`, `scope`, `operation`, `ownership`, `visibility`) | Facade and payment requests refused, by the check that failed. Each refusal also writes one `request refused` log line carrying `failed_check` and no caller value, at most five lines per check per minute. | | `adapter_journal_write_failures_total` | counter | none | Audit journal writes that failed, so the exchange answered an internal error. Custody and rendering failures are not counted here. | | `adapter_retention_sweep_failures_total` | counter | `store` (`journal`, `idempotency`, `other`) | Retention sweep batches that failed and were left to the next tick. | @@ -782,6 +927,7 @@ Job host series: | `adapter_job_last_successful_pass_age_seconds` | gauge | none | Seconds since a pass in this process settled its page. Absent until the first such pass. | | `adapter_job_pass_failures_total` | counter | `reason` (`page-fault`, `destination-stop`, `refusal-limit`, `store-unreachable`) | Passes that did not settle, and passes that could not reach the store. A pass that finds another process holding the lease is not a failure and is not counted. | | `adapter_job_hook_refusals_total` | counter | `reason` (`not-found`, `method`, `unauthenticated`, `rate-limited`, `unavailable`, `body-timeout`, `body-too-large`, `body-unreadable`) | Hook requests the ingress refused. | +| `adapter_job_request_refusals_total` | counter | `check` (the 45 shared failed-check labels, all present at zero. The hook ingress records `credential-missing`, `credential-malformed`, `shared-secret` and `rate-limit`) | Hook requests refused for a credential or the rate limit, by the check that failed. Each refusal also writes one `request refused` log line carrying `failed_check` and no caller value, at most five lines per check per minute. Present when the host is built with `job-hook`. | | `adapter_job_gauge_sample_failures_total` | counter | none | Item count reads that failed or timed out. | When the store cannot be read at scrape time, `adapter_job_items` carries no samples and diff --git a/docs/site/src/content/docs/operate/advanced/back-up-and-restore.mdx b/docs/site/src/content/docs/operate/advanced/back-up-and-restore.mdx index 56d8a2bfe1..310601baa0 100644 --- a/docs/site/src/content/docs/operate/advanced/back-up-and-restore.mdx +++ b/docs/site/src/content/docs/operate/advanced/back-up-and-restore.mdx @@ -246,8 +246,8 @@ Once the copy serves, work through these: `. The same 24-hour acceptance window applies. See [What cannot be undone](../../breg-retention/#what-cannot-be-undone). - **Hooks.** Deliveries still pending at the backup point are sent again once the copy serves, - under the same `Idempotency-Key` they carried the first time, so a receiver that deduplicates by - that key accepts each one once. Their attempt count is rewound with the rest of the row, so the + under the same `webhook-id` they carried the first time, so a receiver that deduplicates on it + accepts each one once. Their attempt count is rewound with the rest of the row, so the audit records the same attempt number for each of them twice. Deliveries completed before the backup point are not sent again, and delivered events are not recalled. Inspect what is pending with `bregctl hook list`; see [Inspect and recover deliveries](../../breg-webhooks/#inspect-and-recover-deliveries). @@ -268,11 +268,10 @@ Once the copy serves, work through these: {/* Evidence: docs/site/src/content/docs/operate/breg-retention.mdx, "Erasure does not reach backups"; crates/registry-breg/src/action_evidence_client.rs, ACTION_EVIDENCE_RETENTION_SECONDS; crates/registry-bregctl/src/lib.rs, EvidenceRetentionEraseArgs; - crates/registry-platform-hooks/src/delivery/service.rs, delivery_idempotency_key() (derived - from the event, delivery, generation, payload digest, and destination binding digest); + crates/registry-platform-hooks/src/delivery/service.rs, delivery_header_values() (`webhook-id` is the event id); crates/registry-breg/src/review_recovery.rs, module docs; products/breg/scripts/test-backup-restore.sh, checkpoints "re-sending only the delivery pending - at the backup point" (the same idempotency key, no second delivery of delivered work) and + at the backup point" and "continuing the audit stream in the same files" (the prefix kept, the pending delivery recorded twice, one adoption entry); products/casework/scripts/test-backup-restore.sh, checkpoint "recovering the review the restore lost through the registry" (result-unknown-to-authority, diff --git a/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx b/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx index 7e830e8b7e..8571bdfe56 100644 --- a/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx +++ b/docs/site/src/content/docs/operate/advanced/rotate-credentials-and-trust.mdx @@ -80,7 +80,7 @@ server's metadata publishes it (RFC 10070 section 4). {/* Evidence: crates/registry-adapter-engine/src/egress.rs, EndpointEgress, authorize, and maximum_cache_seconds; crates/registry-platform-config/src/secrets.rs, read_secret_file, - validate_file_metadata, and read_environment; + judge_file, and read_environment; crates/registry-evidencectl/src/runtime.rs, without_audit_lock; crates/registry-evidence/src/bundle.rs, RuntimeDocument and ca_bundles; products/evidence/reference/request-adapter/deployment-projects/SOURCE-CREDENTIAL-ROTATION.md; diff --git a/docs/site/src/content/docs/operate/breg-changes.mdx b/docs/site/src/content/docs/operate/breg-changes.mdx index 880f167012..f167338368 100644 --- a/docs/site/src/content/docs/operate/breg-changes.mdx +++ b/docs/site/src/content/docs/operate/breg-changes.mdx @@ -144,7 +144,9 @@ require a frozen Proposal to be rebased even when the migration needs no review. crates/registry-breg/src/package.rs, compare_actions(); crates/registry-breg/tests/refactor_contract.rs. */} -A reviewed migration is a directory you write and keep beside the project. Each migration lives at +A reviewed migration is a directory you keep beside the project. When every change is an access or +disclosure change that touches no table, column, or index, [draft it with `bregctl`](#draft-a-migration-that-needs-no-sql). +Otherwise you write it. Each migration lives at `modules//migrations//` and holds a `descriptor.json`, a `rehearsal.json`, and any SQL steps, assertions, or fixtures the descriptor names. Every path inside it is relative to the directory root. The descriptor covers exactly the changes `diff` reported that are not compatible @@ -180,8 +182,8 @@ lists every key with its values and bounds. The rehearsal receipt, `rehearsal.json`, binds the migration to the exact baseline and candidate: the prior package digest and schema fingerprint, the descriptor's `planDigest`, the digest of every SQL file and fixture, the PostgreSQL major version, the row counts your rehearsal observed, and the -candidate's final schema fingerprint. You write it from your own rehearsal; `bregctl` checks it and -does not generate it. Two commands give you the values it needs: +candidate's final schema fingerprint. For a migration with SQL you write it from your own +rehearsal, and `bregctl` checks it. Two commands give you the values it needs: ```sh test-skip="needs the reader's reviewed migration directory and disposable database" jq -jcS . descriptor.json | shasum -a 256 @@ -198,6 +200,44 @@ fingerprint, and rolls back without writing a receipt. crates/registry-bregctl/src/test_lifecycle.rs, measure(). Refusal and descriptor observed with bregctl 0.42.0 on a disposable PostgreSQL 17. */} +## Draft a migration that needs no SQL + +`bregctl migration draft` writes the descriptor and the rehearsal receipt for a successor whose +changes are access or disclosure changes that alter no table, column, or index. Examples are an +access profile, a route, a query, or an Action. The successor may also add compatible-additive +changes, such as an optional field. The registry applies those through its own additive plan, so a +reviewed migration never covers them and the draft leaves them out. The draft covers every other +change. It installs the candidate on the disposable database to measure its schema fingerprint and +the PostgreSQL major version, and binds both to the verified baseline package: + +```sh test-skip="needs the reader's baseline package and disposable database" +bregctl migration draft ./directory \ + --baseline-package /srv/registry/build-1/package \ + --runtime-config /srv/registry/runtime-test.yaml \ + --output /srv/registry/reviewed-migrations \ + --module directory --id describe-email-update +``` + +It prints the covers it wrote and the directory, +`modules/directory/migrations/describe-email-update/`, under `--output`. Read the covers against +`diff`, then pass the same directory as `--reviewed-migrations`. The package validator still checks the +coverage and the evidence when you run `test` and `package`. + +The command refuses before it reads the runtime configuration or opens a database when: + +- `migration.draft.nothing-to-review`: every change is compatible additive, so no migration is needed. +- `migration.draft.sql-required`: a change needs authored SQL, a backup binding, or a descriptor of + another class. Write that migration by hand as above. The refusal names the first such change. +- `migration.draft.module-unknown`: the project has no module with that identifier. +- `migration.draft.output-exists`: the migration directory already exists. A draft never overwrites + one, so choose another `--id` or review the existing directory. +- `migration.draft.id-invalid`: `--id` is not a local identifier. +- `migration.draft.output-invalid`: `--output` is not an absolute path, or holds a `..` component or a symbolic link. + +{/* Evidence: crates/registry-bregctl/src/migration_draft.rs, run() and plan_covers(); + crates/registry-bregctl/tests/migration_draft.rs; + products/breg/scripts/test-adopter-workflow.sh, the drafted review of the readable-field successor. */} + ## Test and package the successor Pass the active package directory as `--baseline-package` to both `test` and `package`, and the @@ -206,7 +246,7 @@ reviewed migration directory as `--reviewed-migrations` when there is one: ```sh test-skip="needs the reader's disposable database and schema-test credentials" bregctl test ./directory \ --baseline-package /srv/registry/build-1/package \ - --reviewed-migrations ./reviewed-migrations \ + --reviewed-migrations /srv/registry/reviewed-migrations \ --runtime-config /srv/registry/runtime-test.yaml \ --credentials /srv/registry/schema-test-credentials.yaml \ --output /srv/registry/build-2/schema-test-receipt.json diff --git a/docs/site/src/content/docs/operate/breg-monitor.mdx b/docs/site/src/content/docs/operate/breg-monitor.mdx index 991f8bb634..abac5fb0ea 100644 --- a/docs/site/src/content/docs/operate/breg-monitor.mdx +++ b/docs/site/src/content/docs/operate/breg-monitor.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: how-to locale: en standards_referenced: [] @@ -161,11 +161,12 @@ curl -s http://127.0.0.1:9464/metrics ``` After one readiness probe and two requests without a token, the scrape held these samples (help -text and histogram lines omitted): +text and histogram lines omitted, and the other 44 `breg_request_refusals_total` checks showing 0): ```text breg_http_requests_total{route="/ready",method="GET",status="success"} 1 breg_http_requests_total{route="/v1/records/facilities",method="GET",status="client-error"} 2 +breg_request_refusals_total{check="credential-missing"} 2 breg_pool_connections{state="maximum-size"} 4 breg_pool_connections{state="size"} 3 breg_pool_connections{state="available"} 3 @@ -338,6 +339,37 @@ with one of the `breg.external-refresh.*` codes in [Troubleshooting](#troublesho crates/registry-breg/src/subject_access_log.rs, run_retention(); crates/registry-platform-hooks/src/delivery/service.rs, WORKER_POLL_INTERVAL. */} +## Watch refused requests + +`breg_request_refusals_total{check}` counts the requests Base Registry Engine (BReg) refused, by the check that refused +it, since the process started. Every `check` value is published from the first scrape at zero, so a +rate needs no `absent()` guard. A missing or refused credential, a refused token, an unreachable +key source and a refused review completion callback all count. So does a request answered +`404 resource.not_found` because the caller may not see the target (a missing scope or purpose, a +row outside the caller's boundary, a refused task grant, a field beyond the profile), and a write +refused as outside the caller's boundary. A batch of Proposal review contexts answers `200`, and +each concealed item counts once under its own check. A `412` for a stale version and a request for an unknown route are not counted. A failed field guard counts under `action-guard`, also when it answers the generic `412`. + +Each refusal also writes one `request refused` line at `INFO` level with `failed_check` and the +request's trace id, at most five lines per check per minute across the process. At `BREG_LOG=warn` +no line is written, and the counter still counts. The next line for that check carries +`suppressed`, the number of refusals the minute counted but did not log, so alert on the counter, +not the log. The counter and the line carry only a fixed check name, never a token, claim, client +or subject value. Counting changes nothing the caller receives. + +A rising `credential-missing` or `credential-malformed` count usually means a caller sends no +token or a broken one. A rising `key-source-unavailable` count means BReg cannot read or use the +issuer's keys; check the issuer before the callers. + +{/* Evidence: crates/registry-breg/src/correlation.rs, finish_response(); + crates/registry-breg/src/metrics.rs, + the_refusal_counter_declares_every_check_and_publishes_it_at_zero; + crates/registry-breg/tests/authentication_refusals.rs, + every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire; + crates/registry-breg/tests/concealment_refusals.rs, + every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire; + crates/registry-platform-authcommon/src/refusal.rs, the recorder's per-check window. */} + ## Read audit records Each audit record names its schema. @@ -430,9 +462,9 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa | `startup.runtime-role.grants-missing` | The runtime role lost a grant. | Apply the active package again. | | `startup.role-mode.changed` | The ledger records split roles; the file names one. | Restore the runtime role. | | `apply.successor.roles-differ` | The file names other roles than the active activation. | Apply the active package under the new roles, then the successor. | -| `startup.audit.refused` | The audit destination or hash key was refused. | Secret files are regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | +| `startup.audit.refused` | The audit destination or hash key was refused. | Secret files meet the [secret file rule](../../security/hardening-checklist/#secret-files), for example regular, owned by the running user, mode `0400` or `0600`, with one link. The audit directory and its files are owned by the running user, the directory `0700`. | | `startup.cursor.refused` | The cursor secret was refused. | As above. | -| `startup.oidc.refused` | The issuer's key set could not be loaded. | Check that this host reaches and trusts the issuer. | +| `startup.oidc.refused` | The issuer's key set could not be loaded, or a pinned static key set was refused. | Check that this host reaches and trusts the issuer. For a pinned key set refused by the shared key rules, the message names the rule and, for a rule about one key, its position: correct that key. A key set refused by BReg's own rules (`use`, `key_ops`, a denied `kid`, the algorithm, or the number of keys) gets the general OIDC message: check those members. | | `authentication.refused` | A token was refused. | Check [what a token must carry](../breg/#what-a-token-must-carry); `aud` may be a list of up to 16 that includes the audience. | | `breg.runtime.invalid-metrics-listener` | `metricsListener.bind` is invalid. | See [Scrape metrics](#scrape-metrics). | | `postgres.connections.pool-over-half` | One pool may take over half the connections. | Lower the pool or raise `max_connections`. | @@ -458,7 +490,9 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa | `apply.migration.statement-failed` | PostgreSQL refused a statement; the SQLSTATE is named. | Fix the cause and retry, or run `migration reconcile`. | | `apply.migration.failed` | The apply failed mid-maintenance. | Retry the same target, or run `migration reconcile`. | | `apply.hook-destinations.refused` | Destinations and bindings do not match. | Compare `destinations.hooks` with `bregctl explain events`. | -| `startup.hook-destinations.refused` | A destination binding was refused. | Check the key file, the origin, and `allowedPrivateCidrs`. | +| `startup.hook-destinations.refused` | A destination binding was refused. For key failures, the message names the key path. | Follow the action in the message or check the origin and `allowedPrivateCidrs`. | +| `breg.runtime.invalid-delivery-key` | A review authority completion key could not be resolved or failed the key policy. | Correct the key reference or supply the exact bytes as the message directs. | +| `breg.runtime.duplicate-completion-recipient` | Two review authority completion blocks select the same recipient. | Give each authority a distinct `completion.recipientBinding`. | | `startup.hook.retained-bindings` | Pending deliveries need a removed binding. | Restore it until `hook list` shows them drained. | | `startup.instance-id.pending-deliveries` | Pending deliveries carry the previous `identity.instanceId`. | Restore it until they drain. | | `migration.review.*` | The reviewed migration directory was refused. | See [write a reviewed migration descriptor](../breg-changes/#write-a-reviewed-migration-descriptor). | @@ -518,7 +552,7 @@ Find the code the command, log, or HTTP problem printed. A `*` stands for any pa crates/registry-bregctl/src/lib.rs, data command failures, import_authority_failure(), instance_claim_failure(), apply_lifecycle_failure(); crates/registry-breg/src/migration.rs; crates/registry-breg/src/auth.rs, MAX_AUDIENCES; - crates/registry-platform-config/src/secrets.rs, validate_file_metadata(); + crates/registry-platform-config/src/secrets.rs, judge_file(); crates/registry-breg/src/startup.rs, DynamicRuntimeReadiness; crates/registry-breg/src/postgres/context.rs, begin_registry_transaction(); crates/registry-breg/tests/postgres_startup.rs, diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index 5c29a97c8d..98cea0d321 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -211,6 +211,7 @@ destinations: dnsFamily: dual-stack-strict allowedPrivateCidrs: [] hmacSha256KeyRef: secret:file/contact-events-key + # previousHmacSha256KeyRef: secret:file/contact-events-key.previous classificationCeiling: internal deliveryCeilings: attemptTimeoutMilliseconds: 1000 @@ -236,7 +237,7 @@ Some values need a decision: `bregctl --format json explain events ` shows what the package compiled for each delivery: by default five attempts of five seconds each, retried after 1, 2, 4, and 8 seconds, then -a dead letter. Retries keep the event id and idempotency key. Any `2xx` response acknowledges a +a dead letter. Retries and replays keep the event id, sent as `webhook-id`. Any `2xx` response acknowledges a delivery; redirects, timeouts, and every other response are retried. The [configuration reference](../../reference/breg-configuration/) lists every key, including `retention.hookPayloadRetentionDays`. @@ -244,7 +245,7 @@ delivery; redirects, timeouts, and every other response are retried. The Run `bregctl doctor` after every change to this block. It opens each binding, key file included, before the runtime starts. -{/* Evidence: crates/registry-breg/src/event_destination.rs, EventDestinations::activate() +{/* Evidence: crates/registry-breg/src/event_destination.rs, ActivatedEventDestinationRegistry::activate() (InventoryMismatch, DeliveryCeilingWidening), RawEventDestinationConfig, digest_value() for the tls keys; crates/registry-platform-httputil/src/destination.rs, origin_uses_localhost_namespace(); @@ -252,7 +253,7 @@ before the runtime starts. crates/registry-breg/src/hooks.rs; crates/registry-bregctl/src/doctor.rs, startup.hook-destinations.refused. */} -## Provision the shared key +## Provision one key per destination Generate the HMAC-SHA-256 key as an owner-only file in the runtime's secret directory, as the user that runs `breg`: @@ -261,13 +262,23 @@ that runs `breg`: (umask 077; openssl rand -hex 32 | tr -d '\n' > /var/lib/breg/secrets/contact-events-key) ``` -Give the receiver the same bytes through its own secret store. BReg signs with the file's bytes -exactly as written, so the receiver loads the 64 characters as its key and does not decode them. -The key must be at least 32 bytes, and the file a regular file owned by the user that runs `breg` -with mode `0400` or `0600`; `doctor` and startup refuse anything else. +Give this destination's receiver the same file through its secret store. BReg uses the 32 to 64 +key bytes exactly as written. The recipe produces 64 hexadecimal characters that the receiver +loads directly as its key. Use a regular file owned by the user that runs `breg`, with mode `0400` +or `0600`. Startup refuses a key reused across destinations or with a review completion and names +both configuration paths. The signature covers the webhook ID, the timestamp and the body but not +the URL, so a delivery signed with a key two destinations share could be replayed to the other one. +See [Use a separate key for each destination](../../reference/delivery-signing/#use-a-separate-key-for-each-destination). -{/* Evidence: crates/registry-platform-crypto/src/delivery_signature.rs, MIN_HMAC_SHA256_KEY_BYTES; - crates/registry-platform-config/src/secrets.rs, read_secret_file() and validate_file_metadata(). */} +To rotate a key stored through a `secret:file` reference, copy the current file to a new name and +reference the copy as `previousHmacSha256KeyRef`. Write new bytes to the file +`hmacSha256KeyRef` references, then restart BReg so it signs with both keys. Once the receiver +has the new key, remove the previous reference and restart BReg. + +{/* Evidence: crates/registry-breg/src/event_destination.rs, resolve_delivery_keys(), digest_value(); + crates/registry-breg/tests/runtime_config.rs, a_previous_destination_key_leaves_the_binding_digest_unchanged, + a_completion_key_equal_to_a_destination_key_is_refused_naming_both_paths; + crates/registry-platform-config/src/secrets.rs, read_secret_file() and judge_file(). */} ## Build the receiver against a sample @@ -283,19 +294,11 @@ Built the sample delivery. The canonical request follows. event contact-created-v1 POST HTTP/1.1 -Accept: application/json -Content-Type: application/json -Idempotency-Key: sha256:0000000000000000000000000000000000000000000000000000000000000000 -X-Registry-Delivery-Attempt: 1 -X-Registry-Delivery-Time: 2026-01-01T00:00:00Z -X-Registry-Event-Generation: 1 -X-Registry-Signature: v1= -ce-dataschema: urn:breg:event-schema:local-directory:contact:contact-created-v1:sha256:644104a736a00be2962cf3682f869cc1a6d17b101a2d747927302dddb49d9f34 -ce-id: 00000000-0000-4000-8000-000000000001 -ce-source: urn:registrystack:registry:local-directory:instance: -ce-specversion: 1.0 -ce-time: 2026-01-01T00:00:00Z -ce-type: contact-created-v1 +accept: application/json +content-type: application/json +webhook-id: 00000000-0000-4000-8000-000000000001 +webhook-signature: v1, +webhook-timestamp: 1767225600 {"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{"packageRevision":"sha256:0000000000000000000000000000000000000000000000000000000000000000","recordId":"00000000-0000-4000-8000-000000000002","recordType":"contact","revision":1,"trigger":"created","values":{"name":"x"}},"dataschema":"urn:breg:event-schema:local-directory:contact:contact-created-v1:sha256:644104a736a00be2962cf3682f869cc1a6d17b101a2d747927302dddb49d9f34","id":"00000000-0000-4000-8000-000000000001","source":"urn:registrystack:registry:local-directory:instance:","subject":{"recordReference":"hmac-sha256:0000000000000000000000000000000000000000000000000000000000000002","recordRevision":1},"time":"2026-01-01T00:00:00Z","type":"contact-created-v1"} ``` @@ -307,16 +310,19 @@ document with the method, request target, headers, body, and canonical body. The receiver should: -1. Verify `X-Registry-Signature` against the exact request bytes, in the signing-input order the - [API reference](../../reference/breg-api/#events-and-webhooks) defines. -2. Check `X-Registry-Delivery-Time` for freshness. -3. Read the Record type from `data.recordType` and the record from `data.recordId`, and order - events for one record by `data.revision`. -4. Deduplicate by `Idempotency-Key`, and answer `2xx` only after it has durably recorded the event. +1. Verify `webhook-signature` over `webhook-id.webhook-timestamp.body` using the exact body bytes. + See the [delivery signing reference](../../reference/delivery-signing/). +2. Check that `webhook-timestamp` is within 300 seconds of the receiver clock in either direction. +3. Read the Record type from `data.recordType` and the record from `data.recordId`. Use + `data.revision` to order events for one record. +4. Deduplicate by `webhook-id` and answer `2xx` after recording the event durably. + +The [client API reference](../../reference/client-api/) describes the client verifiers. {/* Evidence: crates/registry-bregctl/src/lib.rs, HookSampleArgs and hook_sample(); crates/registry-bregctl/src/hook_lifecycle.rs, sample() and synthetic_field_value(); - crates/registry-breg/src/hooks.rs. */} + crates/registry-platform-crypto/src/delivery_signature.rs, verify(), DELIVERY_TOLERANCE; + crates/registry-platform-hooks/src/receiver.rs, verify_hook_delivery(). */} ## Settle local hooks before go-live @@ -476,10 +482,10 @@ Queued the delivery for replay. generation 2 ``` -Replay keeps the event id and issues a new generation and idempotency key. If you are not sure -whether the receiver acted on an earlier attempt, check its state before replaying. A replay whose +Replay keeps the event id. A receiver that already recorded that `webhook-id` acknowledges it +without acting again. Use replay for deliveries the receiver never recorded. A replay whose generation is stale, whose payload has expired, or whose destination is no longer bound is refused -with `hook.operation.refused`; list again and use the current generation. +with `hook.operation.refused`. List again and use the current generation. ### Discard deliveries pinned to an old binding @@ -530,4 +536,4 @@ When `doctor` or a webhook command refuses, look up its diagnostic code in delivery end to end on a local registry. - [Author a registry project](../../configure/breg/) for the Record types that declare events. - [Base Registry Engine API reference](../../reference/breg-api/#events-and-webhooks) for the - delivery request, the signing input, and the CloudEvents headers. + delivery request, the signing input, and the signed headers. diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index b195f68b15..6c88e2e40e 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-10-17" +last_reviewed: "2026-11-27" doc_type: how-to persona: - operator @@ -46,8 +46,9 @@ occupied by the link; choose another unused, non-symbolic-link name under the re - **PostgreSQL 17 or newer**, reached over TLS, with two login roles: a migration role that owns the schema and applies packages, and a runtime role the serving process uses. A project with a `crs84-polygon` field always needs PostGIS 3.5 or newer. A `crs84-point` field needs PostGIS only - when an access profile grants bbox queries. Your administrator creates the roles, schemas, and - extensions. The product never creates any of them. SQLite is not a target. + when an access profile grants bbox queries. `bregctl provision` creates the roles, the database, the + schemas, and the extensions from an administrator's credentials. `breg` and `apply` create none + of them. SQLite is not a target. Ubuntu 24.04 ships PostgreSQL 16 and Debian 12 ships PostgreSQL 15, both too old: install 17 from the PostgreSQL project's apt repository (PGDG), or run the `postgres:17` image (`postgis/postgis` at PostgreSQL 17 when the project requires PostGIS). @@ -138,81 +139,6 @@ the tag. [Serve the container image](#serve-the-container-image) shows how to ru {/* Evidence: crates/registry-breg/install.sh; release/docker/Dockerfile.breg; release/scripts/release_candidate.py, BREG_RUNTIME_IMAGE_NAMES; release/VERIFY.md. */} -## Provision PostgreSQL - -As a PostgreSQL administrator, create the two roles: - -```sql -CREATE ROLE registry_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -CREATE ROLE registry_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE - NOINHERIT NOBYPASSRLS PASSWORD ''; -``` - -Two separate roles are the split role mode, which production uses. The serving process then cannot -write the activation ledger or registry state, and `apply` and startup both refuse a runtime role -that could, naming the grant, ownership, membership, or trigger to remove. Keep the migration -credential off the serving host when no activation is in progress. - -Create two databases with the same shape: the serving database and the schema-test database. In -each, as the administrator (this is the serving database, `registry`): - -```sql -CREATE DATABASE registry; -REVOKE ALL ON DATABASE registry FROM PUBLIC; -REVOKE CREATE ON DATABASE registry FROM registry_migration, registry_runtime; -GRANT CONNECT ON DATABASE registry TO registry_migration, registry_runtime; -\connect registry -CREATE EXTENSION IF NOT EXISTS btree_gist; -CREATE SCHEMA registry_internal AUTHORIZATION registry_migration; -CREATE SCHEMA registry_data AUTHORIZATION registry_migration; -CREATE SCHEMA registry_source AUTHORIZATION registry_migration; -CREATE SCHEMA registry_derived AUTHORIZATION registry_migration; -CREATE SCHEMA registry_context AUTHORIZATION registry_migration; -REVOKE ALL ON SCHEMA registry_internal, registry_data, registry_source, - registry_derived, registry_context FROM PUBLIC; -``` - -The package creates every table, function, and policy inside those five schemas. A missing -prerequisite surfaces at `test` or `apply`, never at runtime. - -The migration role owns only those five schemas. It must not own the database (for example through -`CREATE DATABASE registry OWNER registry_migration`) and must not hold `CREATE` on it, because an -owner holds `CREATE` implicitly. `test` and `apply` check this before changing anything and refuse -with `migration role has database-level administrative authority`, which is also the refusal for a -role that is a superuser or has `BYPASSRLS`, `CREATEDB`, or `CREATEROLE`. If a managed PostgreSQL -service created the database for you, check its owner and its grants first. - -For a project with polygon storage or bbox queries, install PostGIS in a schema neither registry -role owns. If the project grants bbox queries, also add a bounding-box role named after the runtime -role with the suffix `__spatial_bbox`: - -```sql -CREATE ROLE registry_runtime__spatial_bbox NOLOGIN NOSUPERUSER NOCREATEDB - NOCREATEROLE NOINHERIT NOBYPASSRLS; -GRANT registry_runtime__spatial_bbox TO registry_migration - WITH INHERIT FALSE, SET TRUE, ADMIN FALSE; --- in each database -CREATE SCHEMA registry_spatial_ext AUTHORIZATION postgres; -CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext; -REVOKE CREATE ON DATABASE registry FROM PUBLIC, registry_migration, registry_runtime; -REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC; -GRANT USAGE ON SCHEMA registry_spatial_ext - TO registry_migration, registry_runtime, registry_runtime__spatial_bbox; -``` - -A package that stores polygons and grants no bbox queries omits the bbox role, its membership, and -its name from the final `GRANT USAGE`. Keep the PostGIS schema, extension, and grants to the -migration and runtime roles. - -Size connections, timeouts, and statement statistics once the registry serves; see -[Set a PostgreSQL baseline](../breg-monitor/#set-a-postgresql-baseline). - -{/* Evidence: crates/registry-breg/src/postgres/migration_ledger.rs, RoleMode; - crates/registry-breg/src/postgres/roles.rs, verify_migration_role, - find_runtime_write_authority and the __spatial_bbox role; crates/registry-breg/src/postgres/schema.rs, - refuse_existing_managed_objects(); crates/registry-breg/src/startup.rs, RuntimeWriteAuthority. */} - ## Write the runtime configuration The runtime file binds one package to one database, one token issuer, and one listener. It is a @@ -304,9 +230,9 @@ the metrics listener in [Scrape metrics](../breg-monitor/#scrape-metrics). ### Create the secret files -Create the files as the user that runs `breg` and the operator commands, because the resolver -refuses a file owned by anyone else. Each must be a regular file with mode `0400` or `0600`, with -no other hard link and no symbolic link to it. A name starts with a lowercase letter and uses +Create the files as the user that runs `breg` and the operator commands. Each must meet the +[secret file rule](../../security/hardening-checklist/#secret-files): for example a regular file +you own with mode `0400` or `0600` and no other hard link. A name starts with a lowercase letter and uses lowercase letters, digits, `.`, `_`, and `-`. The bytes are used exactly as written, so write them without a trailing newline: @@ -329,11 +255,154 @@ In a container platform that injects secrets as environment variables, declare `secretProviders.environment` and write `secret:env/` instead. {/* Evidence: crates/registry-platform-config/src/secrets.rs, read_secret_file(), - validate_file_metadata(), read_environment(); crates/registry-platform-yaml/src/secret.rs, + judge_file(), read_environment(); crates/registry-platform-yaml/src/secret.rs, valid_file_name(); crates/registry-platform-audit/src/lib.rs, MIN_AUDIT_SECRET_BYTES; crates/registry-breg/src/cursor.rs, ROOT_SECRET_MIN_BYTES; crates/registry-breg/src/runtime_config.rs, database_connection_config_for(). */} +## Provision PostgreSQL + +Your runtime file already names the roles, their passwords, and the database. They are the URLs +in `database.migrationUrlRef` and `database.runtimeUrlRef`, and the roles under `database.roles`. +With the secret files in place, run `bregctl provision` once as a PostgreSQL role that can create +roles and databases. The runtime file's `package.root` must be a readable directory, though +`provision` reads nothing from it: create an empty one if the package does not exist yet. + +```sh +bregctl provision --runtime-config /etc/breg/runtime.yaml --admin-url-file /etc/breg/admin-url +``` + +The `admin-url` file holds one PostgreSQL URL for that administrator, for example +`postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` +and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable +instead, use `--admin-url-env NAME`. The connection requires TLS and verifies the server +certificate. Set `database.caBundleRef` in the runtime file to trust a private CA. The command +never prints the administrator URL or a password. + +The administrator URL must name the same host and port as the two product URLs, or `provision` +refuses it as `platform.provision.target-mismatch`. It must also name a database other than the +product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. +Where the administrator may connect only to the product database, `provision` cannot run: add +`--print-sql` and give the script to the person who administers the server. + +The command: + +- Creates the migration role and the runtime role, each with `LOGIN` and no other privilege. +- Creates the database and closes it to `PUBLIC`. +- Grants both roles `CONNECT` on the database. +- Installs `btree_gist`. +- Creates the five schemas the package fills, `registry_internal`, `registry_data`, + `registry_source`, `registry_derived`, and `registry_context`, each owned by the migration role + and closed to `PUBLIC`. + +Run it again at any time. It creates only what is missing. It refuses a role that exists with +other attributes, and a role whose URL does not open a session, and tells you which. + +Two roles are the split role mode, which production uses. The serving process then cannot write +the activation ledger or registry state, and `apply` and startup both refuse a runtime role that +could, naming the grant, ownership, membership, or trigger to remove. Keep the migration +credential off the serving host when no activation is in progress. + +The schema-test database that `test` needs has the same shape. Point a copy of the runtime file +at it, as [Check, test, package](#check-test-package) describes, and run `provision` over that +copy too. + +If a database administrator must run the SQL, add `--print-sql` and leave out the administrator +flags. The command connects to nothing and prints the script. Each `CREATE ROLE` is followed by a +`\password` line that prompts for the password in `psql`, so the script holds no password: + +```sql +-- provision script, product breg. Nothing was run. +-- For a server where these objects do not exist yet. Review, then run with psql as an +-- administrator that has CREATEROLE and CREATEDB. It stops at the first error. +\set ON_ERROR_STOP on +SET createrole_self_grant = 'set,inherit'; +CREATE ROLE "registry_migration" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "registry_migration" +CREATE ROLE "registry_runtime" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; +\password "registry_runtime" +CREATE DATABASE "registry" WITH ALLOW_CONNECTIONS false; +REVOKE ALL ON DATABASE "registry" FROM PUBLIC; +GRANT CONNECT ON DATABASE "registry" TO "registry_migration", "registry_runtime"; +ALTER DATABASE "registry" ALLOW_CONNECTIONS true; +\connect "registry" +CREATE EXTENSION btree_gist; +CREATE SCHEMA "registry_internal" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_internal" FROM PUBLIC; +CREATE SCHEMA "registry_data" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_data" FROM PUBLIC; +CREATE SCHEMA "registry_source" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_source" FROM PUBLIC; +CREATE SCHEMA "registry_derived" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_derived" FROM PUBLIC; +CREATE SCHEMA "registry_context" AUTHORIZATION "registry_migration"; REVOKE ALL ON SCHEMA "registry_context" FROM PUBLIC; +``` + +The names come from your URLs. Add `--format json` for a report of each statement and its outcome. + +The migration role owns only those five schemas. It must not own the database (for example through +`CREATE DATABASE registry OWNER registry_migration`) and must not hold `CREATE` on it, because an +owner holds `CREATE` implicitly. `test` and `apply` check this before changing anything and refuse +with `migration role has database-level administrative authority`, which is also the refusal for a +role that is a superuser or has `BYPASSRLS`, `CREATEDB`, or `CREATEROLE`. If a managed PostgreSQL +service created the database for you, check its owner and its grants first. + +`provision` grants the runtime role `CONNECT` on the database, and `USAGE` on the PostGIS schema +when `--package` names a package that needs PostGIS. It grants no `USAGE` on `public`. `apply` +grants the runtime role what serving needs. The package creates every table, function, and policy inside the five schemas. A missing +prerequisite surfaces at `test` or `apply`, never at runtime. + +### Install PostGIS + +For a project with polygon storage or bbox queries, PostGIS lives in a schema neither registry +role owns, and `CREATE EXTENSION postgis` needs a superuser. Pass the built package, and the +command adds the PostGIS steps for a package that needs them: + +```sh +bregctl provision --runtime-config /etc/breg/runtime.yaml \ + --admin-url-file /etc/breg/superuser-url --package /var/lib/breg/build-1/package +``` + +Without `--package`, no PostGIS step is planned. As a role that is not a superuser, the command +stops at that statement with `platform.provision.statement-needs-privilege` at `extension.postgis`. +Run it with `--print-sql` and give the script to a superuser, or run it with a superuser URL, then +run `provision` again. + +A package exists only after `test`, and `test` needs PostGIS in the schema-test database. For that +one database, a superuser runs the PostGIS statements by hand once. If the project grants bbox +queries, the statements also add a bounding-box role named after the runtime role with the suffix +`__spatial_bbox`: + +```sql +CREATE ROLE registry_runtime__spatial_bbox NOLOGIN NOSUPERUSER NOCREATEDB + NOCREATEROLE NOINHERIT NOBYPASSRLS; +GRANT registry_runtime__spatial_bbox TO registry_migration + WITH INHERIT FALSE, SET TRUE, ADMIN FALSE; +-- in each database +CREATE SCHEMA registry_spatial_ext AUTHORIZATION postgres; +CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA registry_spatial_ext; +REVOKE ALL ON SCHEMA registry_spatial_ext FROM PUBLIC; +GRANT USAGE ON SCHEMA registry_spatial_ext + TO registry_migration, registry_runtime, registry_runtime__spatial_bbox; +``` + +For a package that stores polygons and grants no bbox queries, the statements above may leave out +the bbox role, its membership, and its name from the final `GRANT USAGE`. `provision --package` +plans the bbox role for every package that needs PostGIS, including that one. The role is unused +there: the runtime checks for it only when the package grants bbox queries. Keep the PostGIS +schema, extension, and grants to the migration and runtime roles. + +If `provision` stops with `platform.provision.extension-incomplete` at `extension.postgis`, PostGIS +exists in the database but outside `registry_spatial_ext`, or the migration role cannot `SET` the +bbox role. As a superuser, drop a PostGIS installed in another schema, run the statements of the +`extension.postgis` step that `--print-sql` prints, then run `provision` again. + +Size connections, timeouts, and statement statistics once the registry serves; see +[Set a PostgreSQL baseline](../breg-monitor/#set-a-postgresql-baseline). + +{/* Evidence: crates/registry-bregctl/src/provision.rs; crates/registry-platform-provision/src/plan.rs; + crates/registry-breg/src/postgres/migration_ledger.rs, RoleMode; + crates/registry-breg/src/postgres/roles.rs, verify_migration_role, + find_runtime_write_authority and the __spatial_bbox role; crates/registry-breg/src/postgres/schema.rs, + refuse_existing_managed_objects(); crates/registry-breg/src/startup.rs, RuntimeWriteAuthority; + crates/registry-bregctl/tests/provision_postgres.rs. */} + ## What a token must carry The registry verifies a bearer access token before it reads any claim. Configure the issuer so @@ -787,7 +856,7 @@ docker run --restart on-failure \ restart policy's backoff bounds how often. {/* Evidence: release/docker/Dockerfile.breg; crates/registry-breg/src/runtime_config.rs, - ListenerConfig; crates/registry-platform-config/src/secrets.rs, validate_file_metadata(); + ListenerConfig; crates/registry-platform-config/src/secrets.rs, judge_file(); crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path(), require_trusted_ownership(); crates/registry-platform-audit/src/writer.rs, validate_directory(), validate_active_metadata(). */} @@ -816,8 +885,10 @@ container's. `apply` writes audit entries beside `audit.path`, which is why the writable here too. Kubernetes is outside the verified deployment profile. A ConfigMap or Secret volume mounted the -default way presents each key as a symbolic link, which the runtime refuses for both the runtime -file and secret files; inject secrets through `secret:env/` instead. +default way presents each key as a symbolic link, which the runtime refuses for the runtime file. +Secret files accept the link chain Kubernetes writes under the +[secret file rule](../../security/hardening-checklist/#secret-files), which gives the volume +settings that rule needs. {/* Evidence: release/docker/Dockerfile.breg, the bregctl install line and the breg ENTRYPOINT; crates/registry-breg/src/audit.rs, RegistryAudit::open_companion(); diff --git a/docs/site/src/content/docs/operate/casework-retention.mdx b/docs/site/src/content/docs/operate/casework-retention.mdx index 8d933b9482..a264dbca38 100644 --- a/docs/site/src/content/docs/operate/casework-retention.mdx +++ b/docs/site/src/content/docs/operate/casework-retention.mdx @@ -109,6 +109,10 @@ A completion destination is the producer's URL Casework calls when a result is r carries no decision; the producer then reads the result. Each destination is declared under `reviewCompletionDestinations` in the [runtime configuration](../../reference/casework-configuration/#casework-runtime-configuration), keyed by the destination id the producer names in `casework.yaml`. +Casework signs each attempt with a fresh timestamp and the same `webhook-id`. +Deduplicate on that ID even when a retry arrives outside the first attempt's signature +window. [Receive Casework completion wakes](../../configure/casework-completion-receivers/) +describes verification and inbox retention. A failed call returns to the queue and is tried again after `retryDelaySeconds` (default 30), up to `maximumAttempts` (default 12), each attempt bounded by `attemptTimeoutMilliseconds` (default @@ -144,7 +148,7 @@ reason was given. This is the request entry of the decision in [Decide your first ReviewRequest](../../tutorials/first-casework/): ```text -{"schema":"registry-casework-audit/v1","eventId":"","time":"